This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·3222 lines (2721 loc) · 87.5 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
'use strict'
var util = require('util')
var fs = require('fs')
var http = require('http')
var Bot = require('@kikinteractive/kik')
var firebase = require('firebase')
var schedule = require('node-schedule')
var moment = require('moment');
var contents = fs.readFileSync("BHSAcademyBot.json");
var botData = JSON.parse(contents);
var bot = new Bot(botData)
bot.updateBotConfiguration()
firebase.initializeApp(
{
databaseURL: "https://bhs-academy-kik-bot.firebaseio.com/",
serviceAccount: "/home/ec2-user/BHSAcademyBot/serviceAccountCredentials.json"
})
var database = firebase.database()
var homeworkRef = database.ref("/homework")
var usersRef = database.ref("/users")
var announcementsRef = database.ref("/announcements")
var votingRef = database.ref("/voting")
var feedbackRef = database.ref("/feedback")
var peerRef = database.ref("/peer_review")
var dailyHomeworkSchedule = schedule.scheduleJob('30 15 * * *', function ()
{
var users = []
usersRef.orderByChild("subscribed").equalTo(true).once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var decodedMessageFromUsername = snapshot.key
decodedMessageFromUsername = decodedMessageFromUsername.replace(/%2E/g, "\.")
users.push(decodedMessageFromUsername)
})
getHomeworkString(function (homework)
{
homeworkRef.child("notifications_enabled").once("value", function (snapshot)
{
if (snapshot.val() == true)
{
let homeworkString = Bot.Message.text(homework).addResponseKeyboard(["Dismiss"])
bot.broadcast(homeworkString, users)
console.log("Daily homework notification sent to " + users.length + "users")
}
})
})
})
})
var archiveHomeworkSchedule = schedule.scheduleJob('0 2 * * *', function ()
{
homeworkRef.child("auto_archive_enabled").once("value", function (snapshot)
{
if (snapshot.val() == true)
{
var data = {}
homeworkRef.child("items").once("value", function(snapshot)
{
data["negative_timestamp"] = ((new Date() / 1000) * -1) + 86400
let archiveRef = homeworkRef.child("past").push()
archiveRef.set(snapshot.val())
archiveRef.update(data)
})
homeworkRef.child("items").set(null)
console.log("Homework has been archived")
}
})
})
function createUser(message, callback)
{
var data = {}
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
data[encodedMessageFromUsername] = {
context: "home",
is_admin: false,
subscribed: true
}
usersRef.update(data, function (error)
{
if (typeof callback === 'function')
{
callback(error)
}
})
}
function updateContext(message, user, context)
{
var data = {}
data["context"] = context
usersRef.child(user).update(data)
getContextMessage(message, context, function (contextMessage)
{
if (contextMessage != null)
{
bot.send(contextMessage, message.from)
}
})
}
function getClasses(callback)
{
var returnValue = []
homeworkRef.child("classes").once("value", function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
if (childSnapshot.val() == true)
{
returnValue.push(childSnapshot.key)
}
})
returnValue.push("Cancel")
callback(returnValue)
})
}
function resendContextMessage(message, context)
{
getContextMessage(message, context, function (contextMessage)
{
bot.send(contextMessage, message.from)
})
}
function getContextMessage(message, context, callback)
{
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
switch (context)
{
case "home":
let homeContextMessage = Bot.Message.text("How can I help you?")
let userSuggestedResponses = ["📝 Homework", "📢 Announcements", "🗳 Voting", "🗂 More"]
let adminSuggestedResponses = ["📝 Homework", "📢 Announcements", "🗳 Voting", "🗂 More", "🔒 Admin Actions"]
if (message.mention != "bhsacademybot")
{
adminCheck(message, function (isAdmin)
{
if (isAdmin)
{
callback(homeContextMessage.addResponseKeyboard(adminSuggestedResponses))
}
else
{
callback(homeContextMessage.addResponseKeyboard(userSuggestedResponses))
}
})
}
else
{
callback(null)
}
break
case "settings":
let settingsString = Bot.Message.text("Which setting would you like to change?")
userRef.child("subscribed").once("value", function (snapshot)
{
if (snapshot.val() === true)
{
callback(settingsString.addResponseKeyboard(["Unsubscribe", "Cancel"]), message.from)
}
else
{
callback(settingsString.addResponseKeyboard(["Subscribe", "Cancel"]), message.from)
}
})
break
case "admin_actions":
let adminActionsString = Bot.Message.text("What would you like to do?")
adminCheck(message, function (is_admin)
{
callback(adminActionsString.addResponseKeyboard(["Homework", "Voting", "Make an announcement", "🏠 Back to home"]), message.from)
})
break
case "add_homework_item_classes":
getClasses(function(classes)
{
var homeworkClasses = []
classes.forEach(function(homeworkClass)
{
homeworkClasses.push(homeworkClass)
})
let addHomeworkItemString = Bot.Message.text("What class are you adding homework for?").addResponseKeyboard(homeworkClasses)
callback(addHomeworkItemString)
})
break
case "add_homework_item_body":
var addHomeworkItemBodyString = Bot.Message.text("What is the homework in that class?").addResponseKeyboard(["Cancel"], true)
var currentHomework = "Here is the current homework in "
var homeworkIsInPendingClass = false
homeworkRef.child("pending_items").child(encodedMessageFromUsername).once("value", function(snapshot)
{
let pendingClass = snapshot.val()
currentHomework = currentHomework + pendingClass + ":\n"
homeworkRef.child("items").child(pendingClass).once("value", function(snapshot)
{
if (snapshot.exists())
{
homeworkIsInPendingClass = true
addHomeworkItemBodyString = Bot.Message.text("What is the homework in " + pendingClass + " that you would like to add?").addResponseKeyboard(["Cancel"], true)
snapshot.forEach(function(childSnapshot)
{
currentHomework = currentHomework + childSnapshot.val() + "\n"
})
var responseItems = []
if (homeworkIsInPendingClass)
{
let currentHomeworkMessage = Bot.Message.text(currentHomework)
responseItems.push(currentHomeworkMessage)
}
responseItems.push(addHomeworkItemBodyString)
callback(responseItems)
}
else
{
callback(addHomeworkItemBodyString)
}
})
})
break
case "remove_homework_item":
var homeworkRemovableItems = []
var removeHomeworkItemString = Bot.Message.text("What item would you like to remove")
homeworkRef.child("pending_removal").child(encodedMessageFromUsername).once("value", function(snapshot)
{
homeworkRef.child("items").child(snapshot.val()).once("value", function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
homeworkRemovableItems.push(childSnapshot.val())
})
homeworkRemovableItems.push("Cancel")
removeHomeworkItemString.addResponseKeyboard(homeworkRemovableItems)
callback(removeHomeworkItemString)
})
})
break
case "remove_homework_item_class":
var homeworkRemovableClasses = []
var removeHomeworkItemClassString = Bot.Message.text("Which class would you like to remove homework from?")
homeworkRef.child("items").once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
homeworkRemovableClasses.push(childSnapshot.key)
})
homeworkRemovableClasses.push("Cancel")
removeHomeworkItemClassString.addResponseKeyboard(homeworkRemovableClasses)
callback(removeHomeworkItemClassString)
})
break
case "confirm_add_homework_item":
let addHomeworkItemConfirmationString = Bot.Message.text("There is already homework registered for that class. Are you sure you want to overwrite it?").addResponseKeyboard(["Yes", "No"])
callback(addHomeworkItemConfirmationString)
break
case "make_an_announcement":
let makeAnAnnouncementString = Bot.Message.text("What is the title of the announcement that you would like to make?").addResponseKeyboard(["Cancel"], true)
callback(makeAnAnnouncementString)
break
case "add_announcement_body":
let addAnnouncementBodyString = Bot.Message.text("What is the body of your announcement?").addResponseKeyboard(["Cancel"], true)
callback(addAnnouncementBodyString)
break
case "ask_announcement_image":
let askAnnouncementImageString = Bot.Message.text("Would you like to add an image to your announcement?").addResponseKeyboard(["Yes", "No"])
callback(askAnnouncementImageString)
break
case "ask_change_from":
let askChangeFromString = Bot.Message.text("Would you like to change who the announcement is from (instead of yourself)?").addResponseKeyboard([Bot.Response.friendPicker("Select a person", 1, 1), "No"])
callback(askChangeFromString)
break
case "confirm_make_announcement":
let makeAnnouncementConfirmationString = Bot.Message.text("Are you sure that you want to create this announcement and send a message to eveyone on the subscribed list?").addResponseKeyboard(["Yes", "No"])
callback(makeAnnouncementConfirmationString)
break
case "add_announcement_image":
let addAnnouncementImageString = Bot.Message.text("Please send me the image you would like to attach to this announcement").addResponseKeyboard(["Cancel"], true)
callback(addAnnouncementImageString)
break
case "homework_actions":
var homeworkActionsList = ["Show homework", "Add homework item", "Remove homework item", "Manually clear homework", "Add homework class", "Remove homework class"]
homeworkRef.child("auto_clear_enabled").once("value", function (snapshot)
{
if (snapshot.val() == true)
{
homeworkActionsList.push("Disable homework auto clear")
}
else
{
homeworkActionsList.push("Enable homework auto clear")
}
homeworkRef.child("notifications_enabled").once("value", function (snapshot)
{
if (snapshot.val() == true)
{
homeworkActionsList.push("Disable homework notifications")
}
else
{
homeworkActionsList.push("Enable homework notifications")
}
homeworkActionsList.push("🔙 To Admin Actions")
let homeworkActionsString = Bot.Message.text("What would you like to do concerning homework?").addResponseKeyboard(homeworkActionsList)
callback(homeworkActionsString)
})
})
break
case "clear_homework":
let clearHomeworkString = Bot.Message.text("Are you sure that you want to clear ALL of the currently registered homework?").addResponseKeyboard(["Yes", "No"])
callback(clearHomeworkString)
break
case "enable_homework_auto_clear":
let EnableHomeworkAutoClear = Bot.Message.text("Are you sure that you want to enable homework auto clear? (this happens everyday at 2:00AM)").addResponseKeyboard(["Yes", "No"])
callback(EnableHomeworkAutoClear)
break
case "disable_homework_auto_clear":
let DisableHomeworkAutoClear = Bot.Message.text("Are you sure that you want to disable homework auto clear?").addResponseKeyboard(["Yes", "No"])
callback(DisableHomeworkAutoClear)
break
case "enable_homework_notifications":
let EnableHomeworkNotifications = Bot.Message.text("Are you sure that you want enable homework notifications for everyone? (this happens everyday at 3:30PM)").addResponseKeyboard(["Yes", "No"])
callback(EnableHomeworkNotifications)
break
case "disable_homework_notifications":
let DisableHomeworkNotifications = Bot.Message.text("Are you sure that you want to disable homework notifications?").addResponseKeyboard(["Yes", "No"])
callback(DisableHomeworkNotifications)
break
case "announcements":
let announcements = []
let startTime = ((new Date() / 1000) - 604800) * -1
announcementsRef.child("items").orderByChild("negative_timestamp").endAt(startTime).limitToFirst(19).once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
announcements.push(childSnapshot.val().title)
})
announcements.push("Back")
let announcementsString = Bot.Message.text("Here are the latest announcements").addResponseKeyboard(announcements)
callback(announcementsString)
})
break
case "voting_actions":
let VotingActionsString = Bot.Message.text("What would you like to do concerning voting?").addResponseKeyboard(["Create a poll", "End a poll", "🔙 To Admin Actions"])
callback(VotingActionsString)
break
case "create_a_poll":
let createAPollString = Bot.Message.text("Send me all the votable items that you would lke to add to this poll in individual texts and end me \"Done\" when you have finished").addResponseKeyboard(["Cancel"], true)
callback(createAPollString)
break
case "add_poll_title":
let addPollTitleString = Bot.Message.text("What is the title of this poll?").addResponseKeyboard(["Cancel"], true)
callback(addPollTitleString)
break
case "ask_make_poll_announcement":
let askMakePollAnnouncement = Bot.Message.text("Do you want to send all of the subscribers a notification? (NOTE: ONLY DO THIS IF THE POLL IS IMPORTANT)").addResponseKeyboard(["Yes", "No"])
callback(askMakePollAnnouncement)
break
case "confirm_create_poll":
let ConfirmCreatePollString = Bot.Message.text("Are you sure you want to create this poll?").addResponseKeyboard(["Yes", "No"])
callback(ConfirmCreatePollString)
break
case "voting":
var pollTitles = []
votingRef.child("polls").child("active").limitToLast(19).orderByChild("negative_timestamp").once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
pollTitles.push(childSnapshot.val().title)
})
pollTitles.push("Back")
let votingString = Bot.Message.text("Which poll would you like to view?").addResponseKeyboard(pollTitles)
callback(votingString)
})
break
case "end_a_poll":
var pollTitles = []
votingRef.child("polls").child("active").once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
pollTitles.push(childSnapshot.val().title)
})
pollTitles.push("🔙 To Voting Actions")
let endVotingString = Bot.Message.text("Here are the current active polls. Click one of them to stop taking responses").addResponseKeyboard(pollTitles)
callback(endVotingString)
})
break
case "view_poll_results":
votingRef.child("polls").child("active").once("value", function (snapshot)
{
let activePolls = []
snapshot.forEach(function(childSnapshot)
{
activePolls.push(childSnapshot.val().title)
})
activePolls.push("🔙 To Voting Options")
let viewActivePollsString = Bot.Message.text("Which poll would you like to view the results for?").addResponseKeyboard(activePolls)
callback(viewActivePollsString)
})
break
case "vote":
var votingItems = []
var pollRef = ""
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
votingRef.child("polls").child("active").once("value", function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
if(childSnapshot.child("voters").child(encodedMessageFromUsername).val() == "pending")
{
pollRef = childSnapshot.key
}
})
snapshot.child(pollRef).child("items").forEach(function(childSnapshot)
{
var decodedItemName = childSnapshot.key
decodedItemName = decodedItemName.replace(/%2E/g, "\.")
votingItems.push(decodedItemName)
})
votingItems.push("Cancel")
let votingItemsString = Bot.Message.text("Choose which item you would like to vote for (Note: you can not change this)").addResponseKeyboard(votingItems)
callback(votingItemsString)
})
break
case "feedback":
let feedbackActionsString = Bot.Message.text("Would you like to submit a suggestion or a complaint?").addResponseKeyboard(["Suggestion", "Complaint", "🏠 Back to Home"])
callback(feedbackActionsString)
break
case "suggestion":
let SuggestActionsString = Bot.Message.text("What is your suggestion?").addResponseKeyboard(["Cancel"], true)
callback(SuggestActionsString)
break
case "complaint":
let ComplaintActionsString = Bot.Message.text("What is your complaint?").addResponseKeyboard(["Cancel"], true)
callback(ComplaintActionsString)
break
case "confirm_suggest":
let ConfirmCreateUserInputSuggestString = Bot.Message.text("Are you sure this is all you want to say?").addResponseKeyboard(["Yes", "No"])
callback(ConfirmCreateUserInputSuggestString)
break
case "confirm_complaint":
let ConfirmCreateUserInputComplaintString = Bot.Message.text("Are you sure this is all you want to say?").addResponseKeyboard(["Yes", "No"])
callback(ConfirmCreateUserInputComplaintString)
break
case "more":
let moreString = Bot.Message.text("How can I help you?").addResponseKeyboard(["📲 Feedback", "ℹ️ Admins", "📊 Stats", "👥 Credits", "⚙ Settings", "🏠 Back to home"])
callback(moreString)
break
case "peer_review":
let PeerReviewString = Bot.Message.text("What would you like to do?").addResponseKeyboard(["Review a Document", "Submit a Document", "🏠 Back to home"])
callback(PeerReviewString)
break
case "submit_document":
let SubmitDocumentURLString = Bot.Message.text("Please paste the URL of the document below.").addResponseKeyboard(["Cancel"], true)
callback(SubmitDocumentURLString)
break
case "submit_document_title":
let SubmitDocumentTitleString = Bot.Message.text("What is the title of the document?").addResponseKeyboard(["Cancel"], true)
callback(SubmitDocumentTitleString)
break
case "confirm_submit_document":
let ConfirmSubmitDocumentString = Bot.Message.text("Is this information correct?").addResponseKeyboard(["Yes", "No"])
callback(ConfirmSubmitDocumentString)
break
case "review_document":
var docTitles = []
peerRef.child("documents").limitToLast(19).orderByChild("negative_timestamp").on("child_added", function (snapshot)
{
docTitles.push(snapshot.val().title)
})
peerRef.child("documents").once("value", function (snapshot)
{
docTitles.push("🔙 To Peer Review")
let ReviewDocumentString = Bot.Message.text("Here are all the documents submitted for reviewal. Click on one to be sent to its page.").addResponseKeyboard(docTitles)
callback(ReviewDocumentString)
})
break
case "homework":
let homeworkContextMessage = Bot.Message.text("What class would you like to get the homework for?")
var responses = ["Show all"]
homeworkRef.child("items").once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
responses.push(childSnapshot.key)
})
responses.push("Back")
homeworkContextMessage.addResponseKeyboard(responses)
callback(homeworkContextMessage)
})
break
case "add_homework_item":
let addHomeworkItemClassesString = Bot.Message.text("What is the homework that you would like to add to that class?").addResponseKeyboard(["Cancel"], true)
callback(addHomeworkItemClassesString)
break
}
}
function sendErrorMessage(message, errorType, callback)
{
if (typeof errorType === 'string')
{
switch (errorType)
{
case "context_error":
bot.send(Bot.Message.text("There has been a fatal error. Please contact @pjtnt11 to get this issue resolved"), message.from)
break
}
}
if (typeof callback === 'function')
{
callback()
}
}
function adminCheck(message, callback)
{
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
userRef.child("is_admin").once("value", function (snapshot)
{
callback(snapshot.val())
})
}
function getHomeworkString(callback)
{
homeworkRef.child("items").once("value", function(snapshot)
{
var classHomework = "Here is all the homework for today:\n"
snapshot.forEach(function(classSnapshot)
{
classHomework = classHomework + "\n" + classSnapshot.key + ":\n"
classSnapshot.forEach(function(homeworkSnapshot)
{
classHomework = classHomework + homeworkSnapshot.val() + "\n"
})
})
callback(classHomework)
})
}
bot.onStartChattingMessage((message) =>
{
console.log(message.from + "\: \(started chatting\)")
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
let sendingMessage = Bot.Message.text("Welcome to the Bartlett High School Academy Kik Bot!\n\nWith this bot you will be able to vote on current topics, receive daily homework information and get notified of announcements.\n\nThis bot was created from scratch by Patrick Stephen so if you have any questions, contact him at @pjtnt11")
createUser(message, function (error)
{
if (error == null)
{
getContextMessage(message, "home", function (contextMessage)
{
bot.send([sendingMessage, contextMessage], message.from)
})
}
})
})
bot.onPictureMessage((message) =>
{
message.markRead()
console.log(message.from + ": (picture message) " + message.picUrl)
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
userRef.once("value", function (snapshot)
{
if (!snapshot.exists())
{
createUser(message)
}
})
userRef.child("context").once("value", function (snapshot)
{
if (snapshot.val() == "add_announcement_image")
{
var announcementData = {}
announcementData["picture_url"] = message.picUrl
announcementsRef.child("pending").child(encodedMessageFromUsername).update(announcementData)
userRef.update(
{
context: "ask_change_from"
})
getContextMessage(message, "ask_change_from", function (contextMessage)
{
bot.send(contextMessage, message.from)
})
}
else
{
resendContextMessage(message, snapshot.val())
}
})
})
bot.onVideoMessage((message) =>
{
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
userRef.once("value", function (snapshot)
{
if (!snapshot.exists())
{
createUser(message)
}
})
message.markRead()
console.log(message.from + ": (video message) " + message.videoUrl)
userRef.child("context").once("value", function (snapshot)
{
resendContextMessage(message, snapshot.val())
})
})
bot.onFriendPickerMessage((message) =>
{
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
userRef.once("value", function (snapshot)
{
if (!snapshot.exists())
{
createUser(message)
}
})
message.markRead()
console.log(message.from + ": (friend picker message) " + message.picked)
userRef.child("context").once("value", function (snapshot)
{
let context = snapshot.val()
if (context == "ask_change_from")
{
var data = {}
data["from"] = message.picked[0]
announcementsRef.child("pending").child(encodedMessageFromUsername).update(data)
updateContext(message, encodedMessageFromUsername, "confirm_make_announcement")
}
else
{
resendContextMessage(message, snapshot.val())
}
})
})
bot.onScanDataMessage((message) =>
{
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
userRef.once("value", function (snapshot)
{
if (!snapshot.exists())
{
createUser(message)
}
})
message.markRead()
console.log(message.from + ": (scan data message) " + message.scanData)
userRef.child("context").once("value", function (snapshot)
{
resendContextMessage(message, snapshot.val())
})
})
bot.onStickerMessage((message) =>
{
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
userRef.once("value", function (snapshot)
{
if (!snapshot.exists())
{
createUser(message)
}
})
message.markRead()
console.log(message.from + ": (sticker message) " + message.stickerUrl)
userRef.child("context").once("value", function (snapshot)
{
resendContextMessage(message, snapshot.val())
})
})
bot.onTextMessage((message) =>
{
console.log(message.from + ": " + message.body)
if (message.body != "")
{
message.markRead()
}
var encodedMessageFromUsername = message.from
encodedMessageFromUsername = encodedMessageFromUsername.replace(/\./g, "%2E")
let userRef = usersRef.child(encodedMessageFromUsername)
userRef.child("context").once("value", function (snapshot)
{
context = snapshot.val()
if (!snapshot.exists())
{
createUser(message)
}
var context = snapshot.val()
if (message.mention == "bhsacademybot")
{
let mentionResponceKeyboard = ["Homework", "Latest Announcement", "Stats", "Admins"]
switch (message.body)
{
case "homework":
case "Homework":
case "HOMEWORK":
getHomeworkString(function (homeworkString)
{
message.reply([Bot.Message.text(homeworkString).addResponseKeyboard(mentionResponceKeyboard)])
})
break
case "latest announcement":
case "Latest Announcement":
announcementsRef.child("items").limitToLast(1).once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
let announcementString = Bot.Message.text("Announcement from @" + childSnapshot.val().from + " - \n\n" + childSnapshot.val().title + ":\n\n" + childSnapshot.val().body).addResponseKeyboard(mentionResponceKeyboard)
if (childSnapshot.val().picture_url !== undefined)
{
let picture = Bot.Message.picture(childSnapshot.val().picture_url)
message.reply([announcementString, picture], message.from)
}
else
{
message.reply([announcementString], message.from)
}
})
})
break
case "stats":
case "Stats":
var numRegisteredUsers = 0
var numSubscribedUsers = 0
var numAdmins = 0
usersRef.on("child_added", function (snapshot)
{
if (snapshot.val().subscribed == true)
{
numSubscribedUsers++
}
if (snapshot.val().is_admin == true)
{
numAdmins++
}
})
usersRef.once("value", function (snapshot)
{
numRegisteredUsers = snapshot.numChildren()
let statsString = Bot.Message.text("There are currently " + numRegisteredUsers + " users registered in the database. Of those, " + numSubscribedUsers + " are subscribed and " + numAdmins + " are admins").addResponseKeyboard(mentionResponceKeyboard)
message.reply([statsString], message.from)
})
break
case "admins":
case "Admins":
var adminsString = "Here are the admins\n"
var postAdminString = "Contact one of them if you are would like to create a poll or make an announcement"
usersRef.on("child_added", function (snapshot)
{
if (snapshot.val().is_admin == true)
{
var decodedMessageFromUsername = snapshot.key
decodedMessageFromUsername = decodedMessageFromUsername.replace(/%2E/g, "\.")
adminsString = adminsString + "@" + snapshot.key + "\n"
}
})
usersRef.once("value", function (snapshot)
{
adminsString = adminsString + "\n" + postAdminString
usersRef.off("child_added")
message.reply([Bot.Message.text(adminsString).addResponseKeyboard(mentionResponceKeyboard)])
})
break
default:
message.reply(Bot.Message.text("Sorry, I don't know what that means. Please use one of the following commands:\n\nHomework\nLatest Announcement\nStats\nAdmins").addResponseKeyboard(mentionResponceKeyboard))
break
}
}
else if (message.body == "Dismiss")
{
resendContextMessage(message, context)
}
else if (message.body == "View")
{
announcementsRef.child("items").orderByChild("negative_timestamp").limitToFirst(1).once("value", function (snapshot)
{
snapshot.forEach(function(childSnapshot)
{
let announcementString = Bot.Message.text(childSnapshot.val().body).addResponseKeyboard("Dismiss")
if (childSnapshot.val().picture_url !== undefined)
{
let picture = Bot.Message.picture(childSnapshot.val().picture_url).addResponseKeyboard("Dismiss")
bot.send([announcementString, picture], message.from)
}
else
{
bot.send([announcementString], message.from)
}
})
})
}
else
{
switch (context)