This repository has been archived by the owner on Apr 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbob.js
1498 lines (1324 loc) · 58.5 KB
/
bob.js
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const discordAuth = require("./discord_auth.json");
const config = require("./config.json");
const emotes = config.emotes;
const fun = require("./fun.js");
const roles = require("./roles.js");
const Discord = require("discord.js");
const SQLite = require("better-sqlite3");
const https = require("https");
const fs = require("fs");
const helpers = require("./helpers.js");
if (!fs.existsSync("./data/")) {
fs.mkdirSync("./data/");
}
const sql = new SQLite("./data/race.sqlite");
const client = new Discord.Client();
var gameName = Object.keys(config.games)[0];
var categoryName = helpers.normalizeCategory(gameName, null);
var levelName = helpers.normalizeLevel(gameName, null);
var raceId = 0;
// References to timeouts, to cancel them if someone interrupts them
var countDownTimeout1;
var countDownTimeout2;
var countDownTimeout3;
var goTimeout;
var raceDoneTimeout;
var raceDoneWarningTimeout;
// Indicates a race bot state
var State = {
NO_RACE: 0,
JOINING: 1,
COUNTDOWN: 2,
ACTIVE: 3,
DONE: 4
}
// Keeps track of the current stage of racing the bot is occupied with
class RaceState {
constructor() {
this.entrants = new Map(); // Maps from user id to their current race state
this.doneIds = [];
this.ffIds = [];
this.state = State.NO_RACE;
this.startTime = 0;
this.ilScores = new Map();
this.ilResults = [];
this.leavingWhenDone = new Set();
}
// Adds an entrant. Returns true if successful, returns false if the user has already joined.
addEntrant(message) {
if (this.entrants.has(message.author.id)) {
return false;
}
this.entrants.set(message.author.id, new Entrant(message));
return true;
}
// Removes an entrant. Returns true if successful, returns false if the user isn't an entrant.
removeEntrant(id) {
if (this.entrants.has(id)) {
if (this.entrants.get(id).team !== "") {
this.disbandTeam(this.entrants.get(id).team);
}
this.entrants.delete(id);
return true;
}
return false;
}
// Returns true if the user is joined and ready, false if not.
entrantIsReady(id) {
return this.entrants.has(id) && this.entrants.get(id).ready;
}
// Returns true if all entrants are ready, false if not.
isEveryoneReady() {
let everyoneReady = true;
this.entrants.forEach((entrant) => {
if (!entrant.ready) {
everyoneReady = false;
}
});
return everyoneReady;
}
// Returns the current IL score of a user
getILScore(id) {
if (this.ilScores.has(id)) {
return this.ilScores.get(id);
}
return 0;
}
// Resets the team name of all entrants using teamName
disbandTeam(teamName) {
this.entrants.forEach((entrant) => {
if (entrant.team === teamName) {
entrant.team = "";
}
});
}
// Returns true if any teams are registered, false if not
hasTeams() {
let has = false;
this.entrants.forEach((entrant) => {
if (entrant.team !== "") {
has = true;
}
});
return has;
}
}
// Represents a race entrant
class Entrant {
constructor(message) {
this.message = message;
this.ready = false;
this.doneTime = 0;
this.team = "";
}
}
// Holds the winner of an IL race
class ILResult {
constructor(id, level, winner) {
this.id = id;
this.level = level;
this.winner = winner;
}
}
var raceState = new RaceState();
client.on("ready", () => {
// Setup tables for keeping track of race results
if (!sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='results'").get()['count(*)']) {
sql.prepare("CREATE TABLE results (race_id INTEGER, user_id TEXT, user_name TEXT, game TEXT, category TEXT, level TEXT, time INTEGER, ff INTEGER, team_name TEXT);").run();
sql.prepare("CREATE UNIQUE INDEX idx_results_race ON results (race_id, user_id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// Setup tables for keeping track of user stats
if (!sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='users'").get()['count(*)']) {
sql.prepare("CREATE TABLE users (user_id TEXT, game TEXT, category TEXT, races INTEGER, gold INTEGER, silver INTEGER, bronze INTEGER, ffs INTEGER, elo REAL, pb INTEGER);").run();
sql.prepare("CREATE UNIQUE INDEX idx_users_id ON users (user_id, game, category);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// Setup SQL queries for setting/retrieving results
client.getLastRaceID = sql.prepare("SELECT MAX(race_id) AS id FROM results");
client.getResults = sql.prepare("SELECT * FROM results WHERE race_id = ? ORDER BY time ASC");
client.addResult = sql.prepare("INSERT OR REPLACE INTO results (race_id, user_id, user_name, game, category, level, time, ff, team_name) VALUES (@race_id, @user_id, @user_name, @game, @category, @level, @time, @ff, @team_name);");
// Setup SQL queries for setting/retrieving user stats
client.getUserStatsForGame = sql.prepare("SELECT * FROM users WHERE user_id = ? AND game = ? ORDER BY category ASC");
client.getUserStatsForCategory = sql.prepare("SELECT * FROM users WHERE user_id = ? AND game = ? AND category = ?");
client.addUserStat = sql.prepare("INSERT OR REPLACE INTO users (user_id, game, category, races, gold, silver, bronze, ffs, elo, pb) "
+ "VALUES (@user_id, @game, @category, @races, @gold, @silver, @bronze, @ffs, @elo, @pb);");
client.getUserGamesRan = sql.prepare("SELECT DISTINCT game, category FROM users WHERE user_id = ?");
client.getIdFromName = sql.prepare("SELECT user_id, user_name FROM results WHERE user_name = ? COLLATE NOCASE");
// Setup SQL query to show leaderboard
client.getLeaderboard = sql.prepare("SELECT DISTINCT results.user_id AS user_id, results.user_name AS user_name, users.elo AS elo FROM results INNER JOIN users ON results.user_id = users.user_id "
+ "WHERE results.game = ? AND results.category = ? AND users.game = ? AND users.category = ? GROUP BY results.user_id ORDER BY users.elo DESC");
// Set race ID to highest recorded race ID + 1
raceId = client.getLastRaceID.get().id;
if (!raceId) {
raceId = 0;
}
raceId++;
roles.init(client);
helpers.log("Ready! Next race ID is " + raceId + ".");
});
client.on("message", (message) => {
if (!message.content.startsWith("!") || message.author.bot) {
return;
}
// Race commands
lowerMessage = message.content.toLowerCase();
if (message.guild) {
if (lowerMessage.startsWith("!race") || lowerMessage.startsWith("!join"))
raceCmd(message);
else if (lowerMessage.startsWith("!ilrace"))
ilRaceCmd(message);
else if (lowerMessage.startsWith("!game"))
gameCmd(message);
else if (lowerMessage.startsWith("!category"))
categoryCmd(message);
else if (lowerMessage.startsWith("!level"))
levelCmd(message);
else if (lowerMessage.startsWith("!luckydip"))
luckyDipCmd(message);
else if (lowerMessage.startsWith("!team"))
teamCmd(message);
else if (lowerMessage.startsWith("!randomteams"))
randomTeamsCmd(message);
else if (lowerMessage.startsWith("!unteam"))
unteamCmd(message);
else if (lowerMessage.startsWith("!exit") ||
lowerMessage.startsWith("!unrace") ||
lowerMessage.startsWith("!leave") ||
lowerMessage.startsWith("!quit") ||
lowerMessage.startsWith("!yeet") ||
lowerMessage.startsWith("!f"))
forfeitCmd(message);
else if (lowerMessage.startsWith("!ready"))
readyCmd(message);
else if (lowerMessage.startsWith("!unready"))
unreadyCmd(message);
else if (lowerMessage.startsWith("!d") || lowerMessage.startsWith("! d"))
doneCmd(message);
else if (lowerMessage.startsWith("!ud") || lowerMessage.startsWith("!undone"))
undoneCmd(message);
else if (lowerMessage.startsWith("!uf") || lowerMessage.startsWith("!unforfeit"))
unforfeitCmd(message);
// Admin/Mod only commands
else if (message.member.roles.cache.some(role => role.name === "Admin" || role.name === "Moderator")) {
if (lowerMessage.startsWith("!modhelp"))
modHelpCmd(message);
else if (lowerMessage.startsWith("!clearrace"))
clearRaceCmd(message);
else if (lowerMessage.startsWith("!clearteams"))
clearTeamsCmd(message);
}
}
// Commands available anywhere
if (lowerMessage.startsWith("!help") || lowerMessage.startsWith("!commands"))
helpCmd(message);
else if (lowerMessage.startsWith("!me"))
meCmd(message);
else if (lowerMessage.startsWith("!runner"))
runnerCmd(message);
else if (lowerMessage.startsWith("!results"))
resultsCmd(message);
else if (lowerMessage.startsWith("!ilresults"))
ilResultsCmd(message);
else if (lowerMessage.startsWith("!elo") || lowerMessage.startsWith("!leaderboard"))
leaderboardCmd(message);
else if (lowerMessage.startsWith("!s"))
statusCmd(message);
else {
fun.funCmds(lowerMessage, message);
roles.roleCmds(lowerMessage, message);
}
});
client.on('error', console.error);
// !help/!commands
helpCmd = (message) => {
message.channel.send(`
**Pre-race commands**
\`!race\` - Starts a new full-game race, or joins the current open race if someone already started one.
\`!game <game name>\` - Sets the game (e.g. \`!game LBP2\`).
\`!category <category name>\` - Sets the category (e.g. \`!category any%\`).
\`!team <discord id> [<discord id> ... <team name>]\` - Sets up a team for co-op racing.
\`!randomteams [<team size>]\` - Randomly assigns entrants to teams of the given size. Default size is 2.
\`!unteam\` - Disband your current team.
\`!leave\` - Leave the race.
\`!ready\` - Indicate that you're ready to start.
\`!unready\` - Indicate that you're not actually ready.
**Mid-race commands**
\`!d\` - Indicate that you finished.
\`!ud\` - Get back in the race if you finished by accident.
\`!f\` - Drop out of the race.
\`!uf\` - Rejoin the race if you forfeited by accident.
**IL race commands**
\`!ilrace\` - Starts a new series of IL races.
\`!level <level name>\` - Sets the next level to race. Also accepts lbp.me links.
\`!luckydip\` - Sets the next level to race to a random lucky dip level.
\`!ilresults\` - Shows the ILs that have been played so far in a series, and the winner of each one.
**Stat commands**
\`!status\` - Shows current race status/entrants.
\`!results <race #>\` - Shows results of the specified race number (e.g. \`!results 2\`).
\`!me <game name>\` - Shows your race statistics for the specified game (e.g. \`!me lbp\`).
\`!runner <username or id> <game name>\` - Shows someone else's race statistics (e.g. \`!runner RbdJellyfish lbp\`).
\`!elo <game name>/<category name>\` - Shows the ELO leaderboard for the given game/category (e.g. \`!elo lbp/any% no overlord\`).
\`!help\` - Shows this message.
**Other commands**
\`!roles <speedrun.com name>\` - Updates your roles to match races finished + speedrun.com PBs (if you linked your discord account on speedrun.com).
\`!removeroles\` - Removes your runner roles.
`);
}
modHelpCmd = (message) => {
message.channel.send(`
**Admin/moderator only (mid-race)**
\`!modhelp\` - Shows this message.
\`!clearrace\` - Resets the bot; forces ending the race without recording any results.
\`!clearteams\` - Disbands all current teams.
\`!f <discord id>\` - Kicks another user from the race.
\`!roles <speedrun.com name> <discord id>\` - Updates someone else's roles.
\`!removeroles <discord id>\` - Remove someone else's roles.
\`!reloadroles\` - Refreshes all registered roles.
`);
}
// !race/!join
raceCmd = (message) => {
if (raceState.state === State.DONE) {
// Record race results now if results are pending
clearTimeout(raceDoneTimeout);
recordResults();
}
if (raceState.state === State.NO_RACE) {
// Start race
raceState.addEntrant(message);
message.channel.send(helpers.mention(message.author) + " has started a new race! Use `!race` to join; use `!game` and `!category` to setup the race further (currently " + gameName + " / " + categoryName + ").");
raceState.state = State.JOINING;
} else if (raceState.state === State.JOINING) {
// Join existing race
if (raceState.addEntrant(message)) {
message.react(emotes.acknowledge);
}
} else if (raceState.state === State.COUNTDOWN || raceState.state === State.ACTIVE) {
if (raceState.leavingWhenDone.has(message.author.id)) {
raceState.leavingWhenDone.delete(message.author.id);
message.react(emotes.acknowledge);
} else {
// Can't join race that already started
if (!raceState.entrants.has(message.author.id)) {
message.author.send("Can't join because there's a race already in progress!");
}
}
}
}
// !ilrace
ilRaceCmd = (message) => {
if (raceState.state === State.DONE) {
// Record race results now if results are pending
clearTimeout(raceDoneTimeout);
recordResults();
}
if (raceState.state === State.NO_RACE) {
// Start race
raceState.addEntrant(message);
levelName = helpers.normalizeLevel(gameName, null);
msg = helpers.mention(message.author) + " has started a new IL race! Use `!race` to join; use `!game` and `!level` to setup the race further";
if (config.games[gameName].levels === undefined) {
msg += ".\n**Note:** IL races are not configured for " + gameName + ". Use `!game` to choose a game with ILs, or use `!level` to pick the level if this was not a mistake.";
} else {
msg += " (currently " + gameName + " / " + levelName + ").";
}
message.channel.send(msg);
raceState.state = State.JOINING;
} else if (raceState.state === State.JOINING) {
// Join existing race
if (raceState.addEntrant(message)) {
message.react(emotes.acknowledge);
}
} else if (raceState.state === State.COUNTDOWN || raceState.state === State.ACTIVE) {
// Can't join race that already started
message.author.send("Can't join because there's a race already in progress!");
return;
}
// Update category to IL races
categoryName = raceState.hasTeams() ? "Individual Levels (Co-op)" : "Individual Levels";
}
// !game
gameCmd = (message) => {
if (raceState.state !== State.JOINING) {
return;
}
game = message.content.replace(/^!game/i, "").trim();
word = isILRace() ? "level" : "category";
name = isILRace() ? levelName : categoryName;
if (game === null || game === "") {
message.channel.send("Game / " + word + " is currently set to " + gameName + " / " + name + ". Set the game using: `!game <game name>`");
return;
}
game = helpers.normalizeGameName(game);
if (game === null) {
message.channel.send("Specified game name was not valid, try something else.");
return;
}
if (gameName !== game) {
gameName = game;
warning = "";
if (isILRace()) {
levelName = helpers.normalizeLevel(game, null);
name = levelName;
if (config.games[game].levels === undefined) {
warning = "\n**Note:** IL races are not configured for " + gameName + ". Use `!game` to choose another game, or use `!level` to pick the level if this was not a mistake.";
}
} else {
categoryName = helpers.normalizeCategory(game, null);
name = categoryName;
}
message.channel.send("Game / " + word + " updated to " + gameName + " / " + name + "." + warning);
} else {
message.channel.send("Game / " + word + " was already set to " + gameName + " / " + name + ".");
}
}
// !category
categoryCmd = (message) => {
if (raceState.state === State.JOINING) {
category = message.content.replace(/^!category/i, "").trim();
if (category === null || category === "") {
if (isILRace()) {
message.channel.send("IL race is currently in progress. Current game / level is set to " + gameName + " / " + levelName + ".");
} else {
message.channel.send("Game / category is currently set to " + gameName + " / " + categoryName + ". Set the category using: `!category <category name>`");
}
return;
}
normalized = helpers.normalizeCategory(gameName, category);
if (normalized === null) {
if (isILRace()) {
message.channel.send("Switching from IL race to full-game race (" + gameName + " / " + category + "). (This doesn't seem to be an official category, though; did you mean something else?)");
} else {
message.channel.send("Category updated to " + category + ". (This doesn't seem to be an official category, though; did you mean something else?)");
}
categoryName = category;
return;
}
if (normalized.startsWith("Individual Levels")) {
if (!isILRace()) {
categoryName = raceState.hasTeams() ? "Individual Levels (Co-op)" : "Individual Levels";
endMsg = " (currently " + gameName + " / " + levelName + ").";
if (config.games[gameName].levels === undefined) {
endMsg = ".\n**Note:** ILs are not configured for " + gameName + ". Use `!game` to choose a game with ILs, or use `!level` to pick the level if this was not a mistake.";
}
message.channel.send("Switched to IL race. Use `!race` to join; use `!game` and `!level` to setup the race further" + endMsg);
}
return;
}
if (isILRace()) {
message.channel.send("Switching from IL race to full-game race (" + gameName + " / " + normalized + ").");
} else {
message.channel.send("Category updated to " + normalized + ".");
}
categoryName = normalized;
}
}
// !level
levelCmd = (message) => {
if (!isILRace() || raceState.state !== State.JOINING) {
return;
}
// Show current level
level = message.content.replace(/^!level/i, "").trim();
if (level === null || level === "") {
message.channel.send("Game / level is currently set to " + gameName + " / " + levelName + ". Set the level using: `!level <level name>`");
return;
}
// Choose community level
if (level.includes("lbp.me/v/")) {
chooseLbpMeLevel(getLbpMeUrl(level), message);
return;
}
normalized = helpers.normalizeLevel(gameName, level);
if (normalized !== null) {
// Choose story level
levelName = normalized;
message.channel.send("Level updated to " + levelName + ".");
return;
}
// Choose other non-story level
levelName = level;
message.channel.send("Level updated to " + levelName + ". (Level name not recognized in " + gameName + "; did you make a typo?)");
}
// !luckydip
luckyDipCmd = (message) => {
if (!isILRace() || raceState.state !== State.JOINING) {
return;
}
levelRegex = /-/;
luckyDipUrl = "";
lastLetter = gameName.charAt(gameName.length - 1);
switch(lastLetter) {
case "t":
levelRegex = /([^\/]+)" class="level-pic md no-frills lbp1/g;
luckyDipUrl = "https://lbp.me/levels?p=1&t=luckydip&g=lbp1";
break;
case "2":
levelRegex = /([^\/]+)" class="level-pic md no-frills lbp2/g;
luckyDipUrl = "https://lbp.me/levels?p=1&t=luckydip&g=lbp2";
break;
case "3":
levelRegex = /([^\/]+)" class="level-pic md no-frills lbp3/g;
luckyDipUrl = "https://lbp.me/levels?p=1&t=luckydip&g=lbp3";
break;
case "a":
levelRegex = /\/v\/([^"]+)/g;
luckyDipUrl = "https://vita.lbp.me/search?t=luckydip";
break;
default:
message.channel.send("Random community levels are unsupported for " + gameName);
return;
}
chooseLuckyDipLevel(luckyDipUrl, message);
}
chooseLuckyDipLevel = (luckyDipUrl, message) => {
"use-strict";
https.get(luckyDipUrl, (result) => {
var { statusCode } = result;
if (statusCode === 302) {
chooseLuckyDipLevel(result.headers.location, message);
return;
}
if (statusCode !== 200) {
message.channel.send("Couldn't follow " + luckyDipUrl + "; got a " + statusCode + " response.");
return;
}
var dataQueue = "";
result.on("data", (dataBuffer) => {
dataQueue += dataBuffer;
});
result.on("end", () => {
matches = [];
dataQueue.replace(levelRegex, (wholeMatch, parenthesesContent) => {
matches.push(parenthesesContent);
});
level = ((lastLetter === "a") ? "https://vita.lbp.me/v/" : "https://lbp.me/v/")
+ matches[Math.floor(Math.random() * 12)];
chooseLbpMeLevel(getLbpMeUrl(level), message);
});
}).on('error', (e) => {
helpers.log(e, true);
helpers.sendErrorMessage(e, luckyDipUrl, message);
});
}
getLbpMeUrl = (level) => {
if (level.startsWith("http:")) {
level = level.replace("http:", "https:");
} else if (!level.startsWith("https:")) {
level = "https://" + level;
}
if (level.split("/").length < 6) {
level += "/topreviews";
}
return level;
}
// Sets the current level in an IL race to the level at the given lbp.me link
chooseLbpMeLevel = (level, message) => {
isVita = level.includes("vita.lbp.me");
"use-strict";
https.get(level, (result) => {
var { statusCode } = result;
if (statusCode === 302) {
chooseLbpMeLevel(result.headers.location, message, onEnd);
return;
}
if (statusCode !== 200) {
message.channel.send("Couldn't follow " + level + "; got a " + statusCode + " response.");
return;
}
var dataQueue = "";
result.on("data", (dataBuffer) => {
dataQueue += dataBuffer;
});
result.on("end", () => {
start = dataQueue.search("<title>") + 7;
end = dataQueue.search(/ - LBP\.me( PS Vita)?<\/title>/);
titleAuthor = helpers.decodeHTML(dataQueue.substring(start, end).trim());
split = titleAuthor.split(" ");
title = titleAuthor.substring(0, titleAuthor.search(split[split.length - (isVita ? 2 : 1)])).trim(); // On vita.lbp.me there is a "By" between level name and author
levelName = title + (isVita ? " - https://vita.lbp.me/v/" : " - https://lbp.me/v/") + level.split("/")[4];
message.channel.send("Level updated to " + levelName + ".");
});
}).on('error', (e) => {
helpers.log(e, true);
helpers.sendErrorMessage(e, level, message);
});
}
// !team
teamCmd = (message) => {
// Can only run command if you've joined the race and it hasn't started
if (raceState.state !== State.JOINING || !raceState.entrants.has(message.author.id)) {
return;
}
params = message.content.replace(/^!team/i, "").trim().split(" ");
if (params[0] === "") {
message.channel.send("Usage: `!team @teammate1 [@teammate2 @teammate3 ... team name]`");
return;
}
// Parse custom team name first; need to validate this before we start constructing the team
teamName = "Team " + helpers.username(message);
customTeamName = false;
for(var i = 0; i < params.length; i++) {
if (customTeamName) {
teamName += " " + params[i];
} else {
if (!params[i].startsWith("<@!")) {
teamName = params[i];
customTeamName = true;
}
}
}
// Validate that team name is unused
prevTeamName = raceState.entrants.get(message.author.id).team;
if (teamName !== prevTeamName) {
for(var entry in raceState.entrants) {
if (entry[1].team === teamName) {
message.channel.send(helpers.mention(message.author) + ": Cannot create team; the team name \"" + teamName + "\" is already being used.");
return;
}
}
}
// Validate selected team members
selectedUsers = [raceState.entrants.get(message.author.id)];
for(var i = 0; i < params.length; i++) {
if (!params[i].startsWith("<@!")) {
break;
}
discordId = params[i].replace("<@!", "").replace(">", "").trim();
if (!raceState.entrants.has(discordId)) {
message.channel.send(helpers.mention(message.author) + ": Cannot create team; all team members must join the race first.");
return;
}
if (discordId === message.author.id) {
message.channel.send(helpers.mention(message.author) + ": Cannot create team; you can't team with yourself!");
return;
}
entrant = raceState.entrants.get(discordId);
if (entrant.team !== "" && entrant.team !== teamName && entrant.team !== prevTeamName) {
message.channel.send(helpers.mention(message.author) + ": Cannot create team; <@" + discordId + "> is already on another team (" + userTeam + "). They must run `!unteam` before you can add them to your team.");
return;
}
selectedUsers.push(entrant);
}
// Didn't specify team members
if (selectedUsers.length <= 1) {
if (raceState.entrants.get(message.author.id).team !== "" && customTeamName) {
helpers.doForWholeTeam(raceState, message.author.id, (e) => e.team = teamName);
message.channel.send(helpers.mention(message.author) + ": Team name has been changed to **" + teamName + "**.");
} else {
message.channel.send(helpers.mention(message.author) + ": Cannot create team; you must choose teammates.");
}
return;
}
// Form new team
if (isILRace()) {
categoryName = "Individual Levels (Co-op)";
}
if (prevTeamName !== "") {
raceState.disbandTeam(prevTeamName);
}
for (var i = 0; i < selectedUsers.length; i++) {
selectedUsers[i].team = teamName;
}
// Send confirmation message
messageString = helpers.mention(selectedUsers[0].message.author) + " has teamed with ";
for (var i = 1; i < selectedUsers.length; i++) {
messageString += (i > 1 ? ", " : "") + helpers.mention(selectedUsers[i].message.author)
}
messageString += " under the name **" + teamName + "**";
message.channel.send(messageString);
}
// !randomteams
randomTeamsCmd = (message) => {
// Can only run command if you've joined the race and it hasn't started
if (raceState.state !== State.JOINING || !raceState.entrants.has(message.author.id)) {
return;
}
params = message.content.replace(/^!randomteams/i, "").trim().split(" ");
teamSize = 2;
if (params[0] !== "") {
teamSize = parseInt(params[0]);
if (teamSize < 2) {
teamSize = 2;
}
}
if (isILRace()) {
categoryName = "Individual Levels (Co-op)";
}
entrantArray = [];
raceState.entrants.forEach((entrant) => {
if (entrant.team !== "") {
raceState.disbandTeam(entrant.team);
}
entrantArray.push(entrant);
});
entrantArray.sort((a, b) => Math.floor(Math.random() * 3) - 1);
teamCount = 0;
teamName = "";
entrantArray.forEach((entrant) => {
if (teamCount === 0) {
teamName = "Team " + helpers.username(entrant.message);
}
entrant.team = teamName;
teamCount++;
if (teamCount >= teamSize) {
teamCount = 0;
}
});
message.react(emotes.acknowledge);
statusCmd(message);
}
// !unteam
unteamCmd = (message) => {
// Can only run command if you've joined the race and it hasn't started
if (raceState.state !== State.JOINING || !raceState.entrants.has(message.author.id)) {
return;
}
team = raceState.entrants.get(message.author.id).team;
if (team === "") {
return;
}
raceState.disbandTeam(team);
if (isILRace() && !raceState.hasTeams()) {
categoryName = "Individual Levels";
}
message.channel.send("**" + team + "** has been disbanded.");
}
// !ff/!forfeit/!leave/!exit/!unrace
forfeitCmd = (message) => {
// Check if admin is FF'ing for someone else
ffId = message.author.id;
username = helpers.username(message);
if (message.member.roles.cache.some(role => role.name === "Admin" || role.name === "Moderator")) {
params = message.content.trim().split(" ");
if (params.length > 1) {
ffId = params[1].replace("<@!", "").replace(">", "").trim();
username = params[1].trim() + " (via " + helpers.username(message) + ")";
}
}
if (!raceState.entrants.has(ffId)){
// Can't leave if you're not in the race, dummy
return;
}
if (raceState.state === State.JOINING) {
// Leave race completely if the race hasn't started yet
if (raceState.removeEntrant(ffId)) {
if (raceState.entrants.size === 0) {
// Close down race if this is the last person leaving
message.channel.send(username + " has left the race. Closing race.");
raceState = new RaceState();
if (isILRace()) {
categoryName = helpers.normalizeCategory(gameName, null);
}
} else {
if (helpers.isOneTeamRegistered(raceState)) {
// If only one team is left, make sure at least one of its members is unreadied
allReady = true;
raceState.entrants.forEach((entrant) => {
if (!entrant.ready) {
allReady = false;
}
});
if (allReady) {
raceState.entrants.values().next().value.ready = false;
}
}
message.channel.send(username + " has left the race.");
if (raceState.entrants.size === 1) {
// If only one person is left now, make sure they are marked as unready
raceState.entrants.forEach((entrant) => { entrant.ready = false; });
}
if (isILRace() && !raceState.hasTeams()) {
categoryName = "Individual Levels";
}
// If everyone left is ready, start the race
if (raceState.isEveryoneReady()) {
doCountDown(message);
}
}
}
} else if (raceState.state === State.ACTIVE || raceState.state === State.COUNTDOWN) {
if (raceState.ffIds.includes(ffId) || raceState.doneIds.includes(ffId)) {
// If this person has already finished the current race, mark them to leave once the race is over
if (isILRace()) {
raceState.leavingWhenDone.add(ffId);
message.channel.send(username + " has left the race.");
}
} else {
// Otherwise mark them as forfeited
helpers.doForWholeTeam(raceState, ffId, (e) => raceState.ffIds.push(e.message.author.id));
team = raceState.entrants.get(ffId).team;
message.channel.send((team === "" ? username : "**" + team + "**") + " has forfeited (use `!unforfeit` to rejoin if this was an accident).");
// Check if everyone forfeited
if (raceState.ffIds.length + raceState.doneIds.length === raceState.entrants.size) {
if (raceState.state === State.COUNTDOWN) {
stopCountDown();
if (isILRace()) {
newIL();
raceDoneWarningTimeout = setTimeout(() => { message.channel.send("Everyone forfeited. IL not counted."); }, 1000);
} else {
raceState = new RaceState();
raceDoneWarningTimeout = setTimeout(() => { message.channel.send("Everyone forfeited. Closing race."); }, 1000);
}
} else {
doEndRace(message);
}
}
}
}
}
// !uff/!unforfeit
unforfeitCmd = (message) => {
if (!raceState.entrants.has(message.author.id)){
// Can't unforfeit if you're not in the race
return;
}
if (raceState.state === State.ACTIVE || raceState.state === State.COUNTDOWN || raceState.state === State.DONE) {
ufPlayers = [];
helpers.doForWholeTeam(raceState, message.author.id, (e) => ufPlayers.push(e.message.author.id));
if (ufPlayers.length > 0) {
ufPlayers.forEach((id) => {
if (raceState.leavingWhenDone.has(id)) {
raceState.leavingWhenDone.delete(id);
}
raceState.ffIds = helpers.arrayRemove(raceState.ffIds, id);
});
if (raceState.state === State.Done) {
raceState.state = State.ACTIVE;
}
clearTimeout(raceDoneTimeout);
clearTimeout(raceDoneWarningTimeout);
message.react(emotes.acknowledge);
}
}
}
// !ready
readyCmd = (message) => {
if (raceState.state !== State.JOINING) {
return;
}
// Don't allow readying up if only one person has joined
if (raceState.entrants.size === 1 && raceState.entrants.has(message.author.id)) {
message.channel.send("Need more than one entrant before starting!");
return;
}
if (!raceState.entrantIsReady(message.author.id)) {
// Mark as ready
raceState.addEntrant(message);
raceState.entrants.get(message.author.id).ready = true;
// Start countdown if everyone is ready
if (raceState.isEveryoneReady()) {
// Don't start if only one team has joined
if (helpers.isOneTeamRegistered(raceState)) {
message.channel.send("Can't ready up/start; everyone is on the same team!");
raceState.entrants.get(message.author.id).ready = false;
return;
}
doCountDown(message);
}
message.react(emotes.acknowledge);
}
}
// !unready
unreadyCmd = (message) => {
unforfeitCmd(message);
if (raceState.state === State.JOINING || raceState.state === State.COUNTDOWN) {
if (raceState.entrantIsReady(message.author.id)) {
raceState.entrants.get(message.author.id).ready = false;
message.react(emotes.acknowledge);
// If someone unready'd during countdown, stop the countdown
if (raceState.state === State.COUNTDOWN) {
raceState.state = State.JOINING;
stopCountDown();
message.channel.send(helpers.username(message) + " isn't ready; stopping countdown.");
}
}
}
}
// !d/!done
doneCmd = (message) => {
// Check if admin is done'ing for someone else
doneId = message.author.id;
username = helpers.mention(message.author);
if (message.member.roles.cache.some(role => role.name === "Admin" || role.name === "Moderator")) {
params = message.content.trim().toLowerCase().replace("! d", "!d").split(" ");
if (params.length > 1) {
doneId = params[1].replace("<@!", "").replace(">", "").trim();
username = params[1].trim() + " (via " + helpers.username(message) + ")";
}
}
if (raceState.state !== State.ACTIVE || !raceState.entrants.has(doneId) || raceState.doneIds.includes(doneId) || raceState.ffIds.includes(doneId)) {
return;
}
time = message.createdTimestamp / 1000 - raceState.startTime;
helpers.doForWholeTeam(raceState, doneId, (e) => {
e.doneTime = time;
raceState.doneIds.push(e.message.author.id);
});
raceState.doneIds.sort((id1, id2) => raceState.entrants.get(id1).doneTime - raceState.entrants.get(id2).doneTime);
// Calculate Elo diff
inProgress = [];
teamMap = new Map();
raceState.entrants.forEach((entrant) => {
id = entrant.message.author.id;
teamMap.set(id, entrant.team);
if (!raceState.doneIds.includes(id) && !raceState.ffIds.includes(id)) {
inProgress.push(id);
}
});
sortedRacerList = raceState.doneIds.concat(inProgress).concat(raceState.ffIds);
stats = helpers.retrievePlayerStats(sortedRacerList, client.getUserStatsForCategory, gameName, categoryName, teamMap);
eloId = doneId;
if (teamMap.get(doneId) !== "") {
eloId = "!team " + teamMap.get(doneId);
}