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
|
/** @jsx BotUI.createElement */
/** @jsxFrag fragment */
import {
ActionRow,
ApplicationCommandChoice,
ApplicationCommandInteraction,
ApplicationCommandOption,
ApplicationCommandsModule,
autocomplete,
AutocompleteInteraction,
BotUI,
Button,
Embed,
fragment,
MessageComponentInteraction,
slash,
SlashCommandOptionType,
SlashCommandPartial,
} from "../../deps_server.ts";
import { games } from "./games.ts";
import { posts } from "./posts.ts";
import { examinedLeaderboard } from "./examined_leaderboard.ts";
import { categories } from "./categories.ts";
import { runs } from "./runs.ts";
import { whois } from "./whois.ts";
import { worldRecords } from "./world_records.ts";
import { worldRecord } from "./world_record.ts";
import { categoriesPlayed } from "./categories_played.ts";
import { podiums } from "./podiums.ts";
import { modCount } from "./mod_count.ts";
import { runsCount } from "./runs_count.ts";
import {
CommandError,
getGame,
searchGames,
searchUsers,
SRC_API,
} from "./utils.ts";
import { runInfo } from "./run_info.ts";
import { levelInfo } from "./level_info.ts";
import { categoryInfo } from "./category_info.ts";
import { leaderboard } from "./leaderboard.ts";
import type { SpeedrunCom as ISpeedrunCom } from "./types.d.ts";
import gameInfo from "./game_info.ts";
import { delay, Moogle } from "../../deps_general.ts";
const srcUser: ApplicationCommandOption = {
name: "username",
type: SlashCommandOptionType.STRING,
description: "A speedrun.com username",
autocomplete: true,
};
const srcGame: ApplicationCommandOption = {
name: "game",
description: "A game abbreviation.",
type: SlashCommandOptionType.STRING,
autocomplete: true,
};
const srcStatus: ApplicationCommandOption = {
name: "status",
description: "The status of a run.",
type: SlashCommandOptionType.STRING,
choices: [
{
name: "Verified",
value: "verified",
},
{
name: "Rejected",
value: "rejected",
},
{
name: "Pending",
value: "new",
},
],
};
const srcExaminer: ApplicationCommandOption = {
name: "examiner",
description: "The examiner/reviewer of a run.",
type: SlashCommandOptionType.STRING,
autocomplete: true,
};
const srcEmulated: ApplicationCommandOption = {
name: "emulated",
description: "If a run is emulated",
type: SlashCommandOptionType.BOOLEAN,
};
const srcLevel: ApplicationCommandOption = {
name: "level",
description: "A level's name.",
type: SlashCommandOptionType.STRING,
autocomplete: true,
};
const srcCategory = {
name: "category",
description: "A game's category",
type: SlashCommandOptionType.STRING,
autocomplete: true,
};
const srcSubcategory = {
name: "subcategory",
description: "A game's variable, such as a sub category",
type: SlashCommandOptionType.STRING,
};
export const commands: SlashCommandPartial[] = [
{
name: "games",
description: "See how many games a player has submitted runs to.",
options: [
{
...srcUser,
required: true,
},
],
},
{
name: "posts",
description: "See how many posts a player has posted on the site.",
options: [
{
...srcUser,
required: true,
},
],
},
{
name: "mod-count",
description: "See how many games and series a user moderates.",
options: [
{
...srcUser,
required: true,
},
],
},
{
name: "categories",
description: "See the categories of a game.",
options: [
{
...srcGame,
required: true,
},
],
},
{
name: "categories-played",
description: "See how many categories a player has submitted runs to.",
options: [
{
...srcUser,
required: true,
},
srcGame,
{
...srcGame,
name: "game2",
},
],
},
{
name: "podiums",
description:
"See how many runs a player has on the podium of leaderboards.",
options: [
{
...srcUser,
required: true,
},
srcGame,
{
...srcGame,
name: "game2",
},
],
},
{
name: "examined-leaderboard",
description: "See how many runs all moderators of a game have examined.",
options: [
{
...srcGame,
required: true,
},
srcStatus,
],
},
{
name: "runs",
description: "See all runs given the parameters.",
options: [
srcUser,
srcGame,
srcStatus,
srcExaminer,
srcEmulated,
],
},
{
name: "runs-count",
description: "See how many runs given the parameters.",
options: [
srcUser,
srcGame,
srcStatus,
srcExaminer,
srcEmulated,
],
},
{
name: "whois",
description: "See info about a speedrun.com user.",
options: [
{
...srcUser,
required: true,
},
],
},
{
name: "world-records",
description: "See how many world records a player has on `speedrun.com`.",
options: [
{
...srcUser,
required: true,
},
srcGame,
{
...srcGame,
name: "game2",
},
],
},
{
name: "world-record",
description:
"See the world record of a given game, category, and sub-category.",
options: [
{
...srcGame,
required: true,
},
srcCategory,
srcSubcategory,
],
},
{
name: "run-info",
description: "Get info about a run.",
options: [
{
name: "run",
description: "A run ID or link",
type: SlashCommandOptionType.STRING,
required: true,
},
],
},
{
name: "game-info",
description: "Get info about a game.",
options: [
{
...srcGame,
required: true,
},
],
},
{
name: "level-info",
description: "Get info about a game's level.",
options: [
{
...srcGame,
required: true,
},
{
...srcLevel,
required: true,
},
],
},
{
name: "category-info",
description: "Get info about a game's category.",
options: [
{
...srcGame,
required: true,
},
{
...srcCategory,
required: true,
},
],
},
{
name: "leaderboard",
description: "Get the top 10 for a given game, category and subcategory",
options: [
{
...srcGame,
required: true,
},
srcCategory,
srcSubcategory,
],
},
];
function splitIntoChunks(array: string[], perChunk: number): string[][] {
const result = array.reduce<string[][]>((resultArray, item, index) => {
const chunkIndex = Math.floor(index / perChunk);
if (!resultArray[chunkIndex]) {
resultArray[chunkIndex] = []; // start a new chunk
}
resultArray[chunkIndex].push(item);
return resultArray;
}, []);
return result;
}
async function sendCommand(
i: ApplicationCommandInteraction,
func: (
i: ApplicationCommandInteraction,
signal: AbortSignal,
) => Promise<string>,
{ defer = true }: { defer?: boolean } = {},
) {
const controller = new AbortController();
const cancelButtonId = crypto.randomUUID();
runningTasks.set(cancelButtonId, { signal: controller, user: i.user.id });
const CancelButton = (
<>
<ActionRow>
<Button style="danger" label="Cancel" id={cancelButtonId} />
</ActionRow>
</>
);
await i.reply("Loading, please wait...", {
components: CancelButton,
}).catch(console.error);
try {
const [title, ...description] = (await func(i, controller.signal)).split(
"\n",
);
controller.signal.throwIfAborted();
if (description.length > 10) {
await i.editResponse(
"This message will be sent into many small and hidden chunks to prevent spam.",
);
const chunks = splitIntoChunks(description, 10);
for (let ii = 0; ii < chunks.length; ii++) {
controller.signal.throwIfAborted();
await i.send({
embeds: [
new Embed({
title: `${title}: ${ii + 1}/${chunks.length}`,
description: chunks[ii].join("\n"),
}),
],
components: CancelButton,
ephemeral: true,
});
}
} else {
controller.signal.throwIfAborted();
const embed = new Embed({
title,
description: description.join("\n"),
});
await i.editResponse({ embeds: [embed], components: [] }).catch(
console.error,
);
}
} catch (err: unknown) {
const command = `/${i.data.name} ${
i.data.options.map((opt) => `${opt.name}:${opt.value}`)
}`;
if (err instanceof DOMException && err.name === "AbortError") {
await i.deleteResponse();
} else if (err instanceof CommandError) {
console.debug(err);
await i.editResponse(`Error: ${err.message}`);
} else if (err instanceof Error) {
console.error(err);
await i.send({
embeds: [
new Embed({
description:
`Unexpected Error, please report this to a developer: ${command}\n\`/${i.data.name} ${
i.data.options.map((opt) => `${opt.name}:${opt.value}`)
}`,
color: 16711680,
}),
new Embed({
title: err.message,
description: `\`\`\`ts\n${err.stack}\n\`\`\``,
color: 16711680,
}),
],
ephemeral: true,
});
} else {
console.error(err);
await i.reply(
`Critical error, please report this to a developer: \`${command}\``,
);
}
}
runningTasks.delete(cancelButtonId);
}
const runningTasks = new Map<
string,
{ signal: AbortController; user: string }
>();
export class SpeedrunCom extends ApplicationCommandsModule {
static async handleCancelButton(i: MessageComponentInteraction) {
const task = runningTasks.get(i.customID)!;
if (!task) {
try {
await i.respond({
content: "Sorry, but I couldn't find the running task to cancel.",
ephemeral: true,
});
} catch {
await i.editResponse({
content: "Sorry, but I couldn't find the running task to cancel.",
ephemeral: true,
});
}
}
if (task.user !== i.user.id) {
i.send({
content: "You are not allowed to cancel this.",
ephemeral: true,
});
return;
}
task.signal.abort();
try {
await i.respond({
content: "Canceled",
ephemeral: true,
});
} catch {
await i.editResponse({
content: "Canceled",
ephemeral: true,
});
}
runningTasks.delete(i.customID);
}
static async #userCompletions(
d: AutocompleteInteraction,
): Promise<ApplicationCommandChoice[]> {
const users = await searchUsers(d.focusedOption.value);
return users.map((user) => ({
name: user.name,
value: user.name,
}));
}
static async #gamesCompletions(
d: AutocompleteInteraction,
): Promise<ApplicationCommandChoice[]> {
const games = await searchGames(d.focusedOption.value);
return games.map((game) => ({ name: game.name, value: game.abbreviation }));
}
static async #levelCompletions(
d: AutocompleteInteraction,
): Promise<ApplicationCommandChoice[]> {
const game = d.option("game");
const level = d.option("level");
if (
(typeof game === "string" && game.length) && (typeof level === "string")
) {
const gameObj = await getGame(d.option("game"));
if (gameObj) {
const levels = (await (await fetch(
`${SRC_API}/games/${gameObj.id}/levels`,
)).json()).data as ISpeedrunCom.Level[];
if (!levels.length) return [];
const searchService = new Moogle<ISpeedrunCom.Level>();
levels.forEach((level) =>
searchService.addItem([level.name.toLowerCase()], level)
);
const searchResult = searchService.search(
level.toLowerCase(),
);
return ([...searchResult].map((res) => ({
name: res[1].item.name,
value: res[1].item.name,
})));
}
}
return [];
}
static async #categoryCompletion(
d: ApplicationCommandInteraction,
): Promise<ApplicationCommandChoice[]> {
const game = d.option("game");
const category = d.option("category");
if (
(typeof game === "string" && game.length) &&
(typeof category === "string")
) {
const gameObj = await getGame(d.option("game"));
if (gameObj) {
const categories =
(await (await fetch(`${SRC_API}/games/${gameObj.id}/categories`))
.json()).data as ISpeedrunCom.Category[];
const searchService = new Moogle<ISpeedrunCom.Category>();
categories.forEach((category) =>
searchService.addItem([category.name.toLowerCase()], category)
);
const searchResult = searchService.search(
category.toLowerCase(),
);
return ([...searchResult].map((res) => ({
name: res[1].item.name,
value: res[1].item.name,
})));
}
}
return [];
}
@autocomplete("*", "*")
async autoComplete(d: AutocompleteInteraction) {
const completions: ApplicationCommandChoice[] = [];
if (
d.focusedOption.name.includes("user") ||
d.focusedOption.name.includes("username") ||
d.focusedOption.name.includes("examiner")
) {
completions.push(...await SpeedrunCom.#userCompletions(d));
} else if (d.focusedOption.name.includes("game")) {
completions.push(...await SpeedrunCom.#gamesCompletions(d));
} else if (d.focusedOption.name.includes("level")) {
completions.push(...await SpeedrunCom.#levelCompletions(d));
} else if (d.focusedOption.name.includes("category")) {
completions.push(...await SpeedrunCom.#categoryCompletion(d));
}
return d.autocomplete(
completions,
);
}
@slash()
async games(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i, signal) =>
games(i.option("username"), { outputType: "markdown", signal }),
);
}
@slash()
async posts(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) => posts(i.option("username"), { outputType: "markdown" }),
);
}
@slash("mod-count")
async modCount(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) => modCount(i.option("username"), { outputType: "markdown" }),
);
}
@slash()
async categories(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) => categories(i.option("game"), { outputType: "markdown" }),
);
}
@slash("categories-played")
async categoriesPlayed(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
categoriesPlayed(i.option("username"), [
i.option("game"),
i.option("game2"),
], { outputType: "markdown" }),
);
}
@slash()
async podiums(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
podiums(i.option("username"), [
i.option("game"),
i.option("game2"),
], { outputType: "markdown" }),
);
}
@slash("examined-leaderboard")
async examinedLeaderboard(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
examinedLeaderboard(
i.option("game"),
i.option("status"),
{ outputType: "markdown" },
),
);
}
@slash()
async runs(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
runs(
i.option("username"),
i.option("game"),
i.option("status"),
i.option("examiner"),
i.option<string | undefined>("emulated"),
{ outputType: "markdown" },
),
);
}
@slash("runs-count")
async runsCount(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
runsCount(
i.option("username"),
i.option("game"),
i.option("status"),
i.option("examiner"),
i.option<string | undefined>("emulated"),
{ outputType: "markdown" },
),
);
}
@slash()
async whois(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) => whois(i.option("username"), { outputType: "markdown" }),
);
}
@slash("world-records")
async worldRecords(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
worldRecords(i.option("username"), [
i.option("game"),
i.option("game2"),
], { outputType: "markdown" }),
);
}
@slash("world-record")
async worldRecord(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
worldRecord(
i.option("game"),
i.option("category"),
i.option("subcategory"),
{ outputType: "markdown" },
),
);
}
@slash("run-info")
async runInfo(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
runInfo(
i.option("run"),
{ outputType: "markdown" },
),
);
}
@slash("game-info")
async gameInfo(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
gameInfo(
i.option("game"),
{ outputType: "markdown" },
),
);
}
@slash("level-info")
async levelInfo(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
levelInfo(
i.option("game"),
i.option("level"),
{ outputType: "markdown" },
),
);
}
@slash("category-info")
async categoryInfo(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
categoryInfo(
i.option("game"),
i.option("category"),
{ outputType: "markdown" },
),
);
}
@slash("leaderboard")
async leaderboard(i: ApplicationCommandInteraction) {
await sendCommand(
i,
(i) =>
leaderboard(
i.option("game"),
i.option("category"),
i.option("subcategory"),
{ outputType: "markdown" },
),
);
}
}
|