-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile36.js
More file actions
4401 lines (4320 loc) · 214 KB
/
file36.js
File metadata and controls
4401 lines (4320 loc) · 214 KB
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
/* __ _ _ _ ___ _ _
/ __| || | /_\ / __| |__ ___| |_
| (__| __ |/ _ \\__ \ '_ \/ _ \ _|
\___|_||_/_/ \_\___/_.__/\___/\__| CHAS (C) 2017
Build 2020.2 Refactored for DialogFlow v2*/
// Make sure everything is properly defined
'use strict';
// Pick up variables from the server implementation || Remove API keys
// Source: https://github.com/CHASbotGIT/CHASbotNodeHooks
const KEY_IV = process.env.KEY_IV;
const KEY_ROOT = process.env.KEY_ROOT;
const KEY_ADMIN = process.env.KEY_ADMIN;
const KEY_VERIFY = process.env.KEY_VERIFY;
const KEY_CRYPTO = process.env.KEY_CRYPTO;
const URL_CHASBOT = process.env.APP_URL;
const URL_POSTGRES = process.env.DATABASE_URL;
const KEY_API_HERO = process.env.KEY_API_HERO;
const KEY_API_LOTR = process.env.KEY_API_LOTR;
const KEY_API_GIPHY = process.env.KEY_API_GIPHY;
const KEY_DIALOGFLOW = process.env.KEY_DIALOGFLOW;
const KEY_PAGE_ACCESS = process.env.KEY_PAGE_ACCESS;
const KEY_API_WEATHER = process.env.KEY_API_WEATHER;
const KEY_API_MOVIEDB = process.env.KEY_API_MOVIEDB;
const GOOGLE_PROJECT_ID = process.env.GOOGLE_PROJECT_ID;
const KEY_MARVEL_PUBLIC = process.env.KEY_MARVEL_PUBLIC;
const KEY_ADMIN_TRIGGER = process.env.KEY_ADMIN_TRIGGER;
const KEY_MARVEL_PRIVATE = process.env.KEY_MARVEL_PRIVATE;
const GOOGLE_CLIENT_EMAIL = process.env.GOOGLE_CLIENT_EMAIL;
const GOOGLE_PRIVATE_KEY_ORIG = process.env.GOOGLE_PRIVATE_KEY;
const GOOGLE_PRIVATE_KEY = GOOGLE_PRIVATE_KEY_ORIG.replace(/\\n/g, '\n');
// Set-up dependencies for app x-ref tp package.json
const pg = require('pg'); // https://www.npmjs.com/package/pg
const request = require('request'); // https://github.com/request/request
const express = require('express'); // https://expressjs.com
const bodyParser = require('body-parser'); // https://github.com/expressjs/body-parser
const levenshtein = require('js-levenshtein'); // https://www.npmjs.com/package/js-levenshtein
// Configure dialogFlow session credentials
const dialogflow = require('@google-cloud/dialogflow');
const credentials = {
client_email: GOOGLE_CLIENT_EMAIL,
private_key: GOOGLE_PRIVATE_KEY,
};
const sessionClient = new dialogflow.SessionsClient(
{
projectId: GOOGLE_PROJECT_ID,
credentials
}
);
// Node.js libraries used
const fs = require("fs"); // https://nodejs.org/api/fs.html
const http = require('https'); // https://nodejs.org/api/https.html
const crypto = require('crypto'); // https://nodejs.org/api/crypto.html
// Difining algorithm
const ALGO = 'aes-256-cbc';
// Initialise CHASbot
const CHASbot = express();
CHASbot.use(bodyParser.json());
CHASbot.use(bodyParser.urlencoded({ extended: true }));
var server_port = process.env.PORT || 9000; //
var server_ip_address = '127.0.0.1'; // Only for testing via local NGROK.IO
// Timings
const KEEP_ALIVE = 25; // mins
const TIME_TO_WAIT = 120; // mins
const UTC_BST_GMT = 1; // Currently BST = UTC + 1
const UTC_DAWN = 7;
const UTC_DUSK = 21;
// ********************************************************************************************
// ********************************************************************************************
// ESTABLISH LISTENER
/* Only for TESTING via local NGROK.IO
const server = CHASbot.listen(server_port, server_ip_address, () => {
console.log("INFO [NGROK.IO]> Listening on " + server_ip_address + ", port " + server_port );
console.log("INFO [NGROK.IO]>>>>>>>>>>>>>>>>>>> STARTED <<<<<<<<<<<<<<<<<");
});*/
// Only for PRODUCTION hosting on HEROKU
const server = CHASbot.listen(server_port, () => {
console.log("INFO [HEROKU]> Listening on ", + server_port);
console.log("INFO [HEROKU]>>>>>>>>>>>>>>>>>> STARTED <<<<<<<<<<<<<<<<<<");
});
// Keep Heroku alive
setInterval(function() {
http.get(URL_CHASBOT);
}, mnsConvert(KEEP_ALIVE));
// ********************************************************************************************
// ********************************************************************************************
// Messenger templates can be found at:
// https://developers.facebook.com/docs/messenger-platform/send-messages/templates
// File dependencies
const FILE_HIGH = "./high_score.txt"; // Same directory as source code
const FILE_SURVEY = "./survey.txt";
const FILE_CALENDAR = "./calendar.txt";
const FILE_ENCRYPTED_IDS = "./ids_public.txt";
const FILE_ENCRYPTED_BIOS = "./bios_public.txt";
const FILE_TO_BE_ENCRYPTED = "./ids_private.txt"; // "./bios_private.txt" "./fundraising_private.txt"
const FILE_ENCRYPTED_FR_CARD = "./fundraising_public.txt";
const FILE_ENCRYPTED = FILE_ENCRYPTED_IDS; // FILE_ENCRYPTED_FR_CARD FILE_ENCRYPTED_BIOS FILE_ENCRYPTED_IDS
// Messages
const MSG_RPSLS_INTRO = "💡 First to five is the champion.\n✌️Scissors cuts Paper✋,\n✋Paper covers Rock👊,\n👊Rock crushes Lizard🤏,\n🤏Lizard poisons Spock🖖,\n🖖Spock smashes Scissors✌️,\n✌️Scissors decapitates Lizard🤏,\n🤏Lizard eats Paper✋,\n✋Paper disproves Spock🖖,\n🖖Spock vaporizes Rock👊, and\n👊Rock crushes Scissors✌️!";
const MSG_RPSLS_PROMPT = "Choose (type in)... Rock, Paper, Scissors, Lizard or Spock?";
const MSG_HANGMAN_INTRO = "🤔 Figure out the mystery staff member name.\nType a letter to guess, or 'stop'.\nYou are allowed no more than 3 strikes.";
const MSG_SURVEY_THANKS = "❤️ Thank you for finishing our little survey.";
const MSG_HANGMAN_PROMPT = "🤔 Where were we... who is that!\nType a letter, or 'stop'.\nNo more than 3 strikes.";
var MSG_STAR_RATING = [
"Meh, in my book it's complete pants, all rotten tomatoes 🍅🍅🍅🍅🍅.",
"I'd be generous giving it ⭐🍅🍅🍅🍅, I watched it so you don't have to!",
"Wouldn't watch it again at ⭐⭐🍅🍅🍅, give it 20 mins and judge for yourself.",
"I'd give it a better than average ⭐⭐⭐🍅🍅. Pop it on.",
"Well worth the watching ⭐⭐⭐⭐🍅, give it a go.",
"Wow, a fantastic ⭐⭐⭐⭐⭐. In my humble opinion. you must watch."];
var MSG_THUMBS = ["👍👍👍","👍👍👎","👍👎👎","👎👎👎"];
var MSG_RANDOM_COMPLIMENT = [
"Looking good.","You're more fun than bubblewrap.","I bet you do crossword puzzles in ink.",
"You're like a breath of fresh air.","You're like sunshine on a rainy day.","On a scale from 1 to 10, you're an 11.",
"Your smile is contagious.","You know how to find that silver lining.","You're inspiring.","I like your style.",
"You're a great listener.","I bet you sweat glitter.","You were cool way before hipsters.",
"Hanging out with you is always a blast.","You're one of a kind.","You always know just what to say.",
"There's ordinary, and then there's you."];
var MSG_INTERCEPTS = [
["🎁 While it's always nice to receive a gift, I'm not sure what you want me to do with that ",
"🎁 I do appreaciate a nice present, so thank you for the lovely ",
"🎁 I'm far better at understanding regular text, but it is good of you to send me the "],
["👍 I'm so glad you like it.",
"👍 I'm pleased too."],
["👍👍 You are very pleased, press for even longer next time!",
"👍👍 Nice that you are so very chuffed!"],
["👍👍👍 Wow, that good is it! I'm ecstatic too!!",
"👍👍👍 Gosh, you are completely over the moon!!"],
["🐰 I do like a nice sticker though I'm not sure that gets us anywhere.",
"🐰 Stickers are just great, they really brighten up a conversation."],
["😃 I’m not too good at reading emotions but that is a power of positivity you are sending out.",
"😃 You are totally beaming out the sunshine with those happy emojis."],
["😭 Bots may not be big on reading people but I’m picking up a negative vibe.",
"😭 I'm picking up on a lot of unhappy emojis but maybe you just like them."],
["🤔 I’m either not picking you up very well or you’ve got quite mixed feelings.",
"🤔 I’m not sure from that mix of emojis, whether you are up or down."],
["💥 That’s an awful lot of emoticons you crammed in there, hard to find what you are saying.",
"💥 Wow, that's a lot more emojis than I can make sense of."]];
var MSG_TOPTRUMPS_INTRO1 = "🤖 Let's play Top Trumps to see how many wins you can get in a row. I'll get you started with ";
var MSG_TOPTRUMPS_INTRO2 = ", my choice of hero (or villain).\n1️⃣ First pick a category you think you can beat, then\n2️⃣ name your hero or villain.\nKeep picking categories and naming characters until you are defeated! If the value on my card, or on any card you play, is a mystery (i.e.❓) then it will be 50/50 whether you win!";
var MSG_TOPTRUMPS_PROMPT = "Pick a category to try and beat. If the value on this card is ❓ or on the card you play, then it will be 50/50 whether you win.";
var MSG_EVENTS_OOPS = [
"📆 Oops, that's not something I could find...",
"📆 Mmmm, not an event that I recognise...",
"📆 Not sure I'm able to help you with when that is..."];
var MSG_HERO_OOPS = [
"⚠️ Alert: Hydra stole this result from the S.H.I.E.L.D. database...",
"☠️ Warning: Hydra Infiltration. Result unavailable while under attack from enemy forces...",
"👁️ Not even the eye of Uatu sees your request...",
"💾 Program missing, exiting protocol...",
"💣 Danger: Energy Overload..."];
var MSG_LOTR_OOPS = [
"👁️🗨️ Eyes are watching, shhhh...",
"🧙♂️ He that breaks a thing to find out what it is has left the path of wisdom...",
"😍 Curse us and crush us, my precious is lost...",
"💀 I don’t know, and I would rather not guess...",
"👁 Mordor..."];
// Triggers phrases in lowercase - following phrases are handled in code
const TRIGGER_SURVEY = 'survey';
const TRIGGER_QUIZ = 'quiz';
const TRIGGER_HELP = 'help';
const TRIGGER_FEELING_LUCKY = 'feeling lucky';
const TRIGGER_CHAS_LOGO = 'chas logo';
const TRIGGER_CHASABET_1 = 'chas alphabet';
const TRIGGER_CHASABET_2 = 'chas letter';
const TRIGGER_MARVEL = 'marvel';
const TRIGGER_LOTR = 'lotr';
const TRIGGER_CHAS_EVENTS = 'when is';
const TRIGGER_CHAS_BIOGS = 'who is';
const TRIGGER_TOPTRUMPS = 'top trumps';
const TRIGGER_RPSLS = 'bazinga';
const TRIGGER_HANGMAN = 'hangman';
const TRIGGER_STOP = 'stop';
var TRIGGER_SEARCH = ['search','google','wiki','beeb'];
var TRIGGER_LOTTERY = ['lotto','lottery','euromillions','euro-millions'];
var TRIGGER_MOVIEDB = ['synopsis','watched','watch','catch','seen','see'];
// _ _ ___ ___ _ _____
// | || |/ _ \ / _ \| |/ / __|
// | __ | (_) | (_) | ' <\__ \
// |_||_|\___/ \___/|_|\_\___/
// DialogFlow fulfilment hard-coded hooks
// These HOOKS use dialogflow NLP but have hard-coded procedures rather than the user-configured
// The user-configurted hooks are set up in FILE_HOOKS and accept the following 'card' layouts:
// [1] Picture (only)
// [2] Picture with Text
// [3] Text with Button (inc. URL)
const MSG_NO_HOOK = "🐞 Any other day, that might have worked but not today, sorry!";
const MSG_NO_WEATHER = "😔 Oops, I wasn't able to look up the weather for that place just now.";
const FILE_HOOKS = "./hooks.txt";
const HOOK_FUNDRAISING = 'fundraising';
const HOOK_PICKCARD = 'cards';
const HOOK_WEATHER = 'weather';
/*const HOOK_WORKPLACE = 'workplace';
const HOOK_URL_GROUP_DOCS = 'group_docs';
const HOOK_PLAN = 'plan';
const HOOK_XMAS = 'xmas';
const HOOK_CONTACT_INFO = 'contact_info';*/
// Add any new hard-coded hook names to the HOOKS array
var HOOKS = ['fundraising','cards','weather']; // List of UNIQUE hook names, gets extended with custom hook names
var HOOKS_CUSTOM = [];
// End-points
const URL_CHAT_ENDPOINT = "https://graph.facebook.com/v2.6/me/messages";
const URL_API_MOVIEDB = "https://api.themoviedb.org/3/";
const URL_API_WEATHER = "https://api.openweathermap.org/data/2.5/weather?APPID=";
const URL_API_MARVEL = "https://gateway.marvel.com:443/v1/public/characters?nameStartsWith=";
const URL_API_GIPHY = "https://api.giphy.com/v1/gifs/random";
const URL_API_LOTR = "the-one-api.dev";
const URL_API_HERO = "https://superheroapi.com/api.php/";
// URLs
const URL_SEARCH_GOOGLE = "https://www.google.com/search?q=";
const URL_SEARCH_WIKI = "https://en.wikipedia.org/w/index.php?search=";
const URL_SEARCH_BEEB = "https://www.bbc.co.uk/search?q=";
const URL_GOOGLE_THUMB = "https://images.imgbox.com/7f/57/CkDZNBfZ_o.png";
const URL_WIKI_THUMB = "https://images.imgbox.com/30/62/Vv6KJ9k9_o.png";
const URL_BEEB_THUMB = "https://images.imgbox.com/59/f5/PFN3tfX5_o.png";
const URL_CHAS_THUMB = 'https://images.imgbox.com/99/1d/bFWYzY68_o.jpg';
const URL_LOTTO_UK = "https://www.national-lottery.co.uk/games/lotto?";
const URL_LOTTO_SCOT = "https://www.scottishchildrenslottery.com";
const URL_LOTTO_EURO = "https://www.national-lottery.co.uk/games/euromillions?";
const URL_LOTTO_THUMB_UK = "https://images2.imgbox.com/a7/d9/bPkhSTGL_o.png";
const URL_LOTTO_THUMB_SCOT = "https://images2.imgbox.com/38/2f/Do75wmKv_o.png";
const URL_LOTTO_THUMB_EURO = "https://images2.imgbox.com/c0/e9/IMp4gYs4_o.png";
const URL_IMG_PREFIX = "https://images.imgbox.com/";
const URL_IMG_PREFIX2 = "https://images2.imgbox.com/";
const URL_IMG_SUFFIX = "_o.png";
const URL_GIF_SUFFIX = "_o.gif";
// Regular expressions
const REGEX_START = '(?=.*\\b'; // Regular expression bits
const REGEX_MIDDLE = '\\b)';
const REGEX_END = '.+';
// For keeping track of senders
var SENDERS = new Array ();
// Functional
var PROPER_NOUNS_MONTHS = [
"January","February","March","April","May","June","July","August","September","October","November","December"];
var PROPER_NOUNS_DAYS = [
"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var PROPER_NOUNS_NAMES = [
"Rachel House", "Robin House", "CHAS"];
// Add any new proper arrays to strProper()
var TIME_OF_DAY = [
[22,"Getting late"],[19,"Good evening"],[18,"Time for tea"],[13,"Afternoon"],[12,"Lunch time"],
[11,"Time for Elevenses"],[8,"Morning"],[7,"Breakfast time"],[6,"Another day another dollar"],
[5,"Whoa, you're an early bird"],[4,"You're up early (or very late)"],[3,"Yawn, worst time to be awake"],
[2,"You're up late"],[1,"Zzzzz, sorry"],[0,"It's the witching hour"]];
var EMOTICON_UP = ["🙂","😊","😀","😁","😃","😆","😍","😎","😉","😜","😘","😂","😉","😜","😘","😛","😝","🤑",
":)",":]","8)","=)",":D","=D",";)",":P",":p","=p",":-*",":*"];
var EMOTICON_DOWN = ["☹️","🙁","😠","😡","😞","😣","😖","😢","😭","😨","😧","😦","😱","😫","😩","😐","😑","🤔","😕","😟",
":'(",":O",":o",">:O",":|",":/","=/"];
var FB_UNKNOWN = ['Friend','Buddy','Pal','Companion','Chum','Partner','Higness','Trouble'];
// CHASbot help
var HELP_PROMPTS = [
["ad/e9/ivBhjDXd","When is the Devil Dash","Who is Morven MacLean","Where can I get collecting cans","How do I claim expenses","How do I get Christmas cards","CHAS alphabet C"],
["7a/45/0uhs3nQx","Weather at Rachel House","Weather in Aberdeen","Search CHAS","Google FB Workplace","Wiki Santa Claus","Beeb Blue Planet"],
["9a/f7/yRfMnV7i","Bazinga","Hangman","Pick a card","Toss a coin","Roll a dice","Mystic 8"],
["0a/fe/WxsCGnFs","What’s a scrub","Is winter coming","My milkshake","Have you seen Moana","Is this the real life","I want the truth"],
["de/ff/4ZtuUqYX","Marvel codename Hulk","Execute Order 66","Beam me up","Open pod bay doors","Roll for initiative","Talk like Yoda"]]; // images2 source
var HELP_INDEX = 0;
// CHAS events
const CHAS_EVENTS_BLOCK_SIZE = 4;
var CHAS_EVENTS_CALENDAR = new Array();
var CHAS_EVENTS_TOTAL = 0;
var CHAS_EVENTS_OOPS_INDEX = 0;
// CHAS biographies
const CHAS_BIOGS_BLOCK_SIZE = 2;
var CHAS_BIOGS_VIABLE = false;
var CHAS_BIOGS = new Array();
var CHAS_BIOGS_TOTAL = 0;
var CHAS_FR_LIST = "Contact your local Fundraising Team:" + "\n";
// Slim shady
const IDS_BLOCK_SIZE = 2;
var IDS_VIABLE = false;
var IDS_TOTAL = 0;
var IDS_LIST = new Array();
var IDS_TIMESTAMP = new Array();
// CHAS alphabet
var CHASABET = new Array();
CHASABET [0] = ["b1/96/zO6mBcwI","a5/59/dH8YmE0D","28/ca/zIHlflOC"]; // A
CHASABET [1] = ["a7/6b/ykRlRXQ4","35/79/3Fm87p1Z","69/18/7Jwe1SDT"]; // B
CHASABET [2] = ["70/0e/A6ZJwetJ","33/25/aueWYGEx","d9/7e/LaVqtDUQ","85/b1/qh0uavuP"]; // C
CHASABET [3] = ["4a/a3/NqUpBNz4","ef/4c/z5RNxmlD"]; // D
CHASABET [4] = ["63/f7/XaiHgD71","ce/ac/9nCwH3g9","35/3d/TcTbkDhK"]; // E
CHASABET [5] = ["87/c5/ap69ZMxm","ce/20/wUUatq8C"]; // F
CHASABET [6] = ["49/5d/eC9uvi9B","ff/3b/pmvdcWts"]; // G
CHASABET [7] = ["b5/90/PvvkWezf","f5/bf/UXiVHjNV","b6/e0/Tcqrhxhp","ac/2b/eZ5jnY3u","6f/19/EZadWwIQ"]; // H
CHASABET [8] = ["8b/6a/7NVhU4DB","e4/de/dhkBg1G6","ff/35/GWYGOn6L"]; // I
CHASABET [9] = ["50/96/RJQnEZTR","39/a9/rQJGozJp"]; // J
CHASABET [10] = ["a2/d8/Js4Pp0yx","8a/48/3BMq2BbT"]; // K
CHASABET [11] = ["47/a9/rEoruoPl","ce/8e/XQgh4mnL"]; // L
CHASABET [12] = ["e4/d9/3aBWWbLv","9b/f7/YaUMcKiy","8a/24/EUOb4ml4"]; // M
CHASABET [13] = ["a7/b6/I4LznlDF","c5/56/WnE5akMy"]; // N
CHASABET [14] = ["15/78/HIa3Mfir","0f/72/VgMNNoMu"]; // O
CHASABET [15] = ["ef/30/jcLeoia1","00/5c/EKuPupn8","83/0a/dxQuIG6C"]; // P
CHASABET [16] = ["99/c2/eHly9qnq"]; // Q
CHASABET [17] = ["ef/1c/CUsKXwFq","f8/96/qJJm4MIB"]; // R
CHASABET [18] = ["0b/02/O7uHlTst","fd/fe/Tae390bV","95/97/GCCT6cS1","00/ed/yR9lW1az","3c/36/HzHUAz82"]; // S
CHASABET [19] = ["a3/8d/r0xzFJPR","aa/a0/koSvqmVT"]; // T
CHASABET [20] = ["2d/47/F50Ty0wO","d9/04/C1nlNJpU","08/e4/y1bij5xT","fb/a8/pTmffp5t"]; // U
CHASABET [21] = ["d9/da/kzg0lQ8V","e1/79/F9f57NK1"]; // V
CHASABET [22] = ["6e/ec/Hd1zypGj","95/0b/xyZtCqje","b0/f5/wBb2EsqF"]; // W
CHASABET [23] = ["e9/0c/nB1EzCck","2e/60/2ETG0nZa"]; // X
CHASABET [24] = ["2a/4a/9R5ZzF7V","d0/23/QDFnWi52"]; // Y
CHASABET [25] = ["f6/89/4pwI187X","3c/4f/AguL64HL"]; // Z
// All images2 prefix and gif suffix - source: https://www.mikeafford.com/store/weather-icons/weather-icon-set-re-03/
// Maps to https://openweathermap.org/weather-conditions
const EMPTY_WEATHER_GIF_URL = "https://images2.imgbox.com/c0/d5/dTFWiA7h_o.gif";
var WEATHER_GIFS = [
"a7/8c/0ZQ6B9PR day 800",
"89/6c/S892YW2m day 801, 802",
"9d/27/o2e05zGc day 804",
"1d/eb/z98LmXpq day 721",
"0f/61/FCn1GAAr day 701",
"6d/da/XcKVM4EB day 741",
"f9/70/k0JGk0WH night 800",
"ed/ab/Fzq4hS68 day 321, 520, 521, 531",
"9d/c3/wiKQBmSp day 522",
"b7/5d/KqF87CiA day 620, 621",
"ac/25/Y6sde2q8 day 500, 501",
"0c/3b/PxjLH80T day 502, 503",
"10/5b/YO9xBG7c day 600, 601",
"c1/ed/LAEBQvmO day 602",
"92/99/Otcf46PS day 611, 612, 615, 616",
"6f/07/ypBgFMBm day 906",
"76/f9/XqB4iCtM day 202, 211, 212, 221",
"26/36/vW04Z2uV night 321, 520, 521, 531",
"b1/f1/pDcVw9wP night 522",
"8f/e2/FnnYeCUV night 620, 621",
"d0/4c/vWYADC2T night 500, 501",
"01/92/UNomL02l night 502, 503",
"e3/92/wU0uHnZ4 night 600, 601",
"9b/ff/BoURacwM night 602",
"d8/f9/EuC4GMyQ night 611, 612, 615, 616",
"82/e9/7tVFKV08 night 906",
"b1/31/TSZSdk54 night 202, 211, 212, 221",
"c3/03/20ahf4a7 night 721, 801, 802",
"47/fd/OhBirQQd night 804",
"7d/cd/m6gR8cQQ day 803",
"24/60/yj2D9tIN night 803",
"52/04/yiToCBuQ day 904",
"d6/63/ek6aZEfu day 903",
"36/e5/1NHJnEh5 day 300, 301, 310, 311, 313",
"16/52/11EwhgRm day 511",
"ed/71/zJc3BIs7 day 504",
"bd/f8/7V6HMeQO day 711",
"51/eb/SPnVGvEt day 731, 751, 761",
"16/d4/v0JNGIFp day 905",
"a9/2b/m4OOIKOC night 904",
"33/05/RDR9i2iA night 903",
"61/1b/8pU2yng3 night 701",
"03/9e/8ebh09jn night 741",
"da/74/UpiDPXsS night 300, 301, 310, 311, 313",
"e3/6a/FeuXDOcW night 511",
"7c/68/f0pw4zcW night 504",
"33/b5/PqNzCp8K night 711",
"f4/53/gAEADyta night 731, 751, 761",
"af/75/AuCJyiHK night 905",
"2e/69/zDShc6Or night day 781",
"0a/7f/kbmDUHRi night day 771",
"c1/2e/8jAAjnXo day 302, 312, 314",
"79/38/CpeF1okY night 302, 312, 314",
"5b/56/0BE76xjK night day 762",
"48/81/u9HEXhfg day 622",
"c2/50/WYTdKHGp night 622",
"1a/20/q7g8CZnC day 613",
"d7/eb/1BWWNO4Z night 613",
"62/aa/uqyQmDMy day 200, 201, 210, 230, 231, 232",
"30/1e/yM8bbEDc night 200, 201, 210, 230, 231, 232"];
var CHASABET_INDEX = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
// Rock Paper Scissors Lizard Spock
var RPSLS_VALID = ["rock","paper","scissors","lizard","spock"];
var RPSLS_OUTCOMES = ["cuts","covers","crushes","poisons","smashes","decapitates","eats","disproves","vaporizes","crushes"];
var RPSLS_WIN = ["scissorspaper","paperrock","rocklizard","lizardspock","spockscissors","scissorslizard","lizardpaper","paperspock","spockrock","rockscissors"];
var RPSLS_LOSE = ["paperscissors","rockpaper","lizardrock","spocklizard","scissorsspock","lizardscissors","paperlizard","spockpaper","rockspock","scissorsrock"];
var RPSLS_DRAW = ["rockrock","paperpaper","scissorsscissors","lizardlizard","spockspock"];
var RPSLS_IMGS = [
"8a/24/7grzIThv",
"60/ab/GGWv7VGf","5b/aa/gX9yjh8W","de/9a/ZW4Y0A3c","9b/b0/jozAYCPJ","fc/69/9RIO0UnP","ae/96/fImaS52o","e6/d8/NZf7rjvm","ce/75/2lShOY7A","1c/c0/v4T6eRgk","39/85/kCcL35Wx",
"7c/cc/6aXrZ3OR","57/e7/gXFlvW70","49/29/I58HCq4Z","ea/83/4oIJFaQX","35/46/6jfnQOWP","51/27/Mgd2xmkH","5b/43/75oya7i9","65/e5/J9Pi4L30","6d/76/wmyBvmzC","1c/dd/A1qkLRfu",
"bc/5e/WXSBV3m7","7f/65/UufJXgwL","4b/4f/JO6B4jVX","5c/00/lLBYnA89","41/8b/iDCFzS5i"]; // Bottom row images2 source
// Playing cards
var CARD_PICK = '';
var CARD_DECK = [
"♥A","♥2","♥3","♥4","♥5","♥6","♥7","♥8","♥9","♥10","♥J","♥Q","♥K",
"♠A","♠2","♠3","♠4","♠5","♠6","♠7","♠8","♠9","♠10","♠J","♠Q","♠K",
"♦A","♦2","♦3","♦4","♦5","♦6","♦7","♦8","♦9","♦10","♦J","♦Q","♦K",
"♣A","♣2","♣3","♣4","♣5","♣6","♣7","♣8","♣9","♣10","♣J","♣Q","♣K"];
var CARD_PROMPTS = [
"I've picked... ","This time I've drawn... ","I've selected... ","You're card is... "];
// LOTR
var LOTR_MOVIES = [
"5cd95395de30eff6ebccde56🎞️ The Lord of the Rings Series",
"5cd95395de30eff6ebccde57🎞️ The Hobbit Series",
"5cd95395de30eff6ebccde58🎥 The Unexpected Journey (2012)",
"5cd95395de30eff6ebccde59📽️ The Desolation of Smaug (2013)",
"5cd95395de30eff6ebccde5a🎬 The Battle of the Five Armies (2014)",
"5cd95395de30eff6ebccde5b🎥 The Two Towers (2001)",
"5cd95395de30eff6ebccde5c📽️ The Fellowship of the Ring (2002)",
"5cd95395de30eff6ebccde5d🎬 The Return of the King (2003)"];
var LOTR_ARRAY = [];
// TOP TRUMPS
const HERO_STATS = ["🧠 Intelligence","💪 Strength","💨 Speed","🔋 Durability","🌡️ Power","⚔️ Combat"];
const HERO_MAX = 731; // https://superheroapi.com/ids.html
var HERO_ARRAY = [];
// Survey/Quiz
const PRIZES = ["🎉","🎈","💰","🎁","👏","🌹","💐","🍹","🍸","🍺","🍷","🍾","🍰","💋","🎖️","🍀"];
var SURVEY_VIABLE = true;
var SURVEY_NAME = ''; // Loaded from survey.txt 1st line
var SURVEY_QUESTIONS = [];
var QUIZ_NAME = '';
var QUIZ = []; // Loaded from survey.txt 1st line, 1st item
var HIGH_SCORE = ["CHASbot",0];
// Film and TV
var MOVIEDB_RECORDS_INDEX = -1;
var MOVIEDB_RECORDS = new Array();
// Valdate URLs
function urlExists(url, cb) {
request({ url: url, method: 'HEAD' }, function(err, res) {
if (err) return cb(null, false);
cb(null, /4\d\d/.test(res.statusCode) === false);
});
}
// Encryption and decryption of files
var enCrypt = function(text_plain) {
//console.log("DEBUG [enCrypt]> plain: " + text_plain);
let cipher = crypto.createCipheriv(ALGO,Buffer.from(KEY_CRYPTO),Buffer.from(KEY_IV,'hex'));
let crypted = cipher.update(text_plain);
crypted = Buffer.concat([crypted, cipher.final()]);
//console.log("DEBUG [enCrypt]> obscured (raw): " + crypted);
//console.log("DEBUG [enCrypt]> obscured (hex): " + crypted.toString('hex'));
return crypted.toString('hex');
}
var deCrypt = function(text_obscure) {
//console.log("DEBUG [deCrypt]> obscured: " + text_obscure);
let decipher = crypto.createDecipheriv(ALGO,Buffer.from(KEY_CRYPTO),Buffer.from(KEY_IV,'hex'));
let text_obscure_buffer = Buffer.from(text_obscure,'hex');
//console.log("DEBUG [deCrypt]> buffered: " + text_obscure_buffer);
let dec = decipher.update(text_obscure_buffer);
dec = Buffer.concat([dec, decipher.final()]);
//console.log("DEBUG [deCrypt]> deciphered: " + dec);
return dec.toString();
}
function enCryptContents () {
let text_block = fs.readFileSync(FILE_TO_BE_ENCRYPTED, "utf-8");
let text_block_split = text_block.split("\n");
let stream = fs.createWriteStream(FILE_ENCRYPTED, "utf-8");
stream.once('open', function(fd) {
let stream_loop = 0;
for (stream_loop = 0; stream_loop < text_block_split.length; stream_loop++) {
//console.log("DEBUG [enCryptContents]> " + text_block_split[stream_loop]);
if (stream_loop == text_block_split.length - 1 ) {
stream.write(enCrypt(text_block_split[stream_loop])); // Last line
} else {
stream.write(enCrypt(text_block_split[stream_loop]) + '\n');
}
};
stream.end();
});
}
function deCryptContents () {
let text_block = fs.readFileSync(FILE_ENCRYPTED_BIOS, "utf-8");
let text_block_split_garbled = text_block.split("\n");
CHAS_BIOGS = new Array();
let decrypt_loop = 0;
for (decrypt_loop = 0; decrypt_loop < text_block_split_garbled.length; decrypt_loop++) {
CHAS_BIOGS[decrypt_loop] = deCrypt(text_block_split_garbled[decrypt_loop]);
};
let number_bios_entries = CHAS_BIOGS.length;
//console.log("DEBUG [deCryptContents]> Bios entries: " + number_bios_entries);
let remainder = number_bios_entries % CHAS_BIOGS_BLOCK_SIZE;
//console.log("DEBUG [deCryptContents]> Bios remainder (looking for 0): " + remainder);
CHAS_BIOGS_TOTAL = number_bios_entries / CHAS_BIOGS_BLOCK_SIZE;
//console.log("DEBUG [deCryptContents]> Events: " + CHAS_BIOGS_TOTAL);
if ((remainder != 0)||(CHAS_BIOGS_TOTAL == 0)) {
console.log("ERROR [deCryptContents]> Something funky going on with bios");
CHAS_BIOGS_VIABLE = false;
} else {
CHAS_BIOGS_VIABLE = true;0
};
text_block = fs.readFileSync(FILE_ENCRYPTED_IDS, "utf-8");
text_block_split_garbled = text_block.split("\n");
//IDS_LIST = new Array();
decrypt_loop = 0;
for (decrypt_loop = 0; decrypt_loop < text_block_split_garbled.length; decrypt_loop++) {
IDS_LIST[decrypt_loop] = deCrypt(text_block_split_garbled[decrypt_loop]);
IDS_TIMESTAMP[decrypt_loop] = null;
};
let number_ids_entries = IDS_LIST.length;
//console.log("DEBUG [deCryptContents]> ID entries: " + number_ids_entries);
remainder = number_ids_entries % IDS_BLOCK_SIZE;
//console.log("DEBUG [deCryptContents]> ID remainder (looking for 0): " + remainder);
IDS_TOTAL = number_ids_entries / IDS_BLOCK_SIZE;
//console.log("DEBUG [deCryptContents]> IDs: " + IDS_TOTAL);
if ((remainder != 0)||(IDS_TOTAL == 0)) {
console.log("ERROR [deCryptContents]> Something funky going on with IDs");
IDS_VIABLE = false;
} else {
IDS_VIABLE = true;
};
//console.log("DEBUG [deCryptContents]> IDs Viable? " + IDS_VIABLE);
text_block = fs.readFileSync(FILE_ENCRYPTED_FR_CARD, "utf-8");
text_block_split_garbled = text_block.split("\n");
decrypt_loop = 0;
for (decrypt_loop = 0; decrypt_loop < text_block_split_garbled.length; decrypt_loop++) {
CHAS_FR_LIST = CHAS_FR_LIST + deCrypt(text_block_split_garbled[decrypt_loop]);
if (decrypt_loop != text_block_split_garbled.length) {CHAS_FR_LIST = CHAS_FR_LIST + "\n"};
};
//console.log("DEBUG [deCryptContents]> Contact Card: " + CHAS_FR_LIST);
}
// _ ___ _ ___ ___ _ _ ___
// | | / _ \ /_\ | \_ _| \| |/ __|
// | |_| (_) / _ \| |) | || .` | (_ |_ _ _
// |____\___/_/ \_\___/___|_|\_|\___(_|_|_)
// Load reference data from files and Db
function loadHooks() {
// Load in hooks
let text_block = fs.readFileSync(FILE_HOOKS, "utf-8");
let hook_lines = text_block.split("\n");
let hook_line = 0;
if (hook_lines.length > 0) {
for (var i = 0; i < hook_lines.length; i++) {
if (hook_lines[i].slice(0,2)=='//') { continue }; // Skip comments
//console.log("DEBUG [loadHooks]> Possible hook: " + hook_lines[i]);
let poss_hook = hook_lines[i].split("$");
if (poss_hook.length < 2 || poss_hook.length > 4) { continue }; // Skip where not 2,3 or 4 items
let poss_hook_name = poss_hook[0];
//console.log("DEBUG [loadHooks]> Valid items in hook: " + poss_hook.length);
if (!poss_hook_name.match(/^[a-z_]+$/)) { continue }; // Skip hook name not lowercase + underscore
let skip_hook = false;
for (var j = 0; j < HOOKS.length; j++) {
if (HOOKS[j] == poss_hook_name) { // New hook can't be same as another hook
skip_hook = true; // Disqualifies this hook
break;
}; // if
}; // for
if (skip_hook) { continue };
//console.log("DEBUG [loadHooks]> Poss hook name: " + skip_hook);
let poss_hook_url = poss_hook[1];
if (poss_hook_url.slice(0,8) != "https://") { continue }; // Simple check for SSL URL
if (poss_hook_url.slice(8,14) == "groups") {
poss_hook_url = "https://work-" + KEY_ROOT + ".facebook.com/" + poss_hook_url.slice(8,poss_hook_url.length);
};
//console.log("DEBUG [loadHooks]> Poss URL: " + poss_hook_url);
let poss_hook_blurb = '';
let poss_hook_btn = '';
let hook_type = 'image';
if (poss_hook.length > 2) {
poss_hook_blurb = strTrimTo(640,poss_hook[2]); // Limit
if (poss_hook_blurb == '') { continue }; // There should be message text
hook_type = 'image_text';
};
if (poss_hook.length > 3) {
poss_hook_btn = strTrimTo(20,poss_hook[3]); // Limit
if (poss_hook_btn == '') { continue }; // There should be button text
hook_type = 'button';
};
HOOKS_CUSTOM[HOOKS_CUSTOM.length] = [true,hook_type,poss_hook_name,poss_hook_url,poss_hook_blurb,poss_hook_btn];
//console.log("DEBUG [loadHooks]> Valid Hook[" + (HOOKS_CUSTOM.length - 1) + "]: " + HOOKS_CUSTOM[HOOKS_CUSTOM.length - 1]);
// More comprehensive URL check
urlExists(poss_hook_url, function(err, exists) {
//console.log("DEBUG [loadHooks]> URL check: " + poss_hook_url + ' = ' + exists);
if (!exists) {
for (var j = 0; j < HOOKS_CUSTOM.length; j++) {
if (HOOKS_CUSTOM[j][3] == poss_hook_url) { // Callback delay requires fresh search
HOOKS_CUSTOM[j][0] = false; // Disables the hook
//console.log("DEBUG [loadHooks]> Disabled Hook[" + j + "]: " + HOOKS_CUSTOM[j]);
break;
}; // if
}; // for
}; // if (!exists)
}); // urlExists
}; // for
}; // if
}
function loadCalendar() {
// Load in calendar events
let text_block = fs.readFileSync(FILE_CALENDAR, "utf-8");
CHAS_EVENTS_CALENDAR = text_block.split("\n");
// Catch if the calendar list is funky i.e. isn't in blocks of four or missing at least one set
let number_calendar_entries = CHAS_EVENTS_CALENDAR.length;
//console.log("DEBUG [loadCalendar]> Calendar entries: " + number_calendar_entries);
let remainder = number_calendar_entries % CHAS_EVENTS_BLOCK_SIZE;
//console.log("DEBUG [loadCalendar]> Calendar remainder (looking for 0): " + remainder);
CHAS_EVENTS_TOTAL = number_calendar_entries / CHAS_EVENTS_BLOCK_SIZE;
//console.log("DEBUG [loadCalendar]> Events: " + CHAS_EVENTS_TOTAL);
if ((remainder != 0)||(CHAS_EVENTS_TOTAL == 0)) {
console.log("ERROR [loadCalendar]> Something funky going on with calendar");
return false;
} else {
return true;
}
}
function loadSurvey() {
//console.log("DEBUG [loadSurvey]> Reading: " + FILE_SURVEY);
let gone_funky = false;
// Load in survey as a block
let text_block = fs.readFileSync(FILE_SURVEY, "utf-8");
// Populate a temp array
let load_array = text_block.split("\n");
// Configure the survey
if (load_array.length > 2) {
for (var i = 0; i < load_array.length; i++) {
SURVEY_QUESTIONS[i] = load_array[i].split(","); // Split each row into arrays split by comma
if (i>0 && SURVEY_QUESTIONS[i].length > 6) {
gone_funky = true; // Can't have more than 6 elements i.e. Question + 5 Answers
//console.log("DEBUG [loadSurvey]> " + (SURVEY_QUESTIONS[i].length - 1) + " is too many response elements for Q." + i);
break;
}; // if
}; // for (break)
if (SURVEY_QUESTIONS[0].length != 1) { // Has to be a quiz
QUIZ = SURVEY_QUESTIONS[0]; // Load name and responses into array
//console.log("DEBUG [loadSurvey]> Answers: " + QUIZ);
//console.log("DEBUG [loadSurvey]> Number of questions is " + (SURVEY_QUESTIONS.length-1));
//console.log("DEBUG [loadSurvey]> Number of answers is " + (QUIZ.length-1));
if (QUIZ.length != SURVEY_QUESTIONS.length) { // Both dimensions are not the same
gone_funky = true;
//console.log("DEBUG [loadSurvey]> Number of questions doesn't match answers" + i);
} else { // Both dimensions are the same
for (var i = 0; i < QUIZ.length; i++) {
if (i == 0) { // First element
QUIZ_NAME = QUIZ[0];
//console.log("DEBUG [loadSurvey]> Quiz Name: " + QUIZ_NAME);
if (QUIZ_NAME=='') {
gone_funky = true;
//console.log("DEBUG [loadSurvey]> Quiz name can't be empty");
break;
};
} else {
//console.log("DEBUG [loadSurvey]> Question: " + SURVEY_QUESTIONS[i].join(","));
let potential_number = 0;
let known_string = '';
if (!isNaN(QUIZ[i])) {
// Check that there is a pick question, and that the response is within the range of answers
// OR number reponse could be a string
potential_number = parseInt(QUIZ[i],10);
//console.log("DEBUG [loadSurvey]> Value = " + potential_number + " Parse (should be number) = " + typeof(potential_number));
if (SURVEY_QUESTIONS[i].length == 1) { // Matching question has free-text response
known_string = QUIZ[i];
//console.log("DEBUG [loadSurvey]> Over-rule number value = " + known_string + " Parse (should be number string) = " + typeof(known_string));
if (known_string.length == 0) { // Can't be empty
gone_funky = true;
//console.log("DEBUG [loadSurvey]> Funky answer value of <" + known_string + "> where index is " + SURVEY_QUESTIONS[i].length);
break;
}
} else if (potential_number == 0||potential_number > (SURVEY_QUESTIONS[i].length-1)) { // Check against range
gone_funky = true;
//console.log("DEBUG [loadSurvey]> Funky answer value of " + potential_number + " where index is " + SURVEY_QUESTIONS[i].length);
break;
};
} else {
// Check that there is a free text question and that the correct answer is not empty
known_string = QUIZ[i];
//console.log("DEBUG [loadSurvey]> Value = " + known_string + " Parse (should be string) = " + typeof(known_string));
if (SURVEY_QUESTIONS[i].length > 1||known_string.length == 0) {
gone_funky = true;
//console.log("DEBUG [loadSurvey]> Funky answer value of <" + known_string + "> where index is " + SURVEY_QUESTIONS[i].length);
break;
}; // if: funky text response
}; // if/else: index answer OR free text answer
}; // if/else: quiz name OR answer
}; // for (break): loop through quiz answers
}; // if/else: array dimensions not equal OR ok
} else { // Must be a survey, has only one element in top row i.e. name without any answers
SURVEY_NAME = SURVEY_QUESTIONS[0];
if (SURVEY_NAME=='') {
gone_funky = true;
//console.log("DEBUG [loadSurvey]> Survey name can't be empty");
};
};
if (!gone_funky) {
SURVEY_QUESTIONS.shift(); // Removes <survey_name> (plus correct answers in a quiz)
if (QUIZ.length > 0) { QUIZ.shift() }; // Same for quiz
}
} else {
// Has to be at least 2 rows i.e. header row plus 1 question minimum
gone_funky = true;
//console.log("DEBUG [loadSurvey]> There are not enough rows (must header + question at least): " + load_array.length);
};
if (gone_funky) {
console.log("ERROR [loadSurvey]> Something funky going on with survey");
return false;
} else {
return true;
};
}
function loadLOTRcb(lotrArray,chars_or_quotes,quote_id,callback) {
// Block loads quotes in character array
//console.log("DEBUG [loadLOTR]> Method: " + chars_or_quotes);
if (chars_or_quotes == 'quotes') {
//console.log("DEBUG [loadLOTR]> ID: " + quote_id);
let id_position = -1;
for (var loopArray = 0; loopArray < LOTR_ARRAY.length; loopArray++) {
if (LOTR_ARRAY[loopArray][0]==quote_id) {
id_position = loopArray;
//console.log("DEBUG [loadLOTR]> ID found at: " + id_position);
break;
}; // if
}; // for
if (typeof LOTR_ARRAY[id_position][10] == 'undefined') { // Can be defined
let pushArray = [];
for (var loopArray = 0; loopArray < lotrArray.length; loopArray++) {
pushArray.push([lotrArray[loopArray].movie,lotrArray[loopArray].dialog]);
}; // for
LOTR_ARRAY[id_position][10] = pushArray;
//console.log("DEBUG [loadLOTR]> Quotes populated for: " + id_position);
//console.log("DEBUG [loadLOTR]> First film/quote: " + id_position);
}; // if (LOTR_ARRAY[id_position]
//console.log("DEBUG [loadLOTR]> Quotes: " + LOTR_ARRAY[id_position][10].length);
callback();
} else { // if (chars_or_quotes
// Block loads in characters
if (chars_or_quotes == 'chars' && LOTR_ARRAY.length == 0) { // Catch multiple calls
var arrayQuote = [];
for (var loopArray = 0; loopArray < lotrArray.length; loopArray++) {
LOTR_ARRAY.push([lotrArray[loopArray]._id, // [0]
lotrArray[loopArray].Name,
lotrArray[loopArray].gender,
lotrArray[loopArray].Url,
lotrArray[loopArray].race,
lotrArray[loopArray].realm,
lotrArray[loopArray].height,
lotrArray[loopArray].hair,
lotrArray[loopArray].birth,
lotrArray[loopArray].death]); // [9]
}; // for
}; // if
//console.log("DEBUG [loadLOTR]> Characters: " + LOTR_ARRAY.length);
callback();
}; // else
}
function highScore(read_write) {
let client = new pg.Client(URL_POSTGRES);
if (read_write == 'read') { // Load from file
client.connect(function(err) {
if (err) { return console.error("ERROR [highScore]> Could not connect to read postgres: ", err) };
client.query('SELECT high_scorer,high_score FROM quiz WHERE id = 0', function(err, result) {
if (err) { return console.error("ERROR [highScore]> Error running read query: ", err) };
HIGH_SCORE[0]=result.rows[0].high_scorer;
HIGH_SCORE[1]=result.rows[0].high_score;
//console.log("DEBUG [highScore]> Who: " + HIGH_SCORE[0] + " Score: " + HIGH_SCORE[1]);
client.end();
});
});
} else if (read_write == 'write') { // Save to file
client.connect(function(err) {
if (err) { return console.log("ERROR [highScore]> Could not connect to update postgres: ", err) };
let sql_update = "UPDATE quiz SET high_scorer = '" + HIGH_SCORE[0] + "', high_score = " + HIGH_SCORE[1] + " WHERE id = 0";
client.query(sql_update, function(err, result) {
if (err) { return console.error("ERROR [highScore]> Error running update query: ", err) };
client.end();
});
});
};
};
// LOAD
loadHooks();
// Load in encrypted information
// Update Constants FILE_TO_BE_ENCRYPTED (input) and FILE_ENCRYPTED (output)
//enCryptContents(); // Run once to encrypt files
deCryptContents(); // Normal runtime configuration
var CHAS_EVENTS_VIABLE = loadCalendar();
//console.log("DEBUG [postloadCalendar]> Viable? " + CHAS_EVENTS_VIABLE);
var SURVEY_VIABLE = loadSurvey();
//console.log("DEBUG [postloadSurvey]> Viable? " + SURVEY_VIABLE);
highScore('read');
// Facebook/workplace validation
// Configure webhook in work chat integration - KEY_VERIFY matches code and app
// Copy page access token and hard code for testing or set as server variable
CHASbot.get('/webhook', (req, res) => {
if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === KEY_VERIFY) {
res.status(200).send(req.query['hub.challenge']);
} else {
res.status(403).end();
}
});
/* Sender handling and sequencing functions
// ========================================
// http://plaintexttools.github.io/plain-text-table/
// ════════╤═══╤═════════════════╤══════════╤═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Sender │ 0 │ id_of_sender │ long_int │
// ════════╪═══╪═════════════════╪══════════╪═════════╤═══╤═════════════════╤═══════╤═══════╤════╤════════════════════╤══════╤════════════╤════╤════════════════╤═══════
// Survey │ 1 │ survey_in_play │ bool │ Hangman │ 2 │ hangman_in_play │ bool │ RPSLS │ 3 │ rpsls_in_play │ bool │ Top Trumps │ 4 │ trumps_in_play │ bool
// ────────┼───┼─────────────────┼──────────┼─────────┼───┼─────────────────┼───────┼───────┼────┼────────────────────┼──────┼────────────┼────┼────────────────┼───────
// │ 5 │ survey_question │ int │ │ 7 │ hangman_strikes │ int │ │ 10 │ rpsls_action │ int │ │ 14 │ trumps_score │ int
// ├───┼─────────────────┼──────────┤ ├───┼─────────────────┼───────┤ ├────┼────────────────────┼──────┤ ├────┼────────────────┼───────
// │ 6 │ quiz_score │ int │ │ 8 │ hangman_word │ str │ │ 11 │ issue_instructions │ bool │ │ 15 │ trumps_played │ array
// ├───┴─────────────────┴──────────┤ ├───┼─────────────────┼───────┤ ├────┼────────────────────┼──────┤ ├────┼────────────────┼───────
// │ │ │ 9 │ hangman_word │ array │ │ 12 │ rpsls_player │ int │ │ 16 │ trump_tobeat │ int
// │ │ ├───┴─────────────────┴───────┤ ├────┼────────────────────┼──────┤ ├────┼────────────────┼───────
// │ │ │ │ │ 13 │ rpsls_bot │ int │ │ 17 │ trump_picked │ int
// │ │ │ │ ├────┴────────────────────┴──────┤ ├────┼────────────────┼───────
// │ │ │ │ │ │ │ 18 │ trump_category │ str
// │ │ │ │ │ │ ├────┼────────────────┼───────
// │ │ │ │ │ │ │ 19 │ trumps_start │ bool
// │ │ │ │ │ │ ├────┼────────────────┼───────
// │ │ │ │ │ │ │ 20 │ cat_or_char │ str
// │ │ │ │ │ │ ├────┼────────────────┼───────
// │ │ │ │ │ │ │ 21 │ trumps_xs │ array
// ════════╧════════════════════════════════╧═════════╧═════════════════════════════╧═══════╧════════════════════════════════╧════════════╧════╧════════════════╧═══════*/
function inPlayNew(index_id,new_sender) {
SENDERS[index_id] = [new_sender, // 0:id_of_sender
false,false,false,false, // 1:survey_in_play,2:hangman_in_play,3:rpsls_in_play,4:trumps_in_play
0,0, // 5:survey_question,6:quiz_score
0,'',[], // 7:hangman_strikes,8:hangman_word,9:hangman_word
0,true,0,0, // 10:rpsls_action,11:issue_instructions,12:rpsls_player,13:rpsls_bot
0,[],0,0,'',true,'character',[]]; // 14:trumps_score,15:trumps_played,16:trump_tobeat,17:trump_picked,
} // 18:trump_category,19:trumps_start,20:cat_or_char,21:trumps_xs
function inPlay(in_play,index_id) {
let in_play_index = 0;
if (in_play == 'survey') { in_play_index = 1 }
else if (in_play == 'hangman') { in_play_index = 2 }
else if (in_play == 'rpsls') { in_play_index = 3 }
else if (in_play == 'trumps') { in_play_index = 4 };
return SENDERS[index_id][in_play_index];
}
function inPlayClean(in_play,index_id) {
let in_play_index = 0;
if (in_play == 'survey') {
in_play_index = 1
SENDERS[index_id][5] = 0; // survey_question
SENDERS[index_id][6] = 0; // quiz_score
} else if (in_play == 'hangman') {
in_play_index = 2
SENDERS[index_id][7] = 0; // hangman_strikes
SENDERS[index_id][8] = ''; // hangman_word
SENDERS[index_id][9] = []; // hangman_array
} else if (in_play == 'rpsls') {
in_play_index = 3;
SENDERS[index_id][10] = 0; // rpsls_action
SENDERS[index_id][11] = true; // issue_instructions
SENDERS[index_id][12] = 0; // rpsls_player
SENDERS[index_id][13] = 0; // rpsls_bot
} else if (in_play == 'trumps') {
in_play_index = 4;
SENDERS[index_id][14] = 0; // trumps_score
SENDERS[index_id][15] = []; // trumps_played
SENDERS[index_id][16] = 0; // trump_tobeat
SENDERS[index_id][17] = 0; // trump_picked
SENDERS[index_id][18] = ''; // trump_category
SENDERS[index_id][19] = true; // trumps_start
SENDERS[index_id][20] = 'character'; // cat_or_char
SENDERS[index_id][21] = []; // trumps_xs
};
SENDERS[index_id][in_play_index] = false;
}
function inPlaySet(in_play,index_id) {
let in_play_index = 0;
if (in_play == 'survey') { in_play_index = 1 }
else if (in_play == 'hangman') { in_play_index = 2; }
else if (in_play == 'rpsls') { in_play_index = 3 }
else if (in_play == 'trumps') { in_play_index = 4 };
SENDERS[index_id][in_play_index] = true;
}
function inPlayUnset(in_play,index_id) {
let in_play_index = 0;
if (in_play == 'survey') { in_play_index = 1 }
else if (in_play == 'hangman') { in_play_index = 2 }
else if (in_play == 'rpsls') { in_play_index = 3 }
else if (in_play == 'trumps') { in_play_index = 4 };
SENDERS[index_id][in_play_index] = false;
}
function inPlayPause(index_id) {
let refresh_sender = SENDERS[index_id][0];
SENDERS[index_id][1] = false;
SENDERS[index_id][2] = false;
SENDERS[index_id][3] = false;
SENDERS[index_id][4] = false;
SENDERS[index_id][10] = 0;
SENDERS[index_id][19] = true;
SENDERS[index_id][20] = 'character';
}
function inPlayID (id_to_find) {
let sender_index = -1;
for (var i=0; i < SENDERS.length; i++) {
if (SENDERS[i][0] == id_to_find) {
sender_index = i;
break;
};
};
return sender_index;
}
// String and number helper functions
// ==================================
function intPad(n, length) {
var len = length - (''+n).length;
return (len > 0 ? new Array(++len).join('0') : '') + n
}
function intWords (num) {
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
if ((num = num.toString()).length > 9) return 'overflow';
let n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) : '';
return str;
}
function strStandardise(str) {
let emoticon_up_count = 0;
for (var i = 0; i < EMOTICON_UP.length; i++) {
var pos = str.indexOf(EMOTICON_UP[i]);
while(pos > -1){
++emoticon_up_count;
pos = str.indexOf(EMOTICON_UP[i], ++pos);
}; // Count +ve emoticons
str = strReplaceAll(str, EMOTICON_UP[i], ''); // Then remove them
};
let emoticon_down_count = 0;
for (var i = 0; i < EMOTICON_DOWN.length; i++) {
var pos = str.indexOf(EMOTICON_DOWN[i]);
while(pos > -1){
++emoticon_down_count;
pos = str.indexOf(EMOTICON_DOWN[i], ++pos);
}; // Count -ve emoticons
str = strReplaceAll(str, EMOTICON_DOWN[i], ''); // Then remove them
};
// Lowercase
str = str.toLowerCase();
// Strip out non-alphanumeric
str = str.replace(/[^A-Za-z0-9-\s]/g,'');
// Contract white space
str = str.trim();
// Leading and trailing white space
let outboundText = str.replace(/\s\s+/g, ' ');
return [outboundText,emoticon_up_count,emoticon_down_count];
}
function strFixStutter(str) {
return str.replace(/\s(\w+\s)\1/, " $1")
}
function strEscRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function strReplaceAll(str, find, replace) {
return str.replace(new RegExp(strEscRegExp(find), 'ig'), replace); // ig case insensitve for search
}
function strProper(str) {
for (var i = 0; i < PROPER_NOUNS_DAYS.length; i += 1) {
var regex_dynamic = new RegExp(PROPER_NOUNS_DAYS[i], 'ig');
str = str.replace(regex_dynamic, PROPER_NOUNS_DAYS[i]);
};
for (var i = 0; i < PROPER_NOUNS_MONTHS.length; i += 1) {
var regex_dynamic = new RegExp(PROPER_NOUNS_MONTHS[i], 'ig');
str = str.replace(regex_dynamic, PROPER_NOUNS_MONTHS[i]);
};
for (var i = 0; i < PROPER_NOUNS_NAMES.length; i += 1) {
var regex_dynamic = new RegExp(PROPER_NOUNS_NAMES[i], 'ig');
str = str.replace(regex_dynamic, PROPER_NOUNS_NAMES[i]);
};
return str;
}
function strTitleCase(str) {
return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) {
return match.toUpperCase();
});
}
//function strTitleCase(str) {
// return str.replace(/\w\S*/g, function(txt) {return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
//}
function strFirstAlpha(str) {
for (var i = 0; i < str.length; i += 1) {
if ((str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') ||
(str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) {
return str.charAt(i);
};
};
return '';
}
function strTrimTo(trim_length,str) {
if (str.length > trim_length) {str = str.slice(0,trim_length-1) + "🤐"};
return str;
}
function strEmojiLength(str) {
//http://blog.jonnew.com/posts/poo-dot-length-equals-two
const joiner = "\u{200D}";
const split = str.split(joiner);
let count = 0;