-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
1156 lines (935 loc) Β· 32.7 KB
/
index.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
/*
CREATING BIBLE QUIZZLE TELEGRAM BOT USING telegraf LIBRARY.
REFERENCES:
- https:// thedevs.network/blog/build-a-simple-telegram-bot-with-node-js
- https:// www.sohamkamani.com/blog/2016/09/21/making-a-telegram-bot/
*/
/* RUNNING IN NODE JS:
1) now -e BOT_TOKEN='<bot-token>' --public
2) npm start
(Note that (2) will run (1) as defined in the start script)
*/
// ================LIBRARIES AND VARIABLES=================//
// Initialising of Libraries
const {
Markup,
Extra
} = require('micro-bot');
const Telegraf = require('micro-bot');
const bot = new Telegraf(process.env.BOT_TOKEN, {
username: "BibleQuizzleBot"
});
// bot.use(Telegraf.log());
const fs = require('fs');
// const welcomeMessage =
// 'Welcome to Bible Quizzle, a fast-paced Bible trivia game similar to Quizzarium!\n\nTo begin the game, type /start in the bot\'s private chat, or in the group. For more information and a list of all commands, type /help';
const helpMessage =
"Bible Quizzle is a fast-paced Bible trivia game. Once the game is started, the bot will send a question. Send in your open-ended answer and the bot will give you points for the right answer. The faster you answer, the more points you get! Each question has a 50 second timer, and hints will be given every 10 seconds. Alternatively, you can call for a /hint but that costs points. Note that for all answers, numbers are in digit (0-9) form.\n\n" +
"/start - Starts a new game.\n" +
"/quick - Starts a quick game of 10 rounds with category \'all\'.\n" +
"/hint - Shows a hint and fasts-forwards timing.\n" +
"/next - Similar to /hint, except that if 2 or more people use this command, the question is skipped entirely.\n" +
"/stop - Stops the game.\n" +
"/ranking - Displays the global rankings (top 10), as well as your own.\n" +
"/suggest - Suggest questions and answers for the game (external link)!\n" +
"/eggs - Hmm, what could this be?\n" +
"/help - Displays this help message.\n";
let i = 0,
j = 0;
const categories = ["All", "Old Testament", "New Testament", "Gospels", "Prophets", "Miracles", "Kings/Judges",
"Exodus"];
const regex_alphanum = new RegExp("[A-Z0-9]", "gi");
const regex_non_alphanum = new RegExp("[^A-Z0-9]", "gi");
const ADMIN_ID = 413007985;
// ================PRE-GAME SETUP=================//
// Make Category Array from `categories`
let catArr = [],
rowArr = [];
catArr[0] = ["π " + categories[0]]; // First row is single "All" button
const nButtonsOnARow = 2;
for (i = 1; i < categories.length; i += nButtonsOnARow) {
rowArr = [];
for (j = 0; j < nButtonsOnARow; j++) {
if (i + j < categories.length)
rowArr.push("π " + categories[i + j]);
}
catArr.push(rowArr);
}
// Initialise question object
let questions = {};
compileQuestionsList = () => {
questions["all"] = JSON.parse(fs.readFileSync('questions.json', 'utf8'));
// console.log(questions["all"]);
let all_questions = questions["all"];
for (i in all_questions) {
let _cats = all_questions[i].categories;
if (_cats == null /*|| typeof _cats == "undefined"*/ ) continue;
for (j = 0; j < _cats.length; j++) {
let _cat = _cats[j].toString();
if (questions[_cat] === undefined /*|| !questions.hasOwnProperty(_cat) */ ) {
// Key doesn't exist, create empty array
questions[_cat] = [];
}
questions[_cat].push(all_questions[i]);
}
}
};
compileQuestionsList();
// Suggest Q & A
const suggestionFormURL =
"https://forms.gle/aqZ3MK8QrBGzv9PEA";
const suggestionText = "Suggest questions and answers here: " + suggestionFormURL + " !";
let _sendSuggestionLink = (ctx) => {
ctx.reply(suggestionText);
return;
};
bot.command('suggest', (ctx) => {
_sendSuggestionLink(ctx);
});
// ================UI FOR START AND CHOOSING OF CATEGORIES/ROUNDS=================//
let initGame = (ctx) => {
// Set category
// console.log("Pick a category: ", categories);
switch (Game.status) {
case "active":
case "active_wait":
return ctx.reply("A game is already in progress. To stop the game, type /stop");
case "choosing_cat":
case "choosing_category":
resetGame();
return chooseCategory(ctx);
case "choosing_rounds":
return chooseRounds(ctx);
default:
Game.status = "choosing_category";
return;
}
};
let chooseCategory = (ctx) => {
Game.status = 'choosing_category';
return ctx.reply(
'Pick a Category: ',
Extra.inReplyTo(ctx.message.message_id)
.markup(
Markup.keyboard(catArr)
.oneTime()
.resize()
)
);
};
let chooseRounds = (ctx) => {
Game.status = 'choosing_rounds';
return ctx.reply(
'Number of Questions: ',
Extra.inReplyTo(ctx.message.message_id)
.markup(
Markup.keyboard([
["π 10", "π 20"],
["π 50", "π 100"]
])
.oneTime()
.resize()
)
);
};
// ================ACTUAL GAMEPLAY=================//
// Initialise Current Game object
let Game;
resetGame = () => {
let previousQuestionList = [];
if (Game != null && Game.hasOwnProperty("question") && Game.question.hasOwnProperty("id_list")) {
previousQuestionList = Game.question.id_list;
}
Game = {
"status": "choosing_category", // choosing_category, choosing_rounds, active_wait, active
"category": null,
"rounds": {
"current": 0,
"total": 10
},
"question": {
"id": 0, // id of question
"id_list": [], // store all the question ids to prevent repeat
"answerer": [] // person who answered the question: [ persons' name ] | [] (skipped)
},
"hints": {
"text": "",
"current": 0,
"total": 4,
"charsToReveal": [],
"unrevealedIndex": [],
"points": [10, 8, 5, 3, 1]
},
"nexts": {
"current": {}, // object of people who put next
"total": 2
},
"timer": null,
"interval": 10, // in seconds
"leaderboard": {},
"global_leaderboard": null,
"idle": {
"questions": 0, // number of questions for which there is no user input
"threshold": 3, // number of questions before terminating game
"reset": function() {
this.questions = 0;
}
}
};
Game.question.id_list = previousQuestionList;
};
resetGame();
// Start Game function
startGame = (ctx) => {
Game.status = "active";
Game.rounds.current = 0;
Game.idle.reset();
ctx.reply(undefined,
Extra.markup(Markup.removeKeyboard())
);
/*ctx.reply(
"π GAME BEGINS π",
Extra.HTML().markup(
Markup.keyboard([
["β Hint β","β Next β"],
["π Stop Game! π"]
])
.oneTime().resize()
)
);*/
nextQuestion(ctx);
};
// Next Question handler
nextQuestion = (ctx) => {
// Invalid state
if (Game.status.indexOf("active") == -1 || Game.category == null || !questions.hasOwnProperty(Game.category))
return;
Game.status = "active";
// Handling of rounds
// Check if any user input, if not stop
Game.rounds.current++;
if (Game.rounds.current > Game.rounds.total) {
stopGame(ctx);
return;
}
Game.idle.questions++;
if (Game.idle.questions > Game.idle.threshold) {
// log(Game.idle.questions + " " + Game.idle.threshold);
stopGame(ctx);
}
// Handling of question selection
if (Game.question.id_list.length == 0) {
// log("Reloading questions for category " + Game.category);
// Populate the id_list array with to now allow for repeats again
for (i = 0; i < questions[Game.category].length; i++) {
Game.question.id_list.push(i);
}
}
let id_ind = getRandomInt(0, Game.question.id_list.length - 1);
Game.question.id = Game.question.id_list[id_ind];
Game.question.id_list.splice(id_ind, 1);
// Reset nexts and hints
/*Total of 4 hints:
- -1% | Only the question | 10pts
- 0% | No. of characters | 8pts
- 20% | 20% chars shown | 5pts
- 50% | 50% chars shown | 3pts
- 80% | 80% chars shown | 1pts
*/
Game.nexts.current = {};
Game.hints.current = 0;
Game.question.answerer = [];
// Settings no. of chars to reveal for each hint interval
let answer = _getAnswer();
let hints_array = [0, 0, 0.2, 0.5, 0.8]; // base percentage, starting index from 1
for (i = 2; i < hints_array.length; i++) {
// -Getting total number of alpha-numeric characters revealed in hint
hints_array[i] = Math.floor(hints_array[i] * answer.match(regex_alphanum)
.length);
// -Getting total number of NEW characters that'll need to be revealed in this hint
hints_array[i] -= hints_array[i - 1];
}
Game.hints.charsToReveal = hints_array;
// Setting indexes in answer that needs to be revealed
Game.hints.unrevealedIndex = [];
for (i = 0; i < answer.length; i++) {
if (answer[i].match(regex_alphanum)) { // ie is alphanumberic
Game.hints.unrevealedIndex.push(i);
}
}
// Set hint as all underscores
Game.hints.text = answer.replace(regex_alphanum, "_");
// Display Question
let questionText = _getQuestion();
let categoriesText = _getCategories();
_showQuestion(ctx, questionText, categoriesText);
// Handling of timer: Hint handler every `interval` seconds
clearTimeout(Game.timer);
Game.timer = setTimeout(
() => nextHint(ctx),
Game.interval * 1000
);
};
// Hint handler
nextHint = (ctx) => {
if (Game.status != "active")
return; // if it's `active_wait` also return because it means that there's no question at the point in time
/*Total of 4 hints:
- -1% | Only the question | 100pts
- 0% | No. of characters | -5pts
- 20% | 20% chars shown | -10pts
- 50% | 50% chars shown | -20pts
- 80% | 80% chars shown | -30pts
*/
Game.hints.current++;
Game.idle.reset();
if (Game.hints.current >= Game.hints.total) {
_showAnswer(ctx);
return;
}
// Display Question
let questionText = _getQuestion();
let categoriesText = _getCategories();
let answerText = _getAnswer();
// Hint generation
let hint = Game.hints.text.split("");
let hints_given = Game.hints.current;
let r = 0,
ind = 0;
for (i = 0; i < Game.hints.charsToReveal[hints_given]; i++) {
r = getRandomInt(0, Game.hints.unrevealedIndex.length -
1); // get random number to pick index `ind` from the `Game.hints.unrevealedIndex` array.
if (Game.hints.unrevealedIndex.length <= 0) break;
// get a random index `ind` so the character at `ind` will be revealed. pick from `unrevealedIndex` arrray so as to avoid repeat revealing and revealing of non-alphanumberic characters
ind = Game.hints.unrevealedIndex[r];
hint[ind] = answerText[ind]; // reveal character at index `ind`
Game.hints.unrevealedIndex.splice(r, 1); // remove revealed character from `unrevealedIndex` array
}
hint = hint.join("")
.toString();
_showQuestion(ctx, questionText, categoriesText, hint);
Game.hints.text = hint; // save back into `Game` object
// Create new handler every `interval` seconds
clearTimeout(Game.timer);
Game.timer = setTimeout(
() => nextHint(ctx),
Game.interval * 1000
);
};
// Stop Game function
stopGame = (ctx) => {
clearTimeout(Game.timer);
if (Game.status.indexOf("active") != -1) displayScores(ctx);
resetGame();
Game.status = "choosing_category";
};
// ================UI FOR QUESTIONS, ANSWERS AND SCORES=================//
_getQuestion = () => {
if (Game.category != null && Game.question.id != null) {
return questions[Game.category][Game.question.id]["question"].toString();
}
return "";
};
_getCategories = () => {
if (Game.category != null && Game.question.id != null) {
return questions[Game.category][Game.question.id]["categories"].join(", ")
.split("kings_judges")
.join("Kings and Judges")
.split("_")
.join(" ")
.toString()
.toTitleCase();
}
return "";
};
_getAnswer = () => {
if (Game.category != null && Game.question.id != null)
return questions[Game.category][Game.question.id]["answer"].toString();
return "";
};
_getReference = () => {
if (Game.category != null && Game.question.id != null) {
let _q = questions[Game.category][Game.question.id]["reference"];
if (_q != null /* && typeof _q != "undefined" */ )
return _q.toString();
}
return "-nil-";
};
// Get user's name from ctx
_getName = (ctx) => {
let username = ctx.message.from.username;
let first_name = ctx.message.from.first_name;
let last_name = ctx.message.from.last_name;
if (first_name && last_name) return first_name + " " + last_name;
if (!first_name && !last_name) return username;
if (first_name) return first_name;
return last_name;
};
_showQuestion = (ctx, questionText, categoriesText, hintText) => {
ctx.reply(
"<b>BIBLE QUIZZLE</b>\n" +
"ROUND <b>" + Game.rounds.current + "</b> OF <b>" + Game.rounds.total + "</b>" +
" <i>[" + categoriesText + "]</i>" +
"\n--------------------------------\n" +
questionText + "\n" +
((hintText == null /*|| typeof hintText == "undefined"*/ ) ? "" : ("<i>Hint: </i>" + hintText.split("")
.join(" "))),
Extra.HTML()
.markup((m) =>
m.inlineKeyboard([
m.callbackButton('Hint', 'hint'),
m.callbackButton('Next', 'next')
])
)
);
};
_showAnswer = (ctx) => {
let answerers = removeDuplicates(Game.question.answerer);
if (Game.question.answerer.length == 0) {
ctx.reply(
"π₯ <b>Oh no, nobody got it right!</b>\n" +
"π‘ The answer was: <i>" + _getAnswer() + "</i> π‘\n" +
"<i>Bible Reference: " + _getReference() + "</i>",
Extra.HTML()
);
}
else {
let scoreboardText = "";
let score = Game.hints.points[Game.hints.current];
for (i = 0; i < answerers.length; i++) {
scoreboardText += "<b>" + answerers[i].name + "</b> +" + score + "\n";
// Update leaderboard
if (Game.leaderboard[answerers[i].user_id] === undefined) {
// Player doesn't exist in scoreboard, create empty object
Game.leaderboard[answerers[i].user_id] = {
"id": answerers[i].user_id,
"score": 0, // score set at 0
"name": answerers[i].name
};
}
Game.leaderboard[answerers[i].user_id].score = parseInt(Game.leaderboard[answerers[i].user_id].score +
score);
}
ctx.reply(
"β
Correct!\n" +
"π‘ <b>" + _getAnswer() + "</b> π‘\n" +
"<i>Bible Reference: " + _getReference() + "</i>\n\n" +
"π
<b>Scorer(s)</b> π
\n" +
scoreboardText,
Extra.HTML()
);
}
if (Game.rounds.current >= Game.rounds.total) {
stopGame(ctx);
return;
}
Game.status = "active_wait";
// Question shows after less time?
clearTimeout(Game.timer);
Game.timer = setTimeout(
() => nextQuestion(ctx),
Game.interval * 1000 * 0.5
);
};
// Displaying of scores
displayScores = (ctx) => {
let scoreboardText = "";
let scoreboardArr = [];
// Push all stored info from `Game.leaderboard` into `scoreboardArr`
for (i in Game.leaderboard) {
if (!Game.leaderboard.hasOwnProperty(i)) continue;
scoreboardArr.push(Game.leaderboard[i]);
}
// Handler for when nobody played but the game is stopped
if (scoreboardArr.length == 0) {
return ctx.reply(
"βοΈ <b>Everybody's a winner?!?</b> βοΈ\n(\'cos nobody played... π)",
Extra.HTML()
.markup(
Markup.keyboard([
["π Start Game! π"],
["π Quick Game! π", "β Help β"],
// ["π Stop Game! π"],
["π Ranking π"]
])
.oneTime()
.resize()
)
);
}
// Set global rankings and obtain appropriate text
scoreboardText += _setGlobalRanking(scoreboardArr, ctx);
// Show the top scorers with a keyboard to start the game
return ctx.reply(
"π <b>Top Scorers</b> π\n" +
scoreboardText +
"\n" + suggestionText +
"\n\nView global /ranking | /start a new game",
Extra.HTML()
.markup(
Markup.keyboard([
["π Start Game! π"],
["π Quick Game! π", "β Help β"],
// ["π Stop Game! π"],
["π Ranking π"]
])
.oneTime()
.resize()
)
);
};
// ================FEEDBACK FOR SETTING OF ROUND AND CATEGORY=================//
// Initialising/Starting of Game
bot.command('start', (ctx) => {
initGame(ctx);
});
bot.hears("π Start Game! π", (ctx) => {
initGame(ctx);
});
// Category Setting
bot.hears(/π (.+)/, (ctx) => {
if (Game.status != "choosing_category") return;
const heardString = ctx.match[ctx.match.length - 1];
if (heardString == null) return;
const newCategory = heardString.toLowerCase()
.replace(regex_non_alphanum, "_");
if (newCategory == null || !questions.hasOwnProperty(newCategory)) {
ctx.reply("Invalid category: " + heardString);
return;
}
// Different category: reset list
if (newCategory != Game.category) {
// log("Question reset for category " + newCategory);
Game.question.id_list = [];
}
Game.category = newCategory;
chooseRounds(ctx);
});
// Round Setting
bot.hears(/(π|π|π|π)(.\d+)/, (ctx) => {
if (Game.status != "choosing_rounds") return;
Game.rounds.total = parseInt(ctx.match[ctx.match.length - 1]);
startGame(ctx);
});
// ================MISC. COMMANDS=================//
// Quick Game
_quickGame = (ctx) => {
if (Game.status.indexOf("active") != -1) return;
ctx.reply(
"Starting quick game of <b>10 rounds</b> with category <b>ALL</b>",
Extra.HTML()
.inReplyTo(ctx.message.message_id)
);
Game.category = "all";
Game.rounds.total = 10;
startGame(ctx);
};
bot.command('quick', (ctx) => {
_quickGame(ctx);
});
bot.hears("π Quick Game! π", (ctx) => {
_quickGame(ctx);
});
// Stop Command
bot.command('stop', ctx => {
stopGame(ctx);
});
bot.hears("π Stop Game! π", (ctx) => {
stopGame(ctx);
});
// Help Command
bot.command('help', (ctx) => {
ctx.reply(helpMessage);
});
bot.hears("β Help β", (ctx) => {
ctx.reply(helpMessage);
});
// Hint Command and Action (from inline buttons and keyboard)
bot.command('hint', (ctx) => {
nextHint(ctx);
});
bot.hears("β Hint β", (ctx) => {
nextHint(ctx);
});
// Next Command and Action (from inline buttons and keyboard)
_nextCommand = (ctx) => {
if (Game.status != "active")
return; // if it's `active_wait` also return because it means that there's no question at the point in time
Game.idle.reset();
let id = (ctx.callbackQuery == undefined || ctx.callbackQuery.from == undefined || ctx.callbackQuery.from.id ==
undefined) ?
ctx.message.from.id : ctx.callbackQuery.from.id;
Game.nexts.current[id] = 1;
if (Object.keys(Game.nexts.current)
.length >= Game.nexts.total || ctx.chat.type == "private")
return _showAnswer(ctx);
return nextHint(ctx);
};
bot.command('next', (ctx) => {
_nextCommand(ctx);
});
bot.hears("β Next β", ctx => {
_nextCommand(ctx);
});
// Callback Queries
bot.on('callback_query', (ctx) => {
if (ctx.callbackQuery.from.is_bot) return;
let cb = ctx.callbackQuery.data;
Game.idle.reset();
switch (cb) {
case "next":
ctx.answerCbQuery("Next question!")
.catch((failureReason) => {
log(failureReason, "ERROR");
});;
_nextCommand(ctx);
return;
case "hint":
ctx.answerCbQuery("Hint!")
.catch((failureReason) => {
log(failureReason, "ERROR");
});;
nextHint(ctx);
return;
default:
ctx.answerCbQuery("Invalid query " + cb)
.catch((failureReason) => {
log(failureReason, "ERROR");
});;
return;
}
});
// Easter Eggs
//--Eggs
bot.command('eggs', (ctx) => {
const eggGIF = fs.createReadStream("img/egg.gif");
const eggCaption = "Congrats, " + _getName(ctx) +
" you found your first easter egg! \n\nEaster eggs are fun secret commands, like /eggs, that will send cute photos or gifs like this one. They range from cute typos to random words and expressions.\n\nHappy hunting!\n";
return ctx.replyWithAnimation({
source: eggGIF
}, {
caption: eggCaption
});
});
//--HUGS!
bot.hears('/hugs', (ctx) => {
const penguinHugsGIF = fs.createReadStream("img/penguinhugs.gif");
return ctx.replyWithAnimation({
source: penguinHugsGIF
}, {
caption: "HUGS!"
})
});
//--Sads
bot.hears('/sads', (ctx) => {
const jesusWeptPic = fs.createReadStream('img/jesuswept.jpg');
return ctx.replyWithPhoto({
source: jesusWeptPic
}, {
caption: "It's ok to be sad sometimes... Do you need /hugs?"
});
});
//--Trolling with quack
bot.hears("/quack", (ctx) => {
const quackPic = fs.createReadStream("img/quack.jpg");
return ctx.replyWithPhoto({
source: quackPic
}, {
caption: "Did you mean /quick?"
});
});
//--Penguin(s)
bot.hears('/penguins', (ctx) => {
const penguinGIF = fs.createReadStream("img/waddlingpenguin.gif");
return ctx.replyWithAnimation({
source: penguinGIF
}, {
caption: "Did you know? Not all penguins live in Antarctica; in fact, the GalΓ‘pagos penguin lives near the equator in Ecuador!"
})
});
// TODO: Add a easter egg leaderboard as well
// Rankings
//--Sort Leaderboard
_sortLeaderboard = () => {
Game.global_leaderboard.sort(function(a, b) {
return b.score - a.score;
});
};
// --Get global ranking
_getGlobalRanking = () => {
// Check if file exists; if not, create it to prevent problems with access permissions
if (!fs.existsSync("leaderboard.json")) {
log("leaderboard.json doesn't exist... creating file..");
fs.writeFileSync(
'leaderboard.json',
JSON.stringify(Game.global_leaderboard, null, 4)
);
log("File leaderboard.json created!");
return Game.global_leaderboard;
}
// Retrieve data from leaderboard.json
Game.global_leaderboard = JSON.parse(fs.readFileSync('leaderboard.json', 'utf8'));
return Game.global_leaderboard;
};
// --Get ranking of individual user by `user_id`
_getRanking = (user_id, ctx) => {
// First retrieve array data from leaderboard.json
_getGlobalRanking();
if (user_id == null /*|| typeof user_id == "undefined"*/ ) return;
// Find the user's data in the array
let ind = Game.global_leaderboard.findIndex((item, i) => {
return item.id == user_id;
});
if (ind == -1) {
// Data of user doesn't exist:
// Add it to the leaderboard array
Game.global_leaderboard.push({
"id": user_id,
"name": Game.leaderboard[user_id].name,
"score": 0
});
// Sort and save
_sortLeaderboard();
let data = JSON.stringify(Game.global_leaderboard, null, 4);
log("Global leaderboard: " + data);
fs.writeFileSync('leaderboard.json', data);
log("File written for new user " + user_id + ", data: " + data);
// Return new index
ind = Game.global_leaderboard.findIndex((item, i) => {
return item.id == user_id;
});
return ind;
}
else {
return ind;
}
};
// --Update leaderboard for user `user_id` with score `score`
_setRankingIndividual = (user_id, score, ctx) => {
if (user_id == null /*|| typeof user_id == "undefined"*/ ) return;
let ind = _getRanking(user_id, ctx);
// Change score
if (!isNaN(parseInt(score)) && !isNaN(parseInt(ind))) {
Game.global_leaderboard[ind].score += score;
}
};
// Set multiple rankings at once to save time on constantly sorting
// Also generate the output text
_setGlobalRanking = (scoreboardArr, ctx) => {
let scoreboardText = "";
// First sort the top scorers from `scoreboardArr` in descending order (highest score first)
scoreboardArr.sort(function(a, b) {
return b.score - a.score;
});
// Then loop through sorted scoreboard array to set individual ranking
for (i = 0; i < scoreboardArr.length; i++) {
scoreboardText += "<b>" + parseInt(i + 1) + ". " + scoreboardArr[i].name + "</b> <i>(" +
scoreboardArr[i].score + " points)</i>\n";
_setRankingIndividual(scoreboardArr[i].id, scoreboardArr[i].score, ctx);
}
// Sort and save
_sortLeaderboard();
fs.writeFileSync(
'leaderboard.json',
JSON.stringify(Game.global_leaderboard, null, 4)
);
// TODO: Fix issue #15, then remove
_sendAdminJSONRanking(ctx);
return scoreboardText;
};
_showRanking = (ctx) => {
let ind = _getRanking(ctx.message.from.id, ctx);
// Note that `Game.global_leaderboard` is already updated in the `_getGlobalRanking()` function embedded in `_getRanking()`
let leaderboardText = '';
for (i = 0; i < Math.min(Game.global_leaderboard.length, 20); i++) {
if (ind == i) leaderboardText += "π ";
switch (i) {
case 0:
leaderboardText += "π₯ ";
break;
case 1:
leaderboardText += "π₯ ";
break;
case 2:
leaderboardText += "π₯ ";
break;
default:
leaderboardText += "<b>" + parseInt(i + 1) + ".</b> ";
}
leaderboardText += "<b>" + Game.global_leaderboard[i].name + "</b> ";
// if(ind == i) leaderboardText+="<b>";
leaderboardText += "<i>(" + Game.global_leaderboard[i].score + " points)</i>";
// if(ind == i) leaderboardText+="</b>";
if (ind == i) leaderboardText += " π";
leaderboardText += "\n";
}
// User is not part of the top 20
if (ind >= 20) {
leaderboardText += "<b>π " + Game.global_leaderboard[ind].name + " <i>(" + Game.global_leaderboard[ind]
.score +
" points)</i> π</b>";
}
ctx.reply(
"π <b>Global Ranking</b> π\n" +
"<b>----------------------------------</b>\n" +
leaderboardText,
Extra.HTML()
.inReplyTo(ctx.message.message_id)
);
};
bot.command('ranking', (ctx) => {
_showRanking(ctx);
});
bot.hears('π Ranking π', (ctx) => {
_showRanking(ctx);
});
// Debug Stuff
bot.hears('/show_ranking', (ctx) => {
if (ctx.message.from.id != ADMIN_ID) {
// if it isn't the admin's (mine, Samuel Leong's) telegram ID, return
_showRanking(ctx);
return;
}
_getGlobalRanking();
ctx.reply(
"ADMIN DEBUG! Displaying entire ranking for saving...\n" +
"==========================\n" +
JSON.stringify(Game.global_leaderboard, null, 4)
);
});
// Send admin the ranking JSON
let prevSentAdminMessageID = 0;
_sendAdminJSONRanking = (ctx) => {
_getGlobalRanking();
// Delete any old messages sent by the bot
if (prevSentAdminMessageID != 0) {
const chatID = ADMIN_ID;
const msgID = prevSentAdminMessageID;
bot.telegram.deleteMessage(chatID, msgID)
.catch((reason) => {