-
Notifications
You must be signed in to change notification settings - Fork 27
/
quiz.js
1368 lines (1179 loc) · 46.7 KB
/
quiz.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 state = require('./../common/static_state.js');
const assert = require('assert');
const globals = require('./../common/globals.js');
const sendStats = require('./../discord/quiz_stats.js');
const { Permissions } = require('monochrome-bot');
const quizReportManager = require('./../common/quiz/session_report_manager.js');
const quizManager = require('./../common/quiz/manager.js');
const createHelpContent = require('./../common/quiz/decks_content.js').createContent;
const getAdvancedHelp = require('./../common/quiz/decks_content.js').getAdvancedHelp;
const constants = require('./../common/constants.js');
const { FulfillmentError } = require('monochrome-bot');
const NormalGameMode = require('./../common/quiz/normal_mode.js');
const MasteryGameMode = require('./../common/quiz/mastery_mode.js');
const ConquestGameMode = require('./../common/quiz/conquest_mode.js');
const ReviewGameMode = require('./../common/quiz/review_mode.js');
const saveManager = require('./../common/quiz/pause_manager.js');
const deckLoader = require('./../common/quiz/deck_loader.js');
const DeckCollection = require('./../common/quiz/deck_collection.js');
const Session = require('./../common/quiz/session.js');
const trimEmbed = require('./../common/util/trim_embed.js');
const audioConnectionManager = require('./../discord/audio_connection_manager.js');
const MAXIMUM_UNANSWERED_QUESTIONS_DISPLAYED = 20;
const MAX_INTERMEDIATE_CORRECT_ANSWERS_FIELD_LENGTH = 275;
const NEW_QUESTION_DELAY_IN_MS_FOR_USER_OVERRIDE = 3000;
const MASTERY_NAME = 'conquest';
const CONQUEST_NAME = 'inferno';
const MASTERY_EXTENSION = `-${MASTERY_NAME}`;
const CONQUEST_EXTENSION = `-${CONQUEST_NAME}`;
const INTERMEDIATE_ANSWER_TRUNCATION_REPLACEMENT = ' [...]';
function createMasteryModeDisabledString(prefix) {
return `Conquest Mode is not enabled in this channel. Please do it in a different channel, or in DM, or ask a server admin to enable it by saying **${prefix}settings quiz/japanese/conquest_and_inferno_enabled enabled**`;
}
function createConquestModeDisabledString(prefix) {
return `Inferno Mode is not enabled in this channel. Please do it in a different channel, or in DM, or ask a server admin to enable it by saying **${prefix}settings quiz/japanese/conquest_and_inferno_enabled enabled**`;
}
function createTitleOnlyEmbedWithColor(title, color) {
return {
embed: {
title,
color,
},
};
}
function createTitleOnlyEmbed(title) {
return createTitleOnlyEmbedWithColor(title, constants.EMBED_NEUTRAL_COLOR);
}
function getFinalAnswerLineForQuestionAndAnswerLinkAnswer(card) {
return `${card.question} ([${card.answer.join(', ')}](${card.dictionaryLink}))`;
}
function getFinalAnswerLineForQuestionAndAnswerBoldAnswer(card) {
return `-- ${card.question} (**${card.answer.join(', ')}**)`;
}
function getFinalAnswerLineForQuestionAndAnswerLinkQuestion(card) {
return `[${card.question}](${card.dictionaryLink}) (${card.answer.join(', ')})`;
}
function getFinalAnswerLineForAnswerOnly(card) {
return `[${card.answer.join(',')}](${card.dictionaryLink})`;
}
function getFinalAnswerLineForQuestionOnly(card) {
return `[${card.question}](${card.dictionaryLink})`;
}
function getFinalAnswerLineForJpTestAudio(card) {
const uri = `http://japanesetest4you.com/mp3/${card.question}`
return `[${card.question}](${uri}) (${card.answer.join(', ')})`;
}
function getFinalAnswerLineForForvoAudioLink(card) {
const answer = card.answer[0];
const uri = `https://forvo.com/word/${encodeURIComponent(answer)}/#ja`;
return `[${answer}](${uri})`;
}
function getFinalAnswerLineForHentaiganaComment(card) {
const answer = card.answer[0];
return `${card.meaning} (${card.answer.join(', ')})`;
}
const FinalAnswerListElementStrategy = {
QUESTION_AND_ANSWER_LINK_QUESTION: getFinalAnswerLineForQuestionAndAnswerLinkQuestion,
QUESTION_AND_ANSWER_LINK_ANSWER: getFinalAnswerLineForQuestionAndAnswerLinkAnswer,
QUESTION_AND_ANSWER_BOLD_ANSWER: getFinalAnswerLineForQuestionAndAnswerBoldAnswer,
ANSWER_ONLY: getFinalAnswerLineForAnswerOnly,
QUESTION_ONLY: getFinalAnswerLineForQuestionOnly,
JPTEST_FOR_YOU_AUDIO_LINK: getFinalAnswerLineForJpTestAudio,
FORVO_AUDIO_LINK: getFinalAnswerLineForForvoAudioLink,
HENTAIGANA_COMMENT: getFinalAnswerLineForHentaiganaComment,
};
function truncateIntermediateAnswerString(str) {
if (str.length > MAX_INTERMEDIATE_CORRECT_ANSWERS_FIELD_LENGTH) {
const substringStart = 0;
const substringEnd = MAX_INTERMEDIATE_CORRECT_ANSWERS_FIELD_LENGTH -
INTERMEDIATE_ANSWER_TRUNCATION_REPLACEMENT.length;
return str.substring(substringStart, substringEnd) + INTERMEDIATE_ANSWER_TRUNCATION_REPLACEMENT;
}
return str;
}
function getIntermediateAnswerLineForCorrectAnswers(card) {
return truncateIntermediateAnswerString(card.answer.join('\n'));
}
function getIntermediateAnswerLineForAnswersWithScorersAndPointsFirst(
card,
answersForUser,
pointsForAnswer,
) {
const userIds = Object.keys(answersForUser);
const lines = [];
userIds.forEach((userId) => {
const answers = answersForUser[userId];
answers.forEach((answer) => {
const point = pointsForAnswer[answer];
lines.push(`${answer} (<@${userId}> got ${point} points)`);
});
});
const scorersString = lines.join('\n');
let totalString = `${scorersString}\n\n`;
const answers = card.answer;
let nextAnswerIndex = 0;
while (true) {
if (nextAnswerIndex >= answers.length) {
break;
}
const nextAnswer = answers[nextAnswerIndex];
const stringLengthWithNextAnswer = totalString.length + nextAnswer.length + 3;
nextAnswerIndex += 1;
if (stringLengthWithNextAnswer > MAX_INTERMEDIATE_CORRECT_ANSWERS_FIELD_LENGTH) {
break;
}
if (nextAnswerIndex === 1) {
totalString += nextAnswer;
} else {
totalString += ` ${nextAnswer}`;
}
}
if (nextAnswerIndex < answers.length) {
totalString += ' **and more**';
}
return totalString;
}
const IntermediateAnswerListElementStrategy = {
CORRECT_ANSWERS:
getIntermediateAnswerLineForCorrectAnswers,
ANSWERS_WITH_SCORERS_AND_POINTS_FIRST:
getIntermediateAnswerLineForAnswersWithScorersAndPointsFirst,
};
function createEndQuizMessage(quizName, scores, unansweredQuestions, aggregateLink, description, prefix, reportUri) {
const fields = [];
if (scores.length > 0) {
const finalScoresValue = scores.map((score) => {
let string = `<@${score.userId}> has ${score.totalScore} points`;
if (score.totalScore !== score.normalizedScore) {
string += ` (${Math.floor(score.normalizedScore)} for leaderboard)`;
}
return string;
}).join('\n');
fields.push({ name: 'Final Scores', value: finalScoresValue });
}
if (unansweredQuestions.length > 0) {
const unansweredQuestionsLines = unansweredQuestions.map(card =>
FinalAnswerListElementStrategy[card.discordFinalAnswerListElementStrategy](card));
if (unansweredQuestions.some(card => card.discordFinalAnswerListElementStrategy === 'HENTAIGANA_COMMENT')) {
unansweredQuestionsLines.unshift('(Discord fonts can\'t display the actual hentaigana character)');
}
let unansweredQuestionsCharacters = 0;
const separator = '\n';
for (let i = 0; i < unansweredQuestionsLines.length; i += 1) {
unansweredQuestionsCharacters += unansweredQuestionsLines[i].length + separator.length;
if (
unansweredQuestionsCharacters > constants.MAXIMUM_FIELD_LENGTH ||
i >= MAXIMUM_UNANSWERED_QUESTIONS_DISPLAYED
) {
const moreString = '...More...';
// Pop off the last lines until it's small enough.
while (
unansweredQuestionsLines.join(separator).length +
separator.length +
moreString.length >
constants.MAXIMUM_FIELD_LENGTH
) {
unansweredQuestionsLines.pop();
}
unansweredQuestionsLines.push(moreString);
break;
}
}
const unansweredQuestionsString = unansweredQuestionsLines.join('\n');
fields.push({ name: `Unanswered Questions (${unansweredQuestions.length})`, value: unansweredQuestionsString });
}
if (reportUri) {
fields.push({ name: 'Game Report', value: `[View a report for this game](${reportUri}) (and add missed questions to your custom decks)` });
}
const response = {
embed: {
title: `${quizName} Ended`,
url: aggregateLink,
description,
color: constants.EMBED_NEUTRAL_COLOR,
fields,
footer: { icon_url: constants.FOOTER_ICON_URI, text: `Say ${prefix}lb to see the server leaderboard.` },
},
};
return trimEmbed(response);
}
const afterQuizMessages = [
{
embed: {
title: 'Reviewing',
color: constants.EMBED_NEUTRAL_COLOR,
description: 'Say **<prefix>quiz review** to review the questions no one answered, or **<prefix>quiz reviewme** to review the questions you didn\'t answer (only if you did answer at least one). You can say **<prefix>quiz reviewme** somewhere else (like in a DM) if you prefer.',
},
},
{
embed: {
title: 'O, so you want Anki in Discord?',
color: constants.EMBED_NEUTRAL_COLOR,
description: `Try **Conquest Mode**. Say **<prefix>quiz${MASTERY_EXTENSION}** to learn more.`,
},
},
{
embed: {
title: 'Fonts',
color: constants.EMBED_NEUTRAL_COLOR,
description: 'You can change fonts, colors, and sizes by using the **k!settings** command and going into the **Fonts** submenu.',
},
},
{
embed: {
title: 'O, too fast/slow?',
color: constants.EMBED_NEUTRAL_COLOR,
description: 'You can change timing settings by using the **k!settings** command, or say **k!help quiz** to see how to do it per-game.',
},
},
{
embed: {
title: 'O, your lame friends don\'t use Discord?',
color: constants.EMBED_NEUTRAL_COLOR,
description: '[Play on the web](https://kotobaweb.com/)',
},
},
{
embed: {
title: 'Manual',
color: constants.EMBED_NEUTRAL_COLOR,
description: 'For advanced quiz options, [visit me on the web](https://kotobaweb.com/bot/quiz).',
},
},
{
embed: {
title: 'Stats',
color: constants.EMBED_NEUTRAL_COLOR,
description: 'Say **<prefix>quiz stats** to see your stats for the past 30 days.',
},
},
];
function createAfterQuizMessage(canReview, prefix) {
let index;
if (canReview) {
index = Math.floor(Math.random() * afterQuizMessages.length);
} else {
index = 1 + Math.floor(Math.random() * (afterQuizMessages.length - 1));
}
const afterQuizMessage = { ...afterQuizMessages[index] };
afterQuizMessage.embed = { ...afterQuizMessage.embed };
afterQuizMessage.embed.description = afterQuizMessage.embed.description.replace(/<prefix>/g, prefix);
return afterQuizMessage;
}
async function sendEndQuizMessages(
commanderMessage,
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
description,
) {
const prefix = commanderMessage.prefix;
const endQuizMessage = createEndQuizMessage(
quizName,
scores,
unansweredQuestions,
aggregateLink,
description,
prefix,
await quizReportManager.getReportUriForLocation(commanderMessage.channel),
);
await commanderMessage.channel.createMessage(endQuizMessage);
const afterQuizMessage = createAfterQuizMessage(canReview, prefix);
if (afterQuizMessage) {
return commanderMessage.channel.createMessage(afterQuizMessage);
}
return undefined;
}
function convertDatabaseFacingSaveIdToUserFacing(saveId) {
return saveId + 1;
}
function convertUserFacingSaveIdToDatabaseFacing(saveId) {
return saveId - 1;
}
function getTimeString(timestamp) {
const date = new Date(timestamp);
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}`;
}
function sendSaveMementos(msg, currentSaveMementos, recyclingBinMementos, extraContent) {
const prefix = msg.prefix;
const embed = {
title: 'Loading',
description: `You can load a save by using this command again with the number of the save you want (listed below). For example **${prefix}quiz load 1**.`,
color: constants.EMBED_NEUTRAL_COLOR,
fields: [],
};
if (currentSaveMementos.length > 0) {
embed.fields.push({
name: 'Current saves',
value: currentSaveMementos.map((memento, index) => {
return `${convertDatabaseFacingSaveIdToUserFacing(index)}: ${memento.quizType} (${getTimeString(memento.time)})`;
}).join('\n'),
});
}
if (recyclingBinMementos.length > 0) {
embed.fields.push({
name: 'Recycling bin',
value: '(You can recover old saves from here if you need to. Don\'t wait too long.)\n\n' + recyclingBinMementos.map((memento, index) => {
return `${convertDatabaseFacingSaveIdToUserFacing(index + currentSaveMementos.length)}: ${memento.quizType} (${getTimeString(memento.time)})`;
}).join('\n'),
});
}
return msg.channel.createMessage({ content: extraContent, embed }, null, msg);
}
function createCorrectPercentageField(card) {
const totalAnswers = card.answerHistory.length;
if (totalAnswers > 1) {
const totalCorrect = card.answerHistory.reduce((a, b) => (b ? a + 1 : a), 0);
const percentage = Math.floor((totalCorrect / totalAnswers) * 100);
return { name: 'Correct Answer Rate', value: `${percentage}%`, inline: true };
}
return undefined;
}
class DiscordMessageSender {
constructor(bot, commanderMessage) {
this.commanderMessage = commanderMessage;
this.bot = bot;
}
notifyStarting(inMs, quizName, quizDescription, quizLength, scoreLimit) {
const inSeconds = inMs / 1000;
const embedTitle = `Quiz Starting in ${inSeconds} seconds`;
let embedDescription = `**${quizName}**`;
if (quizDescription) {
embedDescription = `${embedDescription} - ${quizDescription}`;
}
const fields = [
{ name: 'Deck size', value: quizLength, inline: true },
];
if (scoreLimit !== Number.MAX_SAFE_INTEGER) {
fields.push({ name: 'Score limit', value: scoreLimit, inline: true });
}
return this.commanderMessage.channel.createMessage({
embed: {
title: embedTitle,
description: embedDescription,
color: constants.EMBED_NEUTRAL_COLOR,
fields,
},
});
}
stopAudio() {
const guild = this.commanderMessage.channel.guild;
if (!guild) {
return;
}
audioConnectionManager.stopPlaying(this.bot, guild.id);
}
showWrongAnswer(card, skipped, hardcore) {
this.stopAudio();
const correctAnswerFunction =
IntermediateAnswerListElementStrategy[card.discordIntermediateAnswerListElementStrategy];
const correctAnswerText = correctAnswerFunction(card, {}, {});
const fields = [
{ name: 'Correct Answers', value: correctAnswerText, inline: true },
];
const correctPercentageField = createCorrectPercentageField(card);
if (correctPercentageField) {
fields.push(correctPercentageField);
}
if (card.meaning) {
fields.push({ name: card.commentFieldName, value: card.meaning, inline: false });
}
let response = {
embed: {
title: card.deckName,
url: card.dictionaryLink,
description: skipped ? 'Question skipped!' : (hardcore ? 'No one got it right' : 'Time\'s up!'),
color: constants.EMBED_WRONG_COLOR,
fields,
footer: { icon_url: constants.FOOTER_ICON_URI, text: 'You can skip questions by saying \'skip\' or just \'s\'.' },
},
};
response = trimEmbed(response);
return this.commanderMessage.channel.createMessage(response);
}
async outputQuestionScorers(
card,
answerersInOrder,
answersForUser,
pointsForAnswer,
scoreForUser,
scoreLimit,
) {
this.stopAudio();
const scorersListText = answerersInOrder.map(answerer => `<@${answerer}> (${scoreForUser[answerer].totalScore} points)`).join('\n');
const correctAnswerFunction =
IntermediateAnswerListElementStrategy[card.discordIntermediateAnswerListElementStrategy];
const correctAnswerText = correctAnswerFunction(card, answersForUser, pointsForAnswer);
const playingToStr = scoreLimit === Number.MAX_SAFE_INTEGER ? '' : ` (playing to ${scoreLimit})`;
const fields = [
{ name: 'Correct Answers', value: correctAnswerText, inline: true },
{ name: `Scorers ${playingToStr}`, value: scorersListText, inline: true },
];
const correctPercentageField = createCorrectPercentageField(card);
if (correctPercentageField) {
fields.push(correctPercentageField);
}
if (card.meaning) {
fields.push({
name: card.commentFieldName,
value: card.meaning,
inline: !!correctPercentageField,
});
}
let response = {
embed: {
title: card.deckName,
url: card.dictionaryLink,
description: `<@${answerersInOrder[0]}> got it first!`,
color: constants.EMBED_CORRECT_COLOR,
fields,
},
};
response = trimEmbed(response);
const newMessage = await this.commanderMessage.channel.createMessage(response);
return newMessage && newMessage.id;
}
async showQuestion(question, questionId) {
let title = question.deckName;
if (question.deckProgress !== undefined) {
const percentDone = Math.floor(question.deckProgress * 100);
title = `${title} (${percentDone}% complete)`;
}
let content = {
embed: {
description: `**${title}**\n${question.instructions || ''}`,
color: constants.EMBED_NEUTRAL_COLOR,
fields: [],
},
};
let uploadInformation;
if (question.bodyAsPngBuffer) {
content.embed.image = { url: 'attachment://upload.png' };
uploadInformation = { file: question.bodyAsPngBuffer, name: 'upload.png' };
}
if (question.hintString) {
content.embed.footer = { text: question.hintString };
}
if (question.options) {
content.embed.description = `**${title}**\nType the number of the correct answer!`;
const fieldValue = question.options.map((option, index) => {
const optionCharacter = `${index + 1}`;
return `**${optionCharacter}:** ${option}`;
}).join('\n');
content.embed.fields.push({ name: 'Possible Answers', value: fieldValue });
}
if (question.bodyAsText) {
content.embed.description += '\n\n' + question.bodyAsText;
}
if (question.bodyAsImageUri) {
content.embed.image = { url: question.bodyAsImageUri };
}
if (question.bodyAsAudioUri) {
const serverId = this.commanderMessage.channel.guild.id;
const voiceChannel = audioConnectionManager.getConnectedVoiceChannelForServerId(this.bot, serverId);
content.embed.fields.push({name: 'Now playing in', value: `<#${voiceChannel.id}>`});
audioConnectionManager.play(this.bot, serverId, question.bodyAsAudioUri);
}
content = trimEmbed(content);
if (!questionId) {
const msg = await this.commanderMessage.channel.createMessage(content, uploadInformation);
return msg.id;
}
return this.bot.editMessage(this.commanderMessage.channel.id, questionId, content, uploadInformation);
}
async notifySaveSuccessful() {
this.closeAudioConnection();
const reportUri = await quizReportManager.getReportUriForLocation(this.commanderMessage.channel);
const fields = [];
if (reportUri) {
fields.push({
name: 'Game Report',
value: `[View a report for this game](${reportUri}) (and add missed questions to your custom decks)`,
});
}
const embed = {
title: 'Saved',
description: `The quiz has been saved and paused! Say **${this.commanderMessage.prefix}quiz load** later to start it again.`,
color: constants.EMBED_NEUTRAL_COLOR,
fields,
};
return this.commanderMessage.channel.createMessage({ embed });
}
notifySaveFailedNoSpace(maxSaves) {
return this.commanderMessage.channel.createMessage(createTitleOnlyEmbed(`Can't save because you already have ${maxSaves} games saved! Try finishing them sometime, or just load them then stop them to delete them. You can view and load saves by saying '${this.commanderMessage.prefix}quiz load'.`));
}
notifySaveFailedIsReview() {
return this.commanderMessage.channel.createMessage(createTitleOnlyEmbed('You can\'t save a review quiz.'));
}
notifySaving() {
return this.commanderMessage.channel.createMessage(createTitleOnlyEmbed('Saving at the next opportunity.'));
}
notifySaveFailedNotOwner() {
return this.commanderMessage.channel.createMessage(
createTitleOnlyEmbed('Only the person who started the quiz can save it. Maybe ask them nicely?'),
);
}
closeAudioConnection() {
const guild = this.commanderMessage.channel.guild;
if (!guild) {
return;
}
return audioConnectionManager.closeConnection(this.bot, guild.id);
}
notifyQuizEndedScoreLimitReached(
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
scoreLimit,
) {
const description = `The score limit of ${scoreLimit} was reached by <@${scores[0].userId}>. Congratulations!`;
this.closeAudioConnection();
return sendEndQuizMessages(
this.commanderMessage,
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
description,
);
}
notifyQuizEndedUserCanceled(
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
cancelingUserId,
) {
const description = `<@${cancelingUserId}> asked me to stop the quiz.`;
this.closeAudioConnection();
return sendEndQuizMessages(
this.commanderMessage,
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
description,
);
}
notifyQuizEndedTooManyWrongAnswers(
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
wrongAnswers,
) {
const description = `${wrongAnswers} questions in a row went unanswered. So I stopped!`;
this.closeAudioConnection();
return sendEndQuizMessages(
this.commanderMessage,
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
description,
);
}
notifyQuizEndedError(quizName, scores, unansweredQuestions, aggregateLink, canReview) {
const description = 'Sorry, I had an error and had to stop the quiz :( The error has been logged and will be addressed.';
this.closeAudioConnection();
return sendEndQuizMessages(
this.commanderMessage,
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
description,
);
}
notifyQuizEndedNoQuestionsLeft(
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
gameMode,
) {
let description;
if (gameMode.isMasteryMode || gameMode.isConquestMode) {
description = 'You have asserted your total dominance over this deck. It kneels before you in awe of your might.';
} else {
description = 'No questions left in that deck. Impressive!';
}
this.closeAudioConnection();
return sendEndQuizMessages(
this.commanderMessage,
quizName,
scores,
unansweredQuestions,
aggregateLink,
canReview,
description,
);
}
notifyStoppingAllQuizzes(quizName, scores, unansweredQuestions, aggregateLink) {
this.closeAudioConnection();
const description = 'I have to reboot for an update. I\'ll be back in about one minute :)';
return sendEndQuizMessages(
this.commanderMessage,
quizName,
scores,
unansweredQuestions,
aggregateLink,
false,
description,
);
}
notifyStopFailedUserNotAuthorized() {
this.commanderMessage.channel.createMessage(createTitleOnlyEmbed('Only a server admin can stop someone else\'s quiz in Conquest or Inferno Mode.'));
}
}
const mixtureReplacements = {
easymix: 'n5+n4+defs1+anagrams4+10k+katakana',
medmix: 'n3+defs7+9k+8k+7k+anagrams5+prefectures',
hardmix: 'n2+n1+6k+5k+defs12+defs13+onomato+numbers+anagrams6',
hardermix: '4k+3k+j2k+defs17+defs18+defs14+anagrams7+anagrams8+myouji+namae+ejtrans+hard+擬音語+kklc',
insanemix: '2k+j1k+1k+anagrams9+anagrams10+yojijukugo+countries+animals',
};
function createMasteryHelp(isEnabledInServer, prefix) {
let footerMessage = '';
if (!isEnabledInServer) {
footerMessage = `**Disabled!** ${createMasteryModeDisabledString(prefix)}`;
}
return {
embed: {
title: 'Conquest Mode',
description: `In Conquest Mode your goal is to conquer one or more entire quiz decks. If you get a question right on the first try, you won't see it again. But if you get it wrong, you'll see it again until I think you've learned it. The game ends when I think you know every card in the deck (or if you miss too many questions in a row or use **${prefix}quiz stop**).
You can use **${prefix}quiz save** and **${prefix}quiz load** to save and load progress so you can learn over a period of days or weeks or months.
To start, say **${prefix}quiz${MASTERY_EXTENSION}** plus a deck name. For example: **${prefix}quiz${MASTERY_EXTENSION} N5**. Keep in mind that if you aren't in a DM, other people can answer the questions too, and then you won't see them again.
${footerMessage}`,
color: constants.EMBED_NEUTRAL_COLOR,
footer: { icon_url: constants.FOOTER_ICON_URI, text: `You can also conquer multiple decks. For example: ${prefix}quiz${MASTERY_EXTENSION} N5+N4` },
},
};
}
function createConquestHelp(isEnabledInServer, prefix) {
let footerMessage = '';
if (!isEnabledInServer) {
footerMessage = `**Disabled!** ${createConquestModeDisabledString(prefix)}`;
}
return {
embed: {
title: 'Inferno Mode',
description: `In Inferno Mode, every time you miss a question, you have a little bit less time to answer the next one. And I might throw that question back into the deck, so try to remember it!
There is no score limit, so try to get as far as you can. You can use **${prefix}quiz save** and **${prefix}quiz load** to save and load progress.
Bring your friends! The top scorers will appear together as a team on the inferno leaderboard (when/if I make it ;)
To start, say **${prefix}quiz${CONQUEST_EXTENSION}** plus a deck name. For example: **${prefix}quiz${CONQUEST_EXTENSION} N5**.
You can override some quiz settings, however, doing so makes your final results ineligible for the leaderboard. If you want to play N5, lose half a second per wrong answer, and start with a time limit of 20 seconds, try this: **${prefix}quiz${CONQUEST_EXTENSION} N5 .5 20**.
${footerMessage}`,
color: constants.EMBED_NEUTRAL_COLOR,
},
};
}
function getScoreScopeIdFromMsg(msg) {
return msg.channel.guild ? msg.channel.guild.id : msg.channel.id;
}
function throwIfInternetCardsNotAllowed(isDm, session, internetCardsAllowed, prefix) {
if (!internetCardsAllowed && !isDm && session.containsInternetCards()) {
const message = {
embed: {
title: 'Internet decks disabled',
description: `That deck contains internet cards, but internet decks are disabled in this channel. You can try in a different channel, or in a DM, or ask a server admin to enable internet decks by saying **${prefix}settings quiz/japanese/internet_decks_enabled enabled**`,
color: constants.EMBED_NEUTRAL_COLOR,
},
};
throw new FulfillmentError({
publicMessage: message,
logDescription: 'Internet decks disabled',
});
}
}
function throwIfGameModeNotAllowed(isDm, gameMode, masteryEnabled, prefix) {
if (!masteryEnabled && !isDm &&
(gameMode.isMasteryMode ||
gameMode.isConquestMode ||
gameMode.serializationIdentifier === MasteryGameMode.serializationIdentifier ||
gameMode.serializationIdentifier === ConquestGameMode.serializationIdentifier)) {
const message = {
embed: {
title: 'Game mode disabled',
description: `That game mode is not enabled in this channel. You can try it in a different channel, or via DM, or ask a server admin to enable the game mode by saying **${prefix}settings quiz/japanese/conquest_and_inferno_enabled enabled**`,
color: constants.EMBED_NEUTRAL_COLOR,
},
};
throw new FulfillmentError({
publicMessage: message,
logDescription: 'Game mode disable',
});
}
}
function throwIfSessionInProgressAtLocation(locationId, prefix) {
if (quizManager.isSessionInProgressAtLocation(locationId)) {
const message = {
embed: {
title: 'Quiz In Progress',
description: `Only one quiz can run in a channel at a time. Try another channel, or DM. You can stop the currently running quiz by saying **${prefix}quiz stop**`,
color: constants.EMBED_NEUTRAL_COLOR,
},
};
throw new FulfillmentError({
publicMessage: message,
logDescription: 'Session in progress',
});
}
}
async function load(
bot,
msg,
userFacingSaveIdArg,
messageSender,
masteryModeEnabled,
internetCardsAllowed,
logger,
) {
// TODO: Need to prevent loading decks with internet cards if internet decks aren't enabled.
// Tech debt: The deck collection shouldn't be reloading itself.
// There should be a save restorer class to assist in that.
let userFacingSaveId = userFacingSaveIdArg;
const isDm = !msg.channel.guild;
const scoreScopeId = getScoreScopeIdFromMsg(msg);
const prefix = msg.prefix;
throwIfSessionInProgressAtLocation(msg.channel.id, prefix);
const userId = msg.author.id;
const [currentMementos, recyclingBinMementos] = await Promise.all([
(await saveManager.getSaveMementos(userId)) || [],
(await saveManager.getRestorable(userId)) || [],
]);
if (currentMementos.length === 0 && recyclingBinMementos.length === 0) {
return msg.channel.createMessage(createTitleOnlyEmbed(`I don't have any sessions I can load for you. Say ${prefix}quiz to start a new quiz.`), null, msg);
}
if (userFacingSaveId === undefined) {
return sendSaveMementos(msg, currentMementos, recyclingBinMementos);
}
const databaseFacingSaveId =
convertUserFacingSaveIdToDatabaseFacing(parseInt(userFacingSaveId, 10));
let memento;
if (databaseFacingSaveId < currentMementos.length) {
memento = currentMementos[databaseFacingSaveId];
} else if (databaseFacingSaveId - currentMementos.length < recyclingBinMementos.length) {
memento = recyclingBinMementos[databaseFacingSaveId - currentMementos.length];
await saveManager.restore(userId, memento);
} else {
return sendSaveMementos(msg, currentMementos, recyclingBinMementos, `I couldn't find save #${userFacingSaveId}. Here are the available saves.`);
}
throwIfGameModeNotAllowed(isDm, memento, masteryModeEnabled, prefix);
const saveData = await saveManager.load(memento);
const session = await Session.createFromSaveData(
msg.channel.id,
saveData,
scoreScopeId,
messageSender,
);
try {
if (session.requiresAudioConnection()) {
await audioConnectionManager.openConnectionFromMessage(bot, msg);
}
throwIfInternetCardsNotAllowed(isDm, session, internetCardsAllowed, prefix);
} catch (err) {
await saveManager.restore(msg.author.id, memento);
throw err;
}
try {
const endStatus = await quizManager.startSession(session, msg.channel.id);
if (endStatus === quizManager.END_STATUS_ERROR) {
throw new Error('The quiz manager successfully handled an error condition');
}
return undefined;
} catch (err) {
logger.error({
event: 'ERROR IN SAVED SESSION',
err,
});
await saveManager.restore(msg.author.id, memento);
return msg.channel.createMessage(`Looks like there was an error, sorry about that. I have attempted to restore your save data to its previous state, you can try to load it again with **${prefix}quiz load**. The error has been logged and will be addressed.`);
}
}
async function deleteInternetDeck(msg, searchTerm, userId) {
const deletionResult = await deckLoader.deleteInternetDeck(searchTerm, userId);
if (deletionResult === deckLoader.DeletionStatus.DELETED) {
return msg.channel.createMessage('That deck was successfully deleted.', null, msg);
} else if (deletionResult === deckLoader.DeletionStatus.DECK_NOT_FOUND) {
return msg.channel.createMessage(`I didn't find a deck called ${searchTerm}. Did you type it wrong or has it already been deleted?`, null, msg);
} else if (deletionResult === deckLoader.DeletionStatus.USER_NOT_OWNER) {
return msg.channel.createMessage('You can\'t delete that deck because you didn\'t create it.', null, msg);
}
assert(false, 'Should have returned');
return undefined;
}
function createNonReviewGameMode(isMastery, isConquest) {
if (isMastery) {
return MasteryGameMode;
} else if (isConquest) {
return ConquestGameMode;
} else {
return NormalGameMode;
}
}
function createSettings(settingsBlob, gameMode, settingsOverridesStrings) {
const settingsOverrides = settingsOverridesStrings.map(str => parseFloat(str));
const {
userScoreLimitOverride,
userTimeBetweenQuestionsOverrideInMs,
userTimeoutOverrideInMs,
gameModeSettings,
} = gameMode.parseUserOverrides(settingsOverrides);
let userNewQuestionDelayAfterUnansweredOverrideInMs;
let userNewQuestionDelayAfterAnsweredOverrideInMs;
let userAdditionalAnswerWaitTimeInMs;
if (
userTimeBetweenQuestionsOverrideInMs !== undefined &&
!Number.isNaN(userTimeBetweenQuestionsOverrideInMs)
) {
if (
userTimeBetweenQuestionsOverrideInMs < NEW_QUESTION_DELAY_IN_MS_FOR_USER_OVERRIDE
) {
userNewQuestionDelayAfterAnsweredOverrideInMs = 0;
userAdditionalAnswerWaitTimeInMs = userTimeBetweenQuestionsOverrideInMs;
} else if (
userTimeBetweenQuestionsOverrideInMs <= NEW_QUESTION_DELAY_IN_MS_FOR_USER_OVERRIDE * 2
) {
userAdditionalAnswerWaitTimeInMs =
NEW_QUESTION_DELAY_IN_MS_FOR_USER_OVERRIDE;
userNewQuestionDelayAfterAnsweredOverrideInMs =
userTimeBetweenQuestionsOverrideInMs - userAdditionalAnswerWaitTimeInMs;
} else {
userAdditionalAnswerWaitTimeInMs =
userTimeBetweenQuestionsOverrideInMs - NEW_QUESTION_DELAY_IN_MS_FOR_USER_OVERRIDE;
userNewQuestionDelayAfterAnsweredOverrideInMs =
userTimeBetweenQuestionsOverrideInMs - userAdditionalAnswerWaitTimeInMs;
}
userNewQuestionDelayAfterUnansweredOverrideInMs = userNewQuestionDelayAfterAnsweredOverrideInMs;
}