forked from LakeYS/Discord-Trivia-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtriviabot.js
1747 lines (1465 loc) · 57.4 KB
/
triviabot.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 entities = require("html-entities").AllHtmlEntities;
const fs = require("fs");
const JSON = require("circular-json");
var ConfigData = require("./lib/config.js")(process.argv[2]);
var Config = ConfigData.config;
var ConfigLocal = {};
var Trivia = exports;
// getConfigValue(value, channel, guild)
// channel: Unique identifier for the channel. If blank, falls back to guild.
// If detected as a discord.js TextChannel object, automatically fills the
// ID for itself and the guild.
// guild: Unique identifier for the server. If blank, falls back to global.
function getConfigVal(value, channel, guild) {
if(typeof channel !== "undefined") {
// discord.js class auto-detection
if(channel.type === "text") {
guild = channel.guild.id;
channel = channel.id;
}
else if(channel.type === "dm") {
channel = channel.id;
}
}
// "channel" refers to the channel's ID.
var file = `./Options/config_${channel}.json`;
if(typeof channel !== "undefined" && fs.existsSync(file)) {
if(typeof ConfigLocal[channel] === "undefined") {
// If the data isn't in the cache, load it from file.
if(ConfigData.localOptions.includes(value)) {
var currentConfig;
try {
currentConfig = fs.readFileSync(file).toString();
currentConfig = JSON.parse(currentConfig);
// Cache the data so it doesn't need to be re-read.
// This also eliminates issues if the file is changed without restarting.
ConfigLocal[channel] = currentConfig;
// If the value doesn't exist, will attempt to fall back to global
if(typeof currentConfig[value] !== "undefined") {
return currentConfig[value];
}
} catch(error) {
// If this fails, fall back to default config and drop an error in the console.
console.log(`Failed to retrieve config option "${value}". Default option will be used instead.`);
console.log(error.stack);
}
}
}
else {
// This data is already in the cache, return it from there.
if(typeof ConfigLocal[channel][value] !== "undefined") {
return ConfigLocal[channel][value];
}
}
}
guild;
if(value.toLowerCase().includes("token")) {
throw new Error("Attempting to retrieve a token through getConfigVal. This may indicate a bad module or other security risk.");
}
return Config[value];
}
Trivia.getConfigVal = getConfigVal;
function setConfigVal(value, newValue, skipOverride, localID) {
var isLocal = typeof localID !== "undefined";
if(skipOverride !== true || !getConfigVal("config-commands-enabled")) {
// TEMPORARY: This is an extra failsafe to make sure this only runs when intended.
return;
}
if(value.toLowerCase().includes("token")) {
return -1;
}
var file = ConfigData.configFile;
var configToWrite = JSON.parse(JSON.stringify(Config));
if(isLocal) {
if(isLocal) {
file = `./Options/config_${localID}.json`;
}
// Get the value first so the file caches in case it hasn't already.
getConfigVal(value, localID);
if(fs.existsSync(file)) {
configToWrite = fs.readFileSync(file).toString();
configToWrite = JSON.parse(configToWrite);
}
// If the file doesn't exist, use the global config.
}
if(newValue === null) {
delete configToWrite[value.toLowerCase()];
}
else {
configToWrite[value.toLowerCase()] = newValue;
}
if(isLocal) {
file = `./Options/config_${localID}.json`;
// Filter out the options that are not global values.
for(var key in configToWrite) {
if(!ConfigData.localOptions.includes(key)) {
delete configToWrite[key];
}
}
}
fs.writeFile(file, JSON.stringify(configToWrite, null, "\t"), "utf8", (err) => {
if(err) {
throw err;
}
});
}
Trivia.setConfigVal = setConfigVal;
global.client.on("ready", () => {
// Initialize restricted channels
var restrictedChannelsInput = getConfigVal("channel-whitelist");
Trivia.restrictedChannels = [];
if(typeof restrictedChannelsInput !== "undefined" && restrictedChannelsInput.length !== 0) {
// Can't use for..in here because is isn't supported by Map objects.
global.client.channels.forEach((channel) => {
for(var i in restrictedChannelsInput) {
var channelInput = restrictedChannelsInput[i];
if(Trivia.restrictedChannels.length === restrictedChannelsInput.length) {
break;
}
if(channelInput === channel.id.toString()) {
Trivia.restrictedChannels.push(channel.id);
}
else if(channelInput.toString().replace("#", "").toLowerCase() === channel.name) {
Trivia.restrictedChannels.push(channel.id);
}
}
});
}
});
// TODO: Use String.fromCharCode(65+letter) instead of this array?
const Letters = ["A", "B", "C", "D"];
// Convert the hex code to decimal so Discord can read it.
Trivia.embedCol = Buffer.from(getConfigVal("embed-color").padStart(8, "0"), "hex").readInt32BE(0);
var Database = "";
if(getConfigVal("database-merge")) {
// TODO: Rather than killing the base process, the manager should
// do this automatically when an initial error is thrown.
if(!Config.databaseURL.startsWith("file://")) {
console.error("A file path starting with 'file://' must be specified when the database merger is enabled.");
global.client.shard.send({evalStr: "process.exit();"});
}
Database = require("./lib/database/mergerdb.js")(Config);
}
else {
Database = Config.databaseURL.startsWith("file://")?require("./lib/database/filedb.js")(Config):require("./lib/database/opentdb.js")(Config);
}
if(typeof Database === "undefined" || Database.error) {
console.error("Failed to load the database.");
global.client.shard.send({evalStr: "process.exit();"});
}
Trivia.database = Database;
var game = {};
global.questions = [];
// Generic message sending function.
// This is to avoid repeating the same error catchers throughout the script.
// channel: Channel ID
// author: Author ID (Omit to prevent error messages from going to the author's DMs)
// msg: Message Object
// callback: Callback Function (Can be used to detect error/success and react)
// noDelete: If enabled, message will not auto-delete even if configured to
Trivia.send = function(channel, author, msg, callback, noDelete) {
channel.send(msg)
.catch((err) => {
if(typeof author !== "undefined") {
if(channel.type !== "dm") {
var str = "";
if(err.message.includes("Missing Permissions")) {
str = "\n\nThe bot does not have sufficient permission to send messages in this channel. This bot requires the \"Read Messages\", \"Send Messages\", \"Embed Links\" permissions in order to work.";
}
if(err.message.includes("Missing Access")) {
str = "\n\nThe bot does not have permission to read messages in this channel. This bot requires the \"Read Messages\", \"Send Messages\", \"Embed Links\" permissions in order to work.";
}
author.send({embed: {
color: 14164000,
description: `TriviaBot is unable to send messages in this channel:\n${err.message.replace("DiscordAPIError: ","")} ${str}`
}})
.catch(() => {
console.warn(`Failed to send message to user ${author.id}, DM failed. Dumping message data...`);
console.log(msg);
console.log("Dumped message data.");
});
}
else {
console.warn(`Failed to send message to user ${author.id}. (already in DM)`);
}
}
else {
console.warn("Failed to send message to channel, user object nonexistent. Dumping message data...");
console.log(msg);
}
if(typeof callback === "function") {
callback(void 0, err);
}
})
.then((msg) => {
if(typeof callback === "function") {
callback(msg);
}
if(getConfigVal("auto-delete-msgs", channel) && noDelete !== true) {
setTimeout(() => {
msg.delete();
}, 15000);
}
});
};
Trivia.commands = {};
var commands = Trivia.commands;
function isFallbackMode(channel) {
if(getConfigVal("fallback-mode")) {
if(typeof getConfigVal("fallback-exceptions") !== "undefined" && getConfigVal("fallback-exceptions").indexOf(channel) !== -1) {
// Return if specified channel is an exception
return;
}
else {
return true;
}
}
}
// getTriviaQuestion
// Returns a promise, fetches a random question from the database.
// If initial is set to true, a question will not be returned. (For initializing the cache)
// If tokenChannel is specified (must be a discord.js TextChannel object), a token will be generated and used.
async function getTriviaQuestion(initial, tokenChannel, tokenRetry, isFirstQuestion, category, typeInput, difficultyInput) {
var length = global.questions.length;
var toReturn;
// Check if there are custom arguments
var isCustom = false;
if(typeof category !== "undefined" || typeof typeInput !== "undefined" || typeof difficultyInput !== "undefined") {
isCustom = true;
}
// To keep the question response quick, the bot always stays one question ahead.
// This way, we're never waiting for the database to respond.
if(typeof length === "undefined" || length < 2 || isCustom) {
// We need a new question, either due to an empty cache or because we need a specific category.
var options = {};
options.category = category; // Pass through the category, even if it's undefined.
if(isCustom || Config.databaseURL.startsWith("file://")) {
options.amount = 1;
}
else {
options.amount = getConfigVal("database-cache-size");
}
options.type = typeInput;
options.difficulty = difficultyInput;
// Get a token if one is requested.
var token;
if(typeof tokenChannel !== "undefined") {
try {
token = await Database.getTokenByIdentifier(tokenChannel.id);
if(getConfigVal("debug-mode")) {
Trivia.send(tokenChannel, void 0, `*DB Token: ${token}*`);
}
} catch(error) {
// Something went wrong. We'll display a warning but we won't cancel the game.
console.log(`Failed to generate token for channel ${tokenChannel.id}: ${error.message}`);
// Skip display of session token messages if a pre-defined error message has been written.
if(typeof Trivia.maintenanceMsg !== "string") {
Trivia.send(tokenChannel, void 0, {embed: {
color: 14164000,
description: `Error: Failed to generate a session token for this channel. You may see repeating questions. (${error.message})`
}});
}
}
if(typeof token !== "undefined" && (isCustom || Config.databaseURL.startsWith("file://")) ) {
// Set the token and continue.
options.token = token;
}
}
var json = {};
var err;
try {
json = await Database.fetchQuestions(options);
if(getConfigVal("debug-database-flush") && !tokenRetry && typeof token !== "undefined") {
err = new Error("Token override");
err.code = 4;
throw err;
}
} catch(error) {
if(error.code === 4 && typeof token !== "undefined") {
// Token empty, reset it and start over.
if(tokenRetry !== 1) {
try {
await Database.resetToken(token);
} catch(error) {
console.log(`Failed to reset token - ${error.message}`);
throw new Error(`Failed to reset token - ${error.message}`);
}
if(!isFirstQuestion) {
if(typeof category === "undefined") {
Trivia.send(tokenChannel, void 0, "You've played all of the available questions! Questions will start to repeat.");
}
else {
Trivia.send(tokenChannel, void 0, "You've played all of the questions in this category! Questions will start to repeat.");
}
}
// Start over now that we have a token.
return await getTriviaQuestion(initial, tokenChannel, 1, isFirstQuestion, category, typeInput, difficultyInput);
}
else {
if(isFirstQuestion) {
err = new Error("There are no questions available under the current configuration.");
err.code = -1;
throw err;
}
else {
// This shouldn't ever happen.
throw new Error("Token reset loop.");
}
}
}
else {
// If an override has been set, show a shortened message instead
if(typeof Trivia.maintenanceMsg !== "string") {
console.log("Received error from the trivia database!");
console.log(error);
console.log(json);
}
else {
console.log("Error from trivia database, displaying canned response");
}
// Delete the token so we'll generate a new one next time.
// This is to fix the game in case the cached token is invalid.
if(typeof token !== "undefined") {
delete Database.tokens[tokenChannel.id];
}
// Author is passed through; Trivia.send will handle it if author is undefined.
throw new Error(`Failed to query the trivia database with error code ${json.response_code} (${Database.responses[json.response_code]}; ${error.message})`);
}
}
finally {
global.questions = json;
}
}
if(!initial) {
// Just in case, check the cached question count first.
if(global.questions.length < 1) {
throw new Error("Received empty response while attempting to retrieve a Trivia question.");
}
else {
toReturn = global.questions[0];
delete global.questions[0];
global.questions = global.questions.filter((val) => Object.keys(val).length !== 0);
return toReturn;
}
}
}
// Initialize the question cache
if(!Config.databaseURL.startsWith("file://")) {
getTriviaQuestion(1)
.catch((err) => {
console.log(`An error occurred while attempting to initialize the question cache:\n ${err}`);
});
}
// Function to end trivia games
function triviaEndGame(id) {
if(typeof game[id] === "undefined") {
console.warn("Attempting to clear empty game, ignoring.");
return;
}
if(typeof game[id].timeout !== "undefined") {
clearTimeout(game[id].timeout);
}
if(game[id].isLeagueGame) {
Trivia.leaderboard.writeScores(game[id].scores, game[id].guildId, ["Monthly", "Weekly"], game[id].config.leagueName);
}
delete game[id];
}
Trivia.applyBonusMultiplier = (id, channel, userID) => {
var score = getConfigVal("score-value", channel)[game[id].difficulty];
var multiplier;
var multiplierBase = getConfigVal("score-multiplier-max", channel);
if(multiplierBase !== 0) {
var index = Object.keys(game[id].participants).indexOf(userID)+1;
// Score multiplier equation
multiplier = multiplierBase/index+1;
// Don't apply if the number is negative or passive.
if(multiplier > 1) {
var bonus = Math.floor((score*multiplier)-score);
return bonus;
}
}
};
// # Trivia.doAnswerReveal #
// Ends the round, reveals the answer, and schedules a new round if necessary.
// TODO: Refactor (clean up and fix gameEndedMsg being relied on as a boolean check)
Trivia.doAnswerReveal = (id, channel, answer, importOverride) => {
if(typeof game[id] === "undefined" || !game[id].inProgress) {
return;
}
game[id].config = game[id].config || {};
var roundTimeout = getConfigVal("round-timeout", channel);
if(typeof game[id].message !== "undefined" && getConfigVal("auto-delete-msgs", channel)) {
game[id].message.delete()
.catch((err) => {
console.log(`Failed to delete message - ${err.message}`);
});
}
// Quick fix for timeouts not clearing correctly.
if(answer !== game[id].answer && !importOverride) {
console.warn(`WARNING: Mismatched answers in timeout for game ${id} (${answer}||${game[id].answer})`);
return;
}
game[id].inRound = 0;
// Custom options
if(typeof game[id].config !== "undefined") {
// Custom round count subtracts by 1 until reaching 0, then the game ends.
if(typeof game[id].config.customRoundCount !== "undefined") {
game[id].config.customRoundCount = game[id].config.customRoundCount-1;
if(typeof game[id].config.intermissionTime !== "undefined" && game[id].config.customRoundCount <= game[id].config.totalRoundCount/2) {
roundTimeout = game[id].config.intermissionTime;
Trivia.send(channel, void 0, `Intermission - Game will resume in ${roundTimeout/60000} minute${roundTimeout/1000===1?"":"s"}.`);
game[id].config.intermissionTime = void 0;
}
else if(game[id].config.customRoundCount <= 0) {
setTimeout(() => {
Trivia.stopGame(channel, true);
return;
}, 100);
}
}
}
var correctUsersStr = "**Correct answers:**\n";
var scoreStr = "";
// If only one participant, we'll only need the first user's score.
if(!getConfigVal("disable-score-display", channel)) {
var scoreVal = game[id].scores[Object.keys(game[id].correctUsers)[0]];
if(typeof scoreVal !== "undefined") {
if(isNaN(game[id].scores[ Object.keys(game[id].correctUsers)[0] ])) {
console.log("WARNING: NaN score detected, dumping game data...");
console.log(game[id]);
}
scoreStr = `(${scoreVal.toLocaleString()} points)`;
}
}
var gameEndedMsg = "", gameFooter = "";
var doAutoEnd = 0;
if(game[id].cancelled) {
gameEndedMsg = "\n\n*Game ended by admin.*";
}
else if(Object.keys(game[id].participants).length === 0 && !game[id].config.useFixedRounds) {
// If there were no participants...
// This is skipped in fixed rounds.
if(game[id].emptyRoundCount+1 >= getConfigVal("rounds-end-after", channel)) {
doAutoEnd = 1;
gameEndedMsg = "\n\n*Game ended.*";
} else {
game[id].emptyRoundCount++;
// Round end warning after we're halfway through the inactive round cap.
if(!getConfigVal("round-end-warnings-disabled", channel) && game[id].emptyRoundCount >= Math.ceil(getConfigVal("rounds-end-after", channel)/2)) {
var roundEndCount = getConfigVal("rounds-end-after", channel.id)-game[id].emptyRoundCount;
gameFooter += `Game will end in ${roundEndCount} round${roundEndCount===1?"":"s"} if there is no activity.`;
}
}
} else {
// If there are participants and the game wasn't force-cancelled...
game[id].emptyRoundCount = 0;
doAutoEnd = 0;
}
if((gameEndedMsg === "" || getConfigVal("disable-score-display", channel)) && !getConfigVal("full-score-display", channel) ) {
var truncateList = 0;
if(Object.keys(game[id].correctUsers).length > 32) {
truncateList = 1;
}
// ## Normal Score Display ## //
if(Object.keys(game[id].correctUsers).length === 0) {
if(Object.keys(game[id].participants).length === 1) {
correctUsersStr = `Incorrect, ${Object.values(game[id].participants)[0]}!`;
}
else {
correctUsersStr = correctUsersStr + "Nobody!";
}
}
else {
if(Object.keys(game[id].participants).length === 1) {
// Only one player overall, simply say "Correct!"
// Bonus multipliers don't apply for single-player games
correctUsersStr = `Correct, ${Object.values(game[id].correctUsers)[0]}! ${scoreStr}`;
}
else {
// More than 10 correct players, player names are separated by comma to save space.
var comma = ", ";
var correctCount = Object.keys(game[id].correctUsers).length;
// Only show the first 32 scores if there are a lot of players.
// This prevents the bot from potentially overflowing the embed character limit.
if(truncateList) {
correctCount = 32;
}
for(var i = 0; i <= correctCount-1; i++) {
if(i === correctCount-1) {
comma = "";
}
else if(correctCount <= 10) {
comma = "\n";
}
var score = game[id].scores[ Object.keys(game[id].correctUsers)[i] ];
var bonusStr = "";
var bonus = Trivia.applyBonusMultiplier(id, channel, Object.keys(game[id].correctUsers)[i]);
if(getConfigVal("debug-log")) {
console.log(`Applied bonus score of ${bonus} to user ${Object.keys(game[id].correctUsers)[i]}`);
}
if(score !== score+bonus && typeof bonus !== "undefined") {
bonusStr = ` + ${bonus} bonus`;
}
else {
bonus = 0;
}
if(!getConfigVal("disable-score-display", channel)) {
scoreStr = ` (${score.toLocaleString()} pts${bonusStr})`;
}
// Apply bonus after setting the string.
game[id].scores[ Object.keys(game[id].correctUsers)[i] ] = score+bonus;
correctUsersStr = `${correctUsersStr}${Object.values(game[id].correctUsers)[i]}${scoreStr}${comma}`;
}
if(truncateList) {
var truncateCount = Object.keys(game[id].correctUsers).length-32;
correctUsersStr = `${correctUsersStr}\n*+ ${truncateCount} more*`;
}
}
}
}
else {
// ## Game-Over Score Display ## //
var totalParticipantCount = Object.keys(game[id].totalParticipants).length;
if(gameEndedMsg === "") {
correctUsersStr = `**Score${totalParticipantCount!==1?"s":""}:**`;
} else {
correctUsersStr = `**Final score${totalParticipantCount!==1?"s":""}:**`;
}
if(totalParticipantCount === 0) {
correctUsersStr = `${correctUsersStr}\nNone`;
}
else {
correctUsersStr = `${correctUsersStr}\n${Trivia.leaderboard.makeScoreStr(game[id].scores, game[id].totalParticipants)}`;
}
}
if(gameFooter !== "") {
gameFooter = "\n\n" + gameFooter;
}
var answerStr = "";
if(getConfigVal("reveal-answers", channel) === true) { // DELTA: Answers will be not shown in the Summary
answerStr = `${game[id].gameMode!==2?`**${Letters[game[id].correctId]}:** `:""}${entities.decode(game[id].answer)}\n\n`;
}
Trivia.send(channel, void 0, {embed: {
color: game[id].color,
description: `${answerStr}${correctUsersStr}${gameEndedMsg}${gameFooter}`
}}, (msg, err) => {
if(typeof game[id] !== "undefined") {
// NOTE: Participants check is repeated below in Trivia.doGame
if(!err && !doAutoEnd) {
game[id].timeout = setTimeout(() => {
if(getConfigVal("auto-delete-msgs", channel)) {
msg.delete()
.catch((err) => {
console.log(`Failed to delete message - ${err.message}`);
});
}
Trivia.doGame(id, channel, void 0, 1);
}, roundTimeout);
}
else {
game[id].timeout = void 0;
triviaEndGame(id);
}
}
}, true);
};
// # parseAnswerHangman # //
// This works by parsing the string, and if it matches the answer, passing it
// to parseAnswer as the correct letter.
Trivia.parseAnswerHangman = function(str, id, userId, username, scoreValue) {
var input = str.toLowerCase();
// Decode and remove all non-alphabetical characters
var answer = entities.decode(game[id].answer).toLowerCase().replace(/\W/g, "");
// Return -1 if the input is a command.
// If the input is much longer than the actual answer, assume that it is not an attempt to answer.
if(input.startsWith(getConfigVal("prefix", id)) || input.length > answer.length*2) {
return -1;
}
if(input.replace(/\W/g, "") === answer) {
return Trivia.parseAnswer(Letters[game[id].correctId], id, userId, username, scoreValue);
}
else {
// The string doesn't match, so we'll pass the first incorrect answer.
var incorrect = Letters.slice(0); // Copy to avoid modifying it
incorrect.splice(game[id].correctId, 1);
return Trivia.parseAnswer(incorrect[0], id, userId, username, scoreValue);
}
};
// # Trivia.parseAnswer # //
// Parses a user's letter answer and scores it accordingly.
// TODO: Refactor this to decouple participant counting from answer processing.
// Str: Letter answer -- id: channel identifier
// scoreValue: Score value from the config file.
Trivia.parseAnswer = function (str, id, userId, username, scoreValue) {
if(!game[id].inRound) {
// Return -1 since there is no game.
return -1;
}
// If they already answered and configured to do so, don't accept subsquent answers.
if(getConfigVal("accept-first-answer-only", id) && typeof game[id].participants[userId] !== "undefined") {
return;
}
if((str === "A" || str === "B" || game[id].isTrueFalse !== 1 && (str === "C"|| str === "D"))) {
// Add to participants if they aren't already on the list
if(game[id].inProgress && typeof game[id].participants[userId] === "undefined") {
game[id].participants[userId] = username;
game[id].totalParticipants[userId] = username;
}
// If their score doesn't exist, intialize it.
game[id].scores[userId] = game[id].scores[userId] || 0;
if(str === Letters[game[id].correctId]) {
if(typeof game[id].correctUsers[userId] === "undefined") {
game[id].correctUsers[userId] = username;
var scoreChange = 0;
if(typeof scoreValue[game[id].difficulty] === "number") {
scoreChange = scoreValue[game[id].difficulty];
}
else {
// Leave the score change at 0, display a warning.
console.warn(`WARNING: Invalid difficulty value '${game[id].difficulty}' for the current question. User will not be scored.`);
}
if(getConfigVal("debug-log")) {
console.log(`Updating score of user ${userId} (Current value: ${game[id].scores[userId]}) + ${scoreChange}.`);
}
game[id].scores[userId] += scoreChange;
if(getConfigVal("debug-log")) {
console.log(`New score for user ${userId}: ${game[id].scores[userId]}`);
}
}
}
else {
// If the answer is wrong, remove them from correctUsers if necessary
if(typeof game[id].correctUsers[userId] !== "undefined") {
if(getConfigVal("debug-log")) {
console.log(`User ${userId} changed answers, reducing score (Current value: ${game[id].scores[userId]}) by ${scoreValue[game[id].difficulty]}.`);
}
game[id].scores[userId] -= scoreValue[game[id].difficulty];
if(getConfigVal("debug-log")) {
console.log(`New score for user ${userId}: ${game[id].scores[userId]}`);
}
// Now that the name is removed, we can remove the ID.
delete game[id].correctUsers[userId];
}
}
}
else {
// Return -1 to indicate that the input is NOT a valid answer
return -1;
}
};
async function addAnswerReactions(msg, id) {
try {
await msg.react("🇦");
await msg.react("🇧");
if(typeof game[id] === "undefined" || !game[id].isTrueFalse) {
await msg.react("🇨");
await msg.react("🇩");
}
} catch (error) {
console.log(`Failed to add reaction: ${error}`);
Trivia.send(msg.channel, void 0, {embed: {
color: 14164000,
description: "Error: Failed to add reaction. This may be due to the channel's configuration.\n\nMake sure that the bot has the \"Use Reactions\" and \"Read Message History\" permissions or disable reaction mode to play."
}});
msg.delete();
triviaEndGame(id);
return;
}
}
function createObscuredAnswer(answer, hint) {
var obscuredAnswer = "";
var skipChars = [];
if(hint) {
// Randomly reveal up to 1/3 of the answer.
var charsToReveal = answer.length/3;
for(var i = 0; i <= charsToReveal; i++) {
var skipChar = Math.floor(Math.random() * answer.length);
skipChars.push(skipChar);
}
}
for(var charI = 0; charI <= answer.length-1; charI++) {
var char = answer.charAt(charI);
if(char === " ") {
obscuredAnswer = `${obscuredAnswer} `;
}
else if(skipChars.includes(charI) || char === "," || char === "\"" || char === "'" || char === ":" || char === "(" || char === ")") {
// If this character is set to be revealed or contains an exception, show it.
obscuredAnswer = `${obscuredAnswer}${char}`;
}
else {
// A thin space character (U+2009) is used so the underscores have
// a small distinguishing space between them.
// ESLint really doesn't like this, but it works great!
obscuredAnswer = `${obscuredAnswer}\\_ `;
}
}
return obscuredAnswer;
}
function doHangmanHint(channel, answer) {
var id = channel.id;
// Verify that the game is still running and that it's the same game.
if(typeof game[id] === "undefined" || !game[id].inRound || answer !== game[id].answer) {
return;
}
answer = entities.decode(answer);
// If the total string is too small, skip showing a hint.
if(answer.length < 4) {
return;
}
var hintStr = createObscuredAnswer(answer, true);
Trivia.send(channel, void 0, {embed: {
color: Trivia.embedCol,
description: `Hint: ${hintStr}`
}});
}
// # Trivia.doGame #
// TODO: Refactor and reduce args
// - id: The unique identifier for the channel that the game is in.
// - channel: The channel object that correlates with the game.
// - author: The user that started the game. Can be left 'undefined'
// if the game is scheduled.
// - scheduled: Set to true if starting a game scheduled by the bot.
// Keep false if starting on a user's command. (must
// already have a game initialized to start)
//
Trivia.doGame = async function(id, channel, author, scheduled, config, category, typeInput, difficultyInput, modeInput) {
// Check if there is a game running. If there is one, make sure it isn't frozen.
// Checks are excepted for games that are being resumed from cache or file.
if(typeof game[id] !== "undefined" && !game[id].resuming) {
if(!scheduled && typeof game[id].timeout !== "undefined" && game[id].timeout._called === true) {
// The timeout should never be stuck on 'called' during a round.
// Dump the game in the console, clear it, and continue.
console.error(`ERROR: Unscheduled game '${id}' timeout appears to be stuck in the 'called' state. Cancelling game...`);
triviaEndGame(id);
}
else if(typeof game[id].timeout !== "undefined" && game[id].timeout._idleTimeout === -1) {
// This check may not be working, have yet to see it catch any games.
// The timeout reads -1. (Can occur if clearTimeout is called without deleting.)
// Dump the game in the console, clear it, and continue.
console.error(`ERROR: Game '${id}' timeout reads -1. Game will be cancelled.`);
triviaEndGame(id);
}
else if(typeof game[id].answer === "undefined") {
console.error(`ERROR: Game '${id}' is missing information. Game will be cancelled.`);
triviaEndGame(id);
}
else if(!scheduled && game[id].inProgress === 1) {
return; // If there's already a game in progress, don't start another unless scheduled by the script.
}
}
if(commands.playAdv.advGameExists(id)) {
return;
}
// ## Permission Checks ##
// Start with the game value if defined, otherwise default to 0.
var gameMode = 0;
if(channel.type !== "dm" && typeof modeInput === "undefined") {
if(getConfigVal("use-reactions", channel)) {
gameMode = 1;
}
else if(getConfigVal("hangman-mode", channel)) {
gameMode = 2;
}
}
if(modeInput === 1) {
gameMode = 1;
}
else if(modeInput === 2) {
gameMode = 2;
}
if(gameMode === 2) {
typeInput = "multiple"; // Override to get rid of T/F questions
}
if(typeof game[id] !== "undefined") {
gameMode = game[id].gameMode || gameMode;
}
var isFirstQuestion = typeof game[id] === "undefined";
// ## Game ##
// Define the variables for the new game.
// NOTE: This is run between rounds, plan accordingly.
game[id] = {
"inProgress": 1,
"inRound": 1,
"guildId": channel.type==="text"?channel.guild.id:void 0,
"userId": channel.type!=="dm"?void 0:channel.recipient.id,
gameMode,
"category": typeof game[id]!=="undefined"?game[id].category:category,
"difficulty": void 0, // Will be defined later
"typeInput": typeof game[id]!=="undefined"?game[id].typeInput:typeInput,
"difficultyInput": typeof game[id]!=="undefined"?game[id].difficultyInput:difficultyInput,
"participants": [],
"correctUsers": {},
"totalParticipants": typeof game[id]!=="undefined"?game[id].totalParticipants:{},
"scores": typeof game[id]!=="undefined"?game[id].scores:{},
"prevParticipants": typeof game[id]!=="undefined"?game[id].participants:null,
"emptyRoundCount": typeof game[id]!=="undefined"?game[id].emptyRoundCount:null,
"isLeagueGame": typeof game[id]!=="undefined"?game[id].isLeagueGame:false,
"config": typeof game[id]!=="undefined"?game[id].config:config
};
// DELTA - Adding fixed number of rounds game
if(isFirstQuestion && getConfigVal("use-fixed-rounds", channel) !== false) {
game[id].config.customRoundCount = getConfigVal("rounds-fixed-number", channel);
game[id].config.useFixedRounds = 1;
if(getConfigVal("debug-log")) { console.log("Setting CustomRoundCount to: " + game[id].config.customRoundCount); } // DELTA - Debug output
}
// DELTA - Adding fixed number of rounds game - END
var question, answers = [], difficultyReceived, correct_answer;
try {
question = await getTriviaQuestion(0, channel, 0, isFirstQuestion, game[id].category, game[id].typeInput, game[id].difficultyInput);
// Stringify the answers in the try loop so we catch it if anything is wrong.
answers[0] = question.correct_answer.toString();
answers = answers.concat(question.incorrect_answers);
difficultyReceived = question.difficulty.toString();
correct_answer = question.correct_answer.toString();
} catch(err) {
if(typeof Trivia.maintenanceMsg === "string") {
Trivia.send(channel, author, {embed: {
color: 14164000,
description: `An error occurred while querying the trivia database:\n*${Trivia.maintenanceMsg}*`
}});
}
else {
if(err.code !== -1) {
console.log("Database query error:");
console.log(err);
}
Trivia.send(channel, author, {embed: {
color: 14164000,
description: `An error occurred while querying the trivia database:\n*${err.message}*`
}});
}
triviaEndGame(id);
}
// Make sure the game wasn't cancelled while querying the database.
if(!game[id]) {
return;
}
if(question.incorrect_answers.length === 1) {
game[id].isTrueFalse = 1;
}
var color = Trivia.embedCol;
if(getConfigVal("hide-difficulty", channel) !== true) {
switch(difficultyReceived) {