-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotk.js
781 lines (728 loc) · 28.2 KB
/
rotk.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
// ROTKbot version 1.0.0 (C)opyright 2018 GuanZhang
var Discord = require('discord.io');
var token;
// If auth.json is not found, we are probably deploying via ZEIT Now
try {
var auth = require("./auth.json");
token = auth.token;
} catch (err) {
token = process.env.BOT_TOKEN;
}
var admin = require("firebase-admin");
// Fetch the service account key JSON file contents
try {
var serviceAccount = require("./firebase_auth.json");
} catch (err) {
var serviceAccount = require("./firebase_auth_zeit");
}
var databaseURL = "https://rotkbot.firebaseio.com";
// Initialize the app with a service account, granting admin privileges
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: databaseURL
});
// As an admin, the app has access to read and write all data, regardless of Security Rules
var db = admin.database();
var botname = "ROTKbot";
// FIXME need to use roles instead
var authorizedUsers = [ "GuanZhang#9024", "Rinth#6469", "RWal#5900", "Haydden#5436", "IbnBattuta#1417" ];
// participants is an array of player objects consisting of
// name, team, status and damage
var defaultRaid = { "4gods": "dragon", "level": "master", "date": "" };
var participants = [];
var fourGods = [ "dragon", "bird" ];
var levels = [ "minor", "intermediate", "advanced", "master" ];
var raid = [];
var teams = ["main", "sub", "looter"];
let msg = "";
var json;
// User defined options
// Frequency of raids, 1 = every day, 2 = every other day, etc.
let freq = 2
let serverTimeZone = 'Asia/Taipei';
// Four Gods boss HP
let fg_hp = {
"dragon": { "minor": 124499,
"intermediate": 256000,
"advanced": 482000,
"master": 792900
},
"bird": { "minor": 124899,
"intermediate": 183879,
"advanced": 482859,
"master": 843390
},
"tiger": {
},
"tortoise": {
}
};
let hp = 0;
let found;
let time = "";
// Needed for ZEIT Now deployments
require('http').createServer().listen(3000)
// Capitalize first character of the word
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.substr(1);
}
// Update key on Firebase
function updateFirebase(ref, data) {
str = ref.parent + "/" + ref.key;
str = str.replace(databaseURL + "/", "");
printNowTime();
console.log("Updating " + str + " on Firebase");
ref.set(data);
};
// Print members of each team
function printTeam(msg, obj, evt) {
team = capitalize(Object.entries(obj)[0][1].team);
msg = msg + team + " team [" + obj.length + "]: ";
let username = "";
let serverID = evt.d.guild_id;
let userObj;
Object.keys(obj).forEach(function (key) {
userObj = bot.servers[serverID].members[obj[key].name];
// Prints server-specific nickname, if set
if (userObj && userObj.nick != null) {
username = bot.servers[serverID].members[obj[key].name].nick;
} else if (bot.users[obj[key].name] == undefined) {
username = "Unknown";
} else {
username = bot.users[obj[key].name].username;
}
if (obj[key].status) {
username = "**" + username + "**";
}
msg = msg + username;
// Only add comm unless it's the last element
if (!(obj.length - 1 == key)) {
msg = msg + ", ";
}
});
return msg + "\n";
}
// Print damage report and return an array with the report and total damage
function printDamage(msg, obj, evt) {
let serverID = evt.d.guild_id;
var total = 0.0;
// Sort by damage in descending order
obj.sort(function(a, b) {
return b.damage - a.damage;
});
Object.keys(obj).forEach(function (key) {
userObj = bot.servers[serverID].members[obj[key].name];
// Prints server-specific nickname, if set
if (userObj && userObj.nick != null) {
username = bot.servers[serverID].members[obj[key].name].nick;
} else if (bot.users[obj[key].name] == undefined) {
username = "Unknown";
} else {
username = bot.users[obj[key].name].username;
}
pc = obj[key].damage/hp*100;
msg = msg + username + ": " +obj[key].damage+ " (" + pc.toFixed(2)+ "%)\n";
total = total + obj[key].damage
});
return [ msg, total ];
}
// Send msg to the channel where command are specified
function sendDaMessage(channelID, msg, embed) {
bot.sendMessage({
to: channelID,
message: msg,
embed: embed
})
}
// Calculate how much time until the next raid
function timeLeft(evt) {
let serverID = evt.d.guild_id;
let channelID = evt.d.channel_id;
var serverRef = db.ref(serverID+"/"+channelID);
return new Promise(resolve => {
serverRef.limitToLast(1).once('value').then(function(snapshot) {
raid = Object.values(snapshot.val())[0]["raid"];
let date = raid["date"];
let raidDate = new Date(date);
let now = new Date();
let diff = (raidDate - now) / 3600000;
let hours = Math.floor(diff);
let minutes = Math.floor(diff %1 * 60);
if (hours) {
time = hours + " hours and " + minutes;
} else {
time = minutes;
}
resolve(time + " minutes");
});
})
}
// Print out current time for logging
function printNowTime() {
let now = new Date();
process.stdout.write("[" + now.toLocaleString('en-US', {hour12: false}) + "] ");
}
// Check to see if user is authorized to use command
function isAuthorized(user, channel) {
let username = bot.users[user].username + "#" + bot.users[user].discriminator;
if (!authorizedUsers.includes(username)) {
msg = bot.users[user].username + ", you are not authorized to run that command";
sendDaMessage(channel, msg);
return false;
} else {
return true;
}
}
// Init ROTKbot
printNowTime();
console.log("Initializing " + botname);
var bot = new Discord.Client({
token: token,
autorun: true
});
bot.on('ready', function (evt) {
printNowTime();
console.log(botname + " [" + bot.username + "] id: " + bot.id + " ready");
});
// Set the game the bot is playing
bot.setPresence({
game:{ name: "Four Gods Battle" }
});
bot.on('message', function (user, userID, channelID, message, evt) {
// Webhooks don't have userIDs, so ignore them
if (!bot.users[userID]) {
return;
}
let sender = bot.users[userID].username;
var validTeams = teams.filter(e => e !== "looter");
let notRegistered = sender + ", you are currently not registered for the raid, try `!register`";
let invalidTeam = sender + ", you did not specify a valid option, valid teams are " + validTeams.map(e => capitalize(e)).join(" and "); + " (eg. `!register sub`)";
let serverID = evt.d.guild_id;
var serverRef = db.ref(serverID+"/"+channelID);
var curRef;
// Bot will listen on '!' commands
if (message.substring(0, 1) == '!') {
var args = message.substring(1).split(' ');
var cmd = args[0].toLowerCase();
let input = "";
args = args.splice(1);
switch(cmd) {
// Raid info
case 'raid':
serverRef.limitToLast(1).once('value').then(function(snapshot) {
if (snapshot.val()) {
var raid = Object.values(snapshot.val())[0]["raid"];
if (raid) {
var date = raid["date"];
var raidDate = new Date(date);
var time;
timeLeft(evt).then(time => {
if (time.charAt(0) == "-" || isNaN(Date.parse(raidDate))) {
msg = "There is currently no scheduled raid, please check back again later";
} else {
msg = "The next raid will be **" + raid["level"] + " level " + raid["4gods"] + "** and is scheduled for **" +date+ " (server time)** which is **" + time+ "** from now";
}
sendDaMessage(channelID, msg);
})
}
} else {
msg = "There is currently no scheduled raid, please check back again later";
sendDaMessage(channelID, msg);
}
//sendDaMessage(channelID, msg);
});
break;
// Register for raid
case 'register':
var participants;
// User didn't specify team
if (args[0] === undefined) {
msg = invalidTeam;
sendDaMessage(channelID, msg);
break;
} else {
found = validTeams.find(function(team) {
return team == args[0].toLowerCase();
});
}
team = args[0].toLowerCase();
// Specified team not found
if (!found) {
msg = invalidTeam;
sendDaMessage(channelID, msg);
} else {
serverRef.limitToLast(1).once('value').then(function(snapshot) {
if (snapshot.val()) {
participants = Object.values(snapshot.val())[0]["participants"];
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
raid = Object.values(snapshot.val())[0]["raid"];
if (participants) {
found = participants.find(function(player) {
return player.name == userID;
});
if (raid) {
var date = raid["date"];
let nextRaidMsg = " for the next **" +raid["level"] + " level " +raid["4gods"]+ "** raid scheduled for " +date+ " (server time)";
// User not found, register him
if (!found) {
var player = { "name": userID, "team": team, "status": 0, "damage": 0 };
participants.push(player);
updateFirebase(curRef.child("participants"), participants);
team = capitalize(team);
msg = sender + ", you are registered in the " +team+ " team" + nextRaidMsg;
sendDaMessage(channelID, msg);
} else {
// User wants to update team
if (found.team != team) {
found.team = team;
updateFirebase(curRef.child("participants"), participants);
team = capitalize(team);
msg = sender + ", your team has been updated to the " +team+ " team" + nextRaidMsg;
} else {
// User is already registered
msg = sender + ", you are already registered" +nextRaidMsg;
}
sendDaMessage(channelID, msg);
};
}
} else {
// Participants key is empty on Firebase
var player = { "name": userID, "team": team, "status": 0, "damage": 0 };
participants = [];
participants.push(player);
updateFirebase(curRef.child("participants"), participants);
team = capitalize(team);
if (raid) {
var date = raid["date"];
let nextRaidMsg = " for the next **" +raid["level"] + " level " +raid["4gods"]+ "** raid scheduled for " +date+ " (server time)";
msg = sender + ", you are registered in the " +team+ " team" + nextRaidMsg;
}
sendDaMessage(channelID, msg);
}
}
})
};
break;
// Unregister from raid
case 'unregister':
serverRef.limitToLast(1).once('value').then(function(snapshot) {
participants = Object.values(snapshot.val())[0]["participants"];
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
if (participants) {
found = participants.find(function(player) {
return player.name == userID;
});
if (found) {
participants = participants.filter(u => u.name != userID);
updateFirebase(curRef.child("participants"), participants);
msg = sender + ", you are unregistered from the next raid";
}
} else {
msg = notRegistered;
}
sendDaMessage(channelID, msg);
})
break;
// List raid participants
case 'list':
var msg = null;
serverRef.limitToLast(1).once('value').then(function(snapshot) {
if (snapshot.val()) {
participants = Object.values(snapshot.val())[0]["participants"];
if (participants && participants.length > 0) {
let str = "are";
count = participants.length;
if (count == 1) {
str = "is";
}
msg = "There " + str + " currently " +count+ " participant(s): \n";
teams.forEach(function(team) {
teamObj = participants.filter(p => p.team === team);
if (Object.keys(teamObj).length) {
msg = printTeam(msg, teamObj, evt);
}
});
}
}
if (!msg) {
msg = "Currently nobody has registered for the next raid."
}
sendDaMessage(channelID, msg);
});
break;
// Check in during roll call
case 'checkin':
serverRef.limitToLast(1).once('value').then(function(snapshot) {
if (snapshot.val()) {
participants = Object.values(snapshot.val())[0]["participants"];
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
if (participants) {
found = participants.find(function(player) {
return player.name == userID;
});
if (found) {
if (found.status) {
found.status = 0;
updateFirebase(curRef.child("participants"), participants);
msg = sender + ", you are no longer checked in";
sendDaMessage(channelID, msg);
} else {
timeLeft(evt).then(time => {
// Only allow check in an hour before scheduled time
if (time.includes("hours")) {
msg = sender + ", you can only check in one hour in advance";
sendDaMessage(channelID, msg);
} else {
found.status = 1;
updateFirebase(curRef.child("participants"), participants);
msg = sender + ", you are checked in";
sendDaMessage(channelID, msg);
}
});
}
}
}
} else {
msg = notRegistered;
sendDaMessage(channelID, msg);
}
})
break;
// List out available commands
case 'commands':
sendDaMessage(channelID, '', {
"color": 9554529,
"description": "**Available Commands**",
"fields": [
{
"name": "!raid",
"value": "Print info about the next scheduled raid"
},
{
"name": "!register",
"value": "Register for the next raid (options are `Main` or `Sub`)"
},
{
"name": "!unregister",
"value": "Un-register from the next raid"
},
{
"name": "!list",
"value": "List the current participants for the next raid"
},
{
"name": "!checkin",
"value": "Check-in during roll call (to un-checkin, just invoke the command while checked-in)"
},
{
"name": "!damage",
"value": "Print damage report or register damage"
},
{
"name": "!stats",
"value": "Print raid stats"
},
]
});
sendDaMessage(channelID, '', {
"color": 9554529,
"description": "**Superuser Commands**",
"fields": [
{
"name": "!newraid",
"value": "Start a new raid that duplicates players and other info from current raid. Add `fresh` option to setup raid for next day"
},
{
"name": "!nag",
"value": "Nag currently registered players to check-in. Add `damage` option to nag players to report damages before next raid"
},
{
"name": "!clearall",
"value": "Clear all data pertaining to current raid, i.e. registered players, damages, etc."
},
{
"name": "!updateraid",
"value": "Update current raid, options are `raid level`, eg. `!updateraid bird advanced`"
},
{
"name": "!updatetime",
"value": "Update the time of the current raid in the format `March 5 2019 10:00 GMT+8`"
},
]
});
break;
// Print damage report or register damage
case 'damage':
serverRef.limitToLast(1).once('value').then(function(snapshot) {
var raid = Object.values(snapshot.val())[0]["raid"];
if (raid) {
// Look up boss HP depending on level
switch(raid["4gods"]) {
case 'dragon':
hp = fg_hp['dragon'][raid["level"]];
break;
case 'bird':
hp = fg_hp['bird'][raid["level"]];
break;
};
let arr = [];
let total = 0;
input = args[0];
target = args[1];
var raidDate = new Date(raid["date"]).toLocaleDateString('en-US');
serverRef.limitToLast(1).once('value').then(function(snapshot) {
participants = Object.values(snapshot.val())[0]["participants"];
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
if (participants) {
if (input === undefined) {
damageObj = participants.filter(p => p.damage > 0);
if (damageObj.length == 0) {
msg = "Currently there are no damages recorded";
} else {
msg = `Damage for ${raid["level"]} ${raid["4gods"]} on ${raidDate}\n`;
arr = printDamage(msg, participants, evt);
msg = arr[0];
total = parseFloat(arr[1]/hp*100).toFixed(2);
msg = msg + "Total: " +total+ "%\n"
if (total >= 100.0) {
msg = msg + "Boss is dead, everybody can exit";
} else {
left = 100.0 - parseFloat(total);
msg = msg + "Remaining: " +left.toFixed(2)+ "%\n";
}
}
sendDaMessage(channelID, msg);
return;
}
if ((isNaN(input) || parseInt(input) < 0 || parseInt(input) > hp)) {
msg = sender + ", you have entered an invalid number, please enter a positive number less than or equal to " + hp + " (HP of boss)";
sendDaMessage(channelID, msg);
return;
}
found = participants.find(function(player) {
//console.log("player: " + player.name);
//console.log("userID: " + userID);
return player.name == userID;
});
//console.log("target: " +target);
if (found) {
arr = printDamage(msg, participants, evt);
damage = parseInt(input);
total = ((+arr[1] + +(damage-found.damage))/hp*100).toFixed(2);
found.damage = damage;
updateFirebase(curRef.child("participants"), participants);
msg = sender + ", your damage (" +((damage/hp*100).toFixed(2))+ "%) has been recorded. Total damage: "+total+ "%";
} else {
msg = notRegistered;
}
sendDaMessage(channelID, msg);
} else {
msg = "Currently there are no damages recorded";
sendDaMessage(channelID, msg);
}
})
}
})
break;
// The follow commands are meant to be used by the superuser
// Start a new raid
case 'newraid':
if (!isAuthorized(userID, channelID)) {
break;
}
input = args[0];
var newRef = serverRef.push();
serverRef.limitToLast(1).once('value').then(function(snapshot) {
// An entry exists, make a copy
if (snapshot.val()) {
var entry = Object.values(snapshot.val())[0];
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
// Start a new empty raid rotating between raids and incrementing
// date by freq
if (input === "fresh") {
var options = { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: false, timeZone: serverTimeZone, timeZoneName: 'short' };
entry["participants"] = [];
let raidDate = new Date(entry["raid"]["date"]);
raidDate.setDate(raidDate.getDate() + parseInt(freq));
entry["raid"]["date"] = raidDate.toLocaleString('en-US', options).replace(/,/g, '');
// Swap raids
// TODO: Account for White Tiger in future release
if (entry["raid"]["4gods"] === "dragon") {
entry["raid"]["4gods"] = "bird";
} else {
entry["raid"]["4gods"] = "dragon";
}
updateFirebase(newRef, entry);
} else {
// Go through each player and un-checkin them and also clear damage
curRef.child("participants").once('value').then(function(snapshot) {
if (snapshot.val()) {
Object.keys(entry["participants"]).forEach(function(key) {
entry["participants"][key].status = 0;
entry["participants"][key].damage = 0;
});
}
updateFirebase(newRef, entry);
})
}
// Fresh database, start from scratch
} else {
updateFirebase(newRef.child("raid"), defaultRaid);
}
})
msg = "New raid created, you can update raid info with `!updateraid` and `!updatetime`";
sendDaMessage(channelID, msg);
break;
// Uncheck-in all participants (useful for running back-to-back raids)
// case 'uncheckin':
// if (!isAuthorized(userID, channelID)) {
// break;
// }
// participantsRef.once('value').then(function(snapshot) {
// participants = snapshot.val();
// Object.keys(participants).forEach(function(key) {
// participants[key].status = 0;
// });
// updateFirebase(participantsRef, participants);
// })
// break;
// Clear damage report and reset for next run
// case 'cleardamage':
// if (!isAuthorized(userID, channelID)) {
// break;
// }
// participantsRef.once('value').then(function(snapshot) {
// participants = snapshot.val();
// Object.keys(participants).forEach(function(key) {
// participants[key].damage = 0;
// });
// updateFirebase(participantsRef, participants);
// })
// break;
// Tag folks who registered but haven't checked in yet
case 'nag':
msg = "";
if (!isAuthorized(userID, channelID)) {
break;
}
input = args[0];
if (input === "damage") {
serverRef.limitToLast(1).once('value').then(function(snapshot) {
participants = Object.values(snapshot.val())[0]["participants"];
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
Object.keys(participants).forEach(function(key) {
if (participants[key].damage === 0) {
msg = msg + "<@!" + participants[key].name + "> ";
}
});
if (msg === "") {
msg = "All players have registered their damage, you may proceed with `!newraid`";
} else {
msg = msg + "please report your damage ASAP with the `!damage` command";
}
sendDaMessage(channelID, msg);
})
} else {
timeLeft(evt).then(time => {
serverRef.limitToLast(1).once('value').then(function(snapshot) {
participants = Object.values(snapshot.val())[0]["participants"];
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
Object.keys(participants).forEach(function(key) {
if (participants[key].status === 0) {
msg = msg + "<@!" + participants[key].name + "> ";
}
});
if (parseInt(time) < 0) {
msg = "Raid is already in progress or we are currently not raiding, no point in nagging...";
} else {
msg = msg + "raid will start in " +time+ " please `!checkin` now!";
}
sendDaMessage(channelID, msg);
})
})
}
break;
// Reset all data by clearing in-memory variable
case 'clearall':
msg = "";
if (!isAuthorized(userID, channelID)) {
break;
}
printNowTime();
console.log("Clearing all participants data");
// clear in-memory data
serverRef.limitToLast(1).once('value').then(function(snapshot) {
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
participants = [];
updateFirebase(curRef.child("participants"), participants);
})
msg = "All data has been cleared";
sendDaMessage(channelID, msg);
break;
// Update next raid and level
case 'updateraid':
let fourGod = args[0];
let level = args[1];
msg = "";
if (!isAuthorized(userID, channelID)) {
break;
}
if (args.length < 2 || args.length > 2) {
msg = "Invalid options, please specify the 4gods and level for the next raid, eg. `!updateraid dragon minor`";
} else if (!levels.includes(level)) {
msg = "You have specified an invalid level, valid options are " + levels.map(e => e).join(", ");
} else if (!fourGods.includes(fourGod)) {
msg = "You have specified an invalid 4gods, valid options are " + fourGods.map(e => e).join(", ");
} else {
msg = "The next raid has been set to " + level + " level " + fourGod + " raid";
serverRef.limitToLast(1).once('value').then(function(snapshot) {
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
updateFirebase(curRef.child("raid/4gods"), fourGod);
updateFirebase(curRef.child("raid/level"), level);
})
}
sendDaMessage(channelID, msg);
break;
// Update next raid time
case 'updatetime':
input = args.join(" ");
msg = "";
if (!isAuthorized(userID, channelID)) {
break;
}
if (!isNaN(Date.parse(input))) {
raidDate = new Date(input);
date = input;
serverRef.limitToLast(1).once('value').then(function(snapshot) {
var curRef = serverRef.child(Object.keys(snapshot.val())[0]);
updateFirebase(curRef.child("raid/date"), input);
})
msg = "The next raid has been set to " + input;
} else {
msg = "Invalid date, please enter date in format `November 2 2018 20:00 CDT`";
}
sendDaMessage(channelID, msg);
break;
// Print out stats about raids
case 'stats':
serverRef.once('value').then(function(snapshot) {
var numRaids = snapshot.numChildren();
msg = `Total raids: ${numRaids}\n`;
fourGods.forEach(function (fourGod) {
var count = 0;
snapshot.forEach(function (key) {
if (fourGod == key.val()["raid"]["4gods"]) {
count++;
}
})
fourGod = capitalize(fourGod);
msg = msg + `${fourGod}: ${count}\n`;
});
sendDaMessage(channelID, msg);
});
break;
}
}
});
// Re-connect on disconnection with 6 seconds delay
bot.on("disconnect", () => setTimeout(() => bot.connect(), 6000));