-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.ts
More file actions
812 lines (743 loc) · 23.2 KB
/
index.ts
File metadata and controls
812 lines (743 loc) · 23.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
import * as Turf from "@turf/turf";
import fs from "fs-extra";
import type { SlackInterface } from "../lib/slack";
import puppeteer from "puppeteer";
import { AteQuizProblem, AteQuizResult } from "../atequiz";
import {
ChatPostMessageArguments,
GenericMessageEvent,
WebClient,
} from "@slack/web-api";
import { increment } from "../achievements";
import { ChannelLimitedBot } from "../lib/channelLimitedBot";
import { Deferred } from "../lib/utils";
import { EventEmitter } from 'events';
const { Mutex } = require("async-mutex");
const { AteQuiz } = require("../atequiz/index.ts");
const cloudinary = require("cloudinary");
const API_KEY = process.env.GOOGLE_MAPS_API_KEY;
const mutex = new Mutex();
const img_size = 1000;
const radius_of_earth = 6378.137;
const postOptions = {
username: "coord-quiz",
icon_emoji: ":globe_with_meridians:",
};
const reNum = /[+-]?(\d+\.?\d*|\.\d+)/;
interface CoordAteQuizProblem extends AteQuizProblem {
answer: [number, number];
zoom: number;
size: number;
}
class CoordAteQuiz extends AteQuiz {
static option?: Partial<ChatPostMessageArguments> = postOptions;
ngReaction: string | null = null;
constructor(
eventClient: EventEmitter,
slack: WebClient,
problem: CoordAteQuizProblem
) {
super(
{ eventClient: eventClient, webClient: slack },
problem,
CoordAteQuiz.option
);
this.answeredUsers = new Set();
}
judge(answer: string, _user: string) {
if (latLngDeformat(answer) === null) {
return false;
}
const [lat, lng] = latLngDeformat(answer);
const [latans, lngans] = this.problem.answer;
const [xm, ym] = latLngToMercator(lat, lng);
const [xmans, ymans] = latLngToMercator(latans, lngans);
const zoom = this.problem.zoom;
const dist = ((Math.PI / 128) * img_size) / 2 / 2 ** zoom;
if (
Math.cos(xm - xmans) >= Math.cos(dist) &&
Math.abs(ym - ymans) <= dist
) {
return true;
} else {
return false;
}
}
solvedMessageGen(post: any): ChatPostMessageArguments {
const message = { ...this.problem.solvedMessage };
const userAnswer = post.text;
const [lat, lng] = latLngDeformat(userAnswer);
const [latans, lngans] = this.problem.answer;
const distance = measureDistance(lat, lng, latans, lngans);
message.text = `<@[[!user]]> 正解:tada:\n中心点の座標は <https://maps.google.co.jp/maps?ll=${latans},${lngans}&q=${latans},${lngans}&t=k|${latLngFormat(
this.problem.answer[0],
this.problem.answer[1]
)}> 、中心点までの距離は${distFormat(
distance
)}だよ:muscle:
`;
message.text = message.text.replaceAll(
this.replaceKeys.correctAnswerer,
post.user as string
);
return message;
}
incorrectMessageGen(post: any): ChatPostMessageArguments {
const message = { ...this.problem.incorrectMessage };
const userAnswer = post.text;
if (latLngDeformat(userAnswer) === null) {
message.text = `<@[[!user]]> 解答形式が間違っているよ:cry:`;
} else {
const [lat, lng] = latLngDeformat(userAnswer);
const [latans, lngans] = this.problem.answer;
const distance = measureDistance(lat, lng, latans, lngans);
message.text = `<@[[!user]]> 不正解:x:\n中心点までの距離は${distFormat(
distance
)}だよ:cry:`;
}
message.text = message.text.replaceAll(
this.replaceKeys.correctAnswerer,
post.user as string
);
return message;
}
waitSecGen(hintIndex: number): number {
return hintIndex === this.problem.hintMessages.length ? 180 : 120;
}
}
const mesHelp = {
text: `使い方`,
blocks: [
{
type: "header",
text: {
type: "plain_text",
text: "使い方",
},
},
{
type: "section",
text: {
type: "mrkdwn",
text: "```座標あて <範囲の1辺の長さ(km)> <国・地域>```\nまたは\n```座標当て <範囲の1辺の長さ(km)> <国・地域>```\nをsandboxチャンネルに打つとクイズが開始されます。答えた緯度と経度の地点がが画像に写っていれば正解です。",
},
},
{
type: "header",
text: {
type: "plain_text",
text: "パラメータ",
},
},
{
type: "section",
text: {
type: "mrkdwn",
text: `*範囲の1辺の長さ*\n出題される問題では正方形(${img_size}px×${img_size}px)の衛星画像が表示されます。その正方形の1辺に対応する地球上の距離を指定できます。単位はkmです。正でない数や10000を超える数が指定された場合と指定がない場合は1000kmに設定されます。`,
},
},
{
type: "section",
text: {
type: "mrkdwn",
text: "*国・地域*\n出題される問題の中心点の位置を国・地域単位で限定できます。国・地域の先頭に-を付けるとその国・地域を除外します。指定がない場合、世界全体が設定されます。-付きの国・地域のみが指定された場合、世界全体からそれらの国・地域を除いた範囲に設定されます。",
},
},
{
type: "header",
text: {
type: "plain_text",
text: "注意点・その他",
},
},
{
type: "section",
text: {
type: "mrkdwn",
text: "画像の中心点は陸上に限定されています。Google Mapのズームの限界値より小さい範囲を指定した場合は、Google Mapのズームの限界値の範囲となります。\n解答では度分秒形式はサポートしていません。35度7分30秒であれば35.125のように小数で答えてください。また、北緯、南緯、東経、西経はそれぞれN, S, E, Wで表し、数字の前につけてください。小文字でもよいです。N, S, E, W, n, s, e, wのいずれもついていない数字は緯度、経度の順で解釈され、それぞれ正の数が北緯あるいは東経、負の数が南緯あるいは西経と解釈します。\n*例*\nN65.4E34.8 → 北緯65.4度東経34.8度\n24.6 -98.4 → 北緯24.6度西経98.4度\nw 178.5,32.9 → 北緯32.9度西経178.5度(wが付いている数字が経度と解釈され、残った数字が緯度と解釈されます。アルファベットの後にスペースがあってもよいです。)\n134.9 s17.6 → 南緯17.6度東経134.9度(sが付いている数字が緯度と解釈され、残った数字が経度と解釈されます。)",
},
},
{
type: "section",
text: {
type: "mrkdwn",
text: "`座標当て countries`あるいは `座標あて countries`と入力すると、対応している国・地域の一覧が見られます。",
},
},
],
};
function countriesListMessageGen(aliases: Record<string, string[]>): any {
const countriesList = countriesExpand(["世界"], aliases)
.filter((country) => country !== "-")
.sort();
const aliasesStringArray = countriesListGen(aliases);
const mesCountries = {
text: "国・地域一覧",
blocks: [
{
type: "header",
text: {
type: "plain_text",
text: "国・地域一覧",
},
},
{
type: "section",
text: {
type: "plain_text",
text: countriesList.join("\n"),
},
},
{
type: "header",
text: {
type: "plain_text",
text: "使用可能な別名",
},
},
...Array.from(aliasesStringArray, (text: string) => {
return { type: "section", text: { type: "mrkdwn", text: text } };
}),
],
};
return mesCountries;
}
function countriesExpand(
countriesOriginal: string[],
aliases: Record<string, string[]>
) {
const countries = countriesOriginal.concat();
let countriesLength = 0;
while (countries.length !== countriesLength) {
countriesLength = countries.length;
for (let i = 0; i < countriesLength; i++) {
if (aliases.hasOwnProperty(countries[i])) {
countries.push(...aliases[countries[i]]);
countries[i] = "-";
}
if (
countries[i].startsWith("-") &&
aliases.hasOwnProperty(countries[i].slice(1))
) {
countries.push(
...Array.from(aliases[countries[i].slice(1)], (x: string) => "-" + x)
);
countries[i] = "-";
}
}
}
return countries;
}
function countriesListGen(aliases: Record<string, string[]>): string[] {
const arr = [];
const aliasesString = [];
let aliasesStringLength = 0;
for (const [key, value] of Object.entries(aliases)) {
const addString = `*${key}* → ${value.sort().join(" ")}`;
if (aliasesStringLength + addString.length <= 2000) {
aliasesString.push(addString);
aliasesStringLength += addString.length;
} else {
arr.push(aliasesString.join("\n"));
aliasesString.splice(0);
aliasesStringLength = 0;
}
}
arr.push(aliasesString.join("\n"));
return arr;
}
async function puppeteerWindow(
latitude: number,
longitude: number,
zoom: number
): Promise<Record<string, any>> {
const browser = await puppeteer.launch({
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
]
});
const page = await browser.newPage();
await page.setViewport({
width: img_size,
height: img_size,
deviceScaleFactor: 1,
});
await page.setContent(
`
<head>
<style>
body {
margin: 0px;
width: ${img_size}px;
height: ${img_size}px;
}
#map_canvas {
width: ${img_size}px;
height: ${img_size}px;
}
</style>
<script async src='https://maps.googleapis.com/maps/api/js?key=${API_KEY}&v=beta&callback=initMap'></script>
<script>
let result;
async function initMap() {
const maxZoomService = new google.maps.MaxZoomService();
const latLng = new google.maps.LatLng(${latitude},${longitude});
await maxZoomService.getMaxZoomAtLatLng(
latLng, (maxZoom) => {result = maxZoom.zoom }
)
const map = new google.maps.Map(
document.getElementById('map_canvas')
, {
center: { lat: ${latitude}, lng: ${longitude}},
zoom: Math.min(${zoom},result),
mapTypeId: 'satellite',
isFractionalZoomEnabled: true,
gestureHandling: 'none',
disableDefaultUI: true,
disableDoubleClickZoom: true,
keyboardShortcuts: false,
scrollwheel: false,
}
);
}
</script>
</head>
<body><div id='map_canvas'></div></body>
`,
{ waitUntil: "networkidle0" }
);
const maxZoom = (await page.evaluate("result")) as number;
const image = (await page.screenshot({
encoding: "binary",
type: "png",
})) as Buffer;
await browser.close();
return { zoom: Math.min(maxZoom, zoom), image: image };
}
function latLngFormat(lat: number, lng: number): string {
let latStr: string, lngStr: string;
if (lat < 0) {
latStr = `S ${-lat}°`;
} else {
latStr = `N ${lat}°`;
}
if (lng < 0) {
lngStr = `W ${-lng}°`;
} else {
lngStr = `E ${lng}°`;
}
return `${latStr} ${lngStr}`;
}
function latLngDeformat(str: string): [number, number] | null {
const lat_regex = /(?<sign>[ns])\s*(?<number>\d+\.?\d*|\.\d+)/i;
const lng_regex = /(?<sign>[we])\s*(?<number>\d+\.?\d*|\.\d+)/i;
const regex = /(?<sign>[+-]?)\s*(?<number>\d+\.?\d*|\.\d+)/i;
const lat_result = str.match(lat_regex)
? str.match(lat_regex).groups
: str.match(regex)
? str.match(regex).groups
: undefined;
if (!lat_result) return null;
str = str.replace(
new RegExp(lat_result.sign + "\\s*" + lat_result.number, "i"),
""
);
const lng_result = str.match(lng_regex)
? str.match(lng_regex).groups
: str.match(regex)
? str.match(regex).groups
: undefined;
if (!lng_result) return null;
let lat = parseFloat(lat_result.number);
let lng = parseFloat(lng_result.number);
if (lat > 90 || lng > 180) return null;
const lat_sign = lat_result.sign.toLowerCase();
const lng_sign = lng_result.sign.toLowerCase();
if (lat_sign === "s" || lat_sign === "-") lat = -lat;
if (lng_sign === "w" || lng_sign === "-") lng = -lng;
return [lat, lng];
}
function latLngToMercator(lat: number, lng: number): number[] {
const x = (lng / 180) * Math.PI;
const y =
Math.log(
(1 + Math.sin((lat / 180) * Math.PI)) /
(1 - Math.sin((lat / 180) * Math.PI))
) / 2;
return [x, y];
}
function latLngToCartesian(lat: number, lng: number): number[] {
const phi = (lat / 180) * Math.PI;
const theta = (lng / 180) * Math.PI;
const x = Math.cos(phi) * Math.cos(theta);
const y = Math.cos(phi) * Math.sin(theta);
const z = Math.sin(phi);
return [x, y, z];
}
function measureDistance(
lat: number,
lng: number,
latans: number,
lngans: number
): number {
const [x, y, z] = latLngToCartesian(lat, lng);
const [xans, yans, zans] = latLngToCartesian(latans, lngans);
const distance = Math.acos(x * xans + y * yans + z * zans) * radius_of_earth;
return distance;
}
function deg2Rad(deg: number): number {
return (deg * Math.PI) / 180;
}
function rad2Deg(rad: number): number {
return (rad * 180) / Math.PI;
}
function randomPoint(extent: number[]): number[] {
let [minx, miny, maxx, maxy] = [...extent];
maxy = Math.min(80, maxy);
miny = Math.max(-80, miny);
const lng = Math.random() * (maxx - minx) + minx;
const lat = rad2Deg(
Math.asin(
Math.random() * (Math.sin(deg2Rad(maxy)) - Math.sin(deg2Rad(miny))) +
Math.sin(deg2Rad(miny))
)
);
return [lat, lng];
}
function distFormat(num: number): string {
if (num >= 10) {
return `${Math.round(num)}km`;
} else if (num >= 1) {
return `${num.toFixed(1)}km`;
} else {
return `${Math.round(num * 1000)}m`;
}
}
function sizeExtract(text: string): number {
const size =
text.match(reNum) === null
? 1000
: parseFloat(text.match(reNum)[0]) > 10000 ||
parseFloat(text.match(reNum)[0]) <= 0
? 1000
: parseFloat(text.match(reNum)[0]);
return size;
}
function countriesExtract(
text: string,
aliases: Record<string, string[]>
): [string[], string] {
const countriesList = countriesExpand(["世界"], aliases)
.filter((country) => country !== "-")
.sort();
let countriesOriginal: string[] = text
.slice(4)
.replaceAll(new RegExp(reNum, "g"), "")
.trim()
.split(/\s+/)
.filter((str: string) => str !== "");
if (
countriesOriginal.filter((country) => !country.startsWith("-")).length === 0
) {
countriesOriginal.push("世界");
}
countriesOriginal.forEach((country, index) => {
if (countriesOriginal.includes("-" + country)) {
countriesOriginal[index] = "-";
}
});
const countries = countriesExpand(countriesOriginal, aliases);
countries.forEach((country, index) => {
if (countries.includes("-" + country)) {
countries[index] = "-";
}
});
countries.forEach((country, index) => {
if (country.startsWith("-")) {
countries[index] = "-";
}
});
let validCounter = 0;
let errorTextArray = [];
for (let i = 0; i < countries.length; i++) {
if (
countries[i] !== "-" &&
!countriesList.includes(countries[i].replace("-", ""))
) {
errorTextArray.push(
`「${
countriesOriginal[i] === undefined
? countries[i]
: countriesOriginal[i]
}」という国・地域はないよ:anger:`
);
} else if (countries[i] !== "-") {
validCounter += 1;
}
}
if (validCounter === 0) {
errorTextArray.push(`当てはまる場所がないよ:anger:`);
}
return [countries, errorTextArray.join("\n")];
}
async function problemGen(
size: number,
worldFilter: any
): Promise<[any, number, number, string, number, number]> {
let country: any,
zoom: number,
img_url: string,
latitude: number,
longitude: number;
const extent = Turf.bbox(worldFilter);
while (true) {
[latitude, longitude] = randomPoint(extent);
const points = Turf.points([[longitude, latitude]]);
const resArr = worldFilter.features.filter(
(country: any) =>
Turf.pointsWithinPolygon(points, country).features.length > 0
);
if (resArr.length > 0) {
country = resArr[0];
zoom = Math.log2(
(((radius_of_earth * 1000 * 2 * Math.PI) / 256) *
img_size *
Math.cos((latitude * Math.PI) / 180)) /
size /
1000
);
const window = await puppeteerWindow(latitude, longitude, zoom);
zoom = window.zoom;
const result: any = await new Promise((resolve, reject) => {
cloudinary.v2.uploader
.upload_stream(
{ resource_type: "image" },
(error: any, data: any) => {
if (error) {
reject(error);
} else {
resolve(data);
}
}
)
.end(window.image);
});
img_url = result.secure_url;
size =
(((radius_of_earth * 1000 * 2 * Math.PI) / 256) *
img_size *
Math.cos((latitude * Math.PI) / 180)) /
2 ** zoom /
1000;
break;
}
}
return [country, zoom, size, img_url, latitude, longitude];
}
function problemFormat(
country: any,
zoom: number,
size: number,
img_url: string,
latitude: number,
longitude: number,
thread_ts: string,
channel: string
) {
const answer = latLngFormat(latitude, longitude);
const problem: CoordAteQuizProblem = {
problemMessage: {
channel,
thread_ts,
text: `緯度と経度を当ててね。サイズは${distFormat(size)}四方だよ。`,
blocks: [
{
type: "section",
text: {
type: "plain_text",
text: `緯度と経度を当ててね。サイズは${distFormat(size)}四方だよ。`,
},
},
{
type: "image",
image_url: img_url,
alt_text: "Map cannot be displayed.",
},
],
},
hintMessages: [
{
channel,
text: `画像の中心点は${country.properties.NAME_JA}にあるよ:triangular_flag_on_post:`,
},
],
immediateMessage: { channel, text: "制限時間: 300秒" },
solvedMessage: {
channel,
text: ``,
reply_broadcast: true,
thread_ts,
unfurl_links: false,
unfurl_media: false,
},
incorrectMessage: {
channel,
text: ``,
unfurl_links: false,
unfurl_media: false,
},
unsolvedMessage: {
channel,
text: `もう、しっかりして!\n中心点の座標は <https://maps.google.co.jp/maps?ll=${latitude},${longitude}&q=${latitude},${longitude}&&t=k|${answer}> だよ:anger:`,
reply_broadcast: true,
thread_ts,
unfurl_links: false,
unfurl_media: false,
},
answer: [latitude, longitude],
zoom,
size,
correctAnswers: [] as string[],
};
return problem;
}
async function prepareProblem(
slack: any,
message: any,
aliases: Record<string, string[]>,
world: Turf.FeatureCollection<Turf.MultiPolygon>,
thread_ts: string,
channel: string
) {
await slack.chat.postEphemeral({
channel,
text: "問題を生成中...",
user: message.user,
...postOptions,
});
const sizeOrig = sizeExtract(message.text);
const [countries, errorText] = countriesExtract(message.text, aliases);
if (errorText.length > 0) {
await slack.chat.postMessage({
text: errorText,
channel,
...postOptions,
});
return;
}
const worldFilter = Object.create(world);
worldFilter.features = worldFilter.features.filter((feature: any) =>
countries.includes(feature.properties.NAME_JA)
);
const [country, zoom, sizeActual, img_url, latitude, longitude] =
await problemGen(sizeOrig, worldFilter);
const problem: CoordAteQuizProblem = problemFormat(
country,
zoom,
sizeActual,
img_url,
latitude,
longitude,
thread_ts,
channel
);
return problem;
}
class MapGuessr extends ChannelLimitedBot {
protected override readonly wakeWordRegex = /^座標[当あ]て/;
protected override readonly username = 'coord-quiz';
protected override readonly iconEmoji = ':globe_with_meridians:';
private readonly aliases: Record<string, string[]>;
private readonly world: Turf.FeatureCollection<Turf.MultiPolygon>;
constructor(slackClients: SlackInterface, aliases: Record<string, string[]>, world: Turf.FeatureCollection<Turf.MultiPolygon>) {
super(slackClients);
this.aliases = aliases;
this.world = world;
}
protected override onWakeWord(message: GenericMessageEvent, channel: string): Promise<string | null> {
if (message.text.includes('help')) {
this.postMessage({
...mesHelp,
channel,
thread_ts: message.ts,
});
return Promise.resolve(null);
}
if (message.text.includes('countries')) {
this.postMessage({
...countriesListMessageGen(this.aliases),
channel,
thread_ts: message.ts,
});
return Promise.resolve(null);
}
if (mutex.isLocked()) {
this.postMessage({
channel,
text: '今クイズ中だよ:angry:',
thread_ts: message.ts,
});
return Promise.resolve(null);
}
const quizMessageDeferred = new Deferred<string | null>();
mutex.runExclusive(async () => {
try {
const problem: CoordAteQuizProblem = await prepareProblem(
this.slack,
message,
this.aliases,
this.world,
message.ts,
channel,
);
if (!problem) {
quizMessageDeferred.resolve(null);
return;
}
const ateQuiz = new CoordAteQuiz(this.eventClient, this.slack, problem);
const startTime = Date.now();
const result = await ateQuiz.start({
mode: 'normal',
onStarted(startMessage: any) {
quizMessageDeferred.resolve(startMessage.ts!);
},
});
await this.deleteProgressMessage(await quizMessageDeferred.promise);
const endTime = Date.now();
if (result.state === 'solved') {
await increment(result.correctAnswerer, 'coord-quiz-easy-answer');
if (problem.size < 20.00001) {
await increment(result.correctAnswerer, 'coord-quiz-professional-answer');
}
if (problem.size <= 100.00001) {
await increment(result.correctAnswerer, 'coord-quiz-hard-answer');
}
if (problem.size <= 500.00001) {
await increment(result.correctAnswerer, 'coord-quiz-medium-answer');
}
if (endTime - startTime <= 30000) {
await increment(result.correctAnswerer, 'coord-quiz-30sec-answer');
}
}
} catch (error: unknown) {
this.log.error('Failed to start map-guessr quiz', error);
const errorText = error instanceof Error && error.stack !== undefined
? error.stack : String(error);
this.postMessage({
channel,
text: `エラー😢\n\`${errorText}\``,
});
quizMessageDeferred.resolve(null);
}
});
return quizMessageDeferred.promise;
}
}
export default async (slackClients: SlackInterface) => {
const aliases = (await fs.readJson(
__dirname + "/country_names.json"
)) as Record<string, string[]>;
const world = await fs.readJson(__dirname + "/countries.geojson");
return new MapGuessr(slackClients, aliases, world);
};