This repository has been archived by the owner on Jan 27, 2021. It is now read-only.
/
discord.js
1238 lines (1096 loc) · 51.6 KB
/
discord.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
/**
* @typedef {import("twitch").Stream} TwitchApi.Stream
*/
const DiscordJs = require("discord.js"),
Commands = require("./commands"),
Db = require("./database"),
Exception = require("./exception"),
Log = require("./log"),
settings = require("./settings"),
Tmi = require("./tmi"),
Twitch = require("./twitch"),
User = require("./user"),
Warning = require("./warning"),
discord = new DiscordJs.Client(/** @type {DiscordJs.ClientOptions} */ (settings.discord.options)), // eslint-disable-line no-extra-parens
messageParse = /^!(?<cmd>[^ ]+)(?: +(?<args>.*[^ ]))? *$/,
urlParse = /^https:\/\/www.twitch.tv\/(?<user>.+)$/;
/**
* @type {Object<string, TwitchApi.Stream>}
*/
const liveChannels = {};
/**
* @type {number[]}
*/
const hostingTimestamps = [];
/**
* @type {string[]}
*/
const hosts = [];
/**
* @type {Object<string, NodeJS.Timeout>}
*/
const channelDeletionTimeouts = {};
/**
* @type {string[]}
*/
const streamers = [];
let currentHost = "",
lastHost = 0,
manualHosting = false,
readied = false,
wasEmptyLast = false;
/**
* @type {Commands}
*/
let commands;
/**
* @type {DiscordJs.TextChannel}
*/
let liveStreamAnnouncementsChannel;
/**
* @type {DiscordJs.TextChannel}
*/
let sixBotGGChannel;
/**
* @type {DiscordJs.Guild}
*/
let sixGuild;
/**
* @type {DiscordJs.Role}
*/
let streamNotifyRole;
/**
* @type {DiscordJs.CategoryChannel}
*/
let streamersCategory;
/**
* @type {DiscordJs.Role}
*/
let streamersRole;
/**
* @type {DiscordJs.CategoryChannel}
*/
let voiceCategory;
// #### # #
// # # #
// # # ## ### ### ### # ## ## #
// # # # # # # # # ## # # ##
// # # # ### # # # # # #
// # # # # # # # # # # ##
// #### ### #### ### ### # ## #
/**
* A static class that handles all Discord.js interctions.
*/
class Discord {
// #
// #
// ## ## # # # # ### ### ### ###
// # # # #### #### # # # # # # ##
// # # # # # # # # ## # # # # ##
// ## ## # # # # # # # # ### ###
/**
* @returns {Commands} The commands object.
*/
static get commands() {
return commands;
}
// # # #
// # #
// ### ## ### ## ## ### ###
// # # # ## # # # # # # #
// # # # ## # # # # # #
// ### ### ### ## ## # ###
/**
* @returns {DiscordJs.Client} The Discord object.
*/
static get discord() {
return discord;
}
// # # # #
// # # # #
// ## # # ### ### ## ### ### #### ## ### ###
// # # # # # # # # ## # # # # # # # ## #
// # # # # # ## # # # # # # # ## #
// ## ### # # ## # # ## # # ## ### ##
/**
* Gets the current host.
* @returns {string} The current host.
*/
static get currentHost() {
return currentHost;
}
/**
* Sets the current host.
* @param {string} value The current host.
*/
static set currentHost(value) {
currentHost = value;
}
// ## # # # #
// # # # #
// # # ### ### # # ### # #### ## ### ### ## ### ###
// #### # # # # # # # # # # # # # ## # # # # # #
// # # # ## # # # # # ## # # # # # ## # # # # ##
// # # # # # # ### # # ### # # ## ### ## ### # # #
// ###
/**
* Gets whether manual hosting is active.
* @returns {boolean} Whether manual hosting is active.
*/
static get manualHosting() {
return manualHosting;
}
/**
* Sets whether manual hosting is active.
* @param {boolean} value Whether manual hosting is active.
*/
static set manualHosting(value) {
manualHosting = value;
}
// #
//
// ## ## ## ###
// # # # # # #
// # # # # # #
// ### ## ## # #
/**
* Six Gaming's icon.
* @returns {string} The URL of the icon.
*/
static get icon() {
if (discord && discord.status === 0) {
return discord.user.avatarURL;
}
return void 0;
}
// # ## # ## #
// # # # #
// ### ## # # # # # ## # ###
// ## # ## # ## # # # # # #
// ## # ## # # # # # # # #
// ### ### # # ### ### ### ### ###
/**
* The Six Gaming guild.
* @returns {DiscordJs.Guild} The Six Gaming guild object.
*/
static get sixGuild() {
return sixGuild;
}
// # #
// # #
// ### ### ### ### ### # # ###
// ## # # # # # # # # # #
// ## # # ## # # # # # #
// ### ## # # # ## ### ###
// #
/**
* Starts up the connection to Discord.
* @returns {void}
*/
static startup() {
commands = new Commands(Discord);
discord.on("ready", () => {
Log.log("Connected to Discord.");
sixGuild = discord.guilds.find((g) => g.name === "Six Gaming");
liveStreamAnnouncementsChannel = /** @type {DiscordJs.TextChannel} */ (sixGuild.channels.find((c) => c.name === "live-stream-announcements")); // eslint-disable-line no-extra-parens
sixBotGGChannel = /** @type {DiscordJs.TextChannel} */ (sixGuild.channels.find((c) => c.name === "sixbotgg")); // eslint-disable-line no-extra-parens
streamersCategory = /** @type {DiscordJs.CategoryChannel} */ (sixGuild.channels.find((c) => c.name === "Streamers")); // eslint-disable-line no-extra-parens
voiceCategory = /** @type {DiscordJs.CategoryChannel} */ (sixGuild.channels.find((c) => c.name === "Voice")); // eslint-disable-line no-extra-parens
streamersRole = sixGuild.roles.find((r) => r.name === "Streamers");
streamNotifyRole = sixGuild.roles.find((r) => r.name === "Stream Notify");
// Start deleting old Discord channels.
sixGuild.channels.filter((channel) => channel.type === "voice").forEach((/** @type {DiscordJs.VoiceChannel} */ channel) => {
if (channel.name !== "\u{1F4AC} General" && channel.members.size === 0) {
Discord.markEmptyVoiceChannel(channel);
}
});
if (!readied) {
readied = true;
Discord.checkStreams();
}
});
discord.on("disconnect", (err) => {
Log.exception("Disconnected from Discord.", err);
});
discord.on("message", async (message) => {
if (message.guild && message.guild.name === "Six Gaming" && message.channel instanceof DiscordJs.TextChannel && message.channel.name === "sixbotgg" && message.channel.type === "text") {
await Discord.message(message.author, message.content);
}
});
discord.on("voiceStateUpdate", (oldMember, newMember) => {
if (oldMember.voiceChannel) {
if (oldMember.voiceChannel.name !== "\u{1F4AC} General" && oldMember.voiceChannel.members.size === 0) {
Discord.markEmptyVoiceChannel(oldMember.voiceChannel);
}
}
if (newMember.voiceChannel) {
if (channelDeletionTimeouts[newMember.voiceChannel.id]) {
clearTimeout(channelDeletionTimeouts[newMember.voiceChannel.id]);
delete channelDeletionTimeouts[newMember.voiceChannel.id];
}
}
});
discord.on("presenceUpdate", (oldMember, newMember) => {
if (newMember.presence && newMember.presence.game && newMember.presence.game.streaming && newMember.presence.game.url && newMember.presence.game.url.includes("twitch.tv")) {
if (urlParse.test(newMember.presence.game.url)) {
const {groups: {user}} = urlParse.exec(newMember.presence.game.url);
Db.streamerExistsByDiscord(newMember.id).then((exists) => {
if (!exists) {
Db.addStreamer(user, newMember.id).then(() => {
Db.deleteHostByUser(user).then(() => {
Discord.addStreamersRole(newMember);
Discord.queue(`${newMember}, you are now setup as a Six Gaming streamer at http://twitch.tv/${user}. If you would like a text channel on Discord for your Twitch community, you can use \`!addmychannel\`.`);
Discord.addStreamer(user);
Discord.removeHost(user);
}).catch((err) => {
Log.exception("There was a database error while removing a hosted streamer after becoming a Six Gaming streamer.", err);
});
}).catch((err) => {
Log.exception("There was a database error inserting into the streamer table.", err);
});
}
}).catch((err) => {
Log.exception(`Error while checking if ${newMember} is a streamer.`, err);
});
}
}
});
}
// #
// #
// ## ## ### ### ## ## ###
// # # # # # # # # ## # #
// # # # # # # # ## # #
// ## ## # # # # ## ## ##
/**
* Connects to Discord. Should only ever be called once.
* @returns {void}
*/
static connect() {
Log.log("Connecting to Discord...");
discord.login(settings.discord.token).then(() => {
Log.log("Connected.");
}).catch((err) => {
Log.exception("Error connecting to Discord, will automatically retry.", err);
});
discord.on("error", (err) => {
Log.exception("Discord error.", err);
});
}
// # ## # #
// # # # #
// ## ### # ## ### ### ## ## ### ## ###
// # ## # # # # # # # # ## # # # ## # #
// # ## # # # # # # # # ## # # ## # #
// ### ### ## ## # # # # ## ## ## ## ###
/**
* Determines whether the bot is connected to Discord.
* @returns {boolean} Whether the bot is connected to Discord.
*/
static isConnected() {
return discord && sixGuild ? discord.status === 0 : false;
}
// # # ## ### ### ### ### ##
// #### # ## ## ## # # # # # ##
// # # ## ## ## # ## ## ##
// # # ## ### ### # # # ##
// ###
/**
* Parses a message.
* @param {DiscordJs.User} user The user who sent the message.
* @param {string} message The text of the message.
* @returns {Promise} A promise that resolves when the message is parsed.
*/
static async message(user, message) {
const member = Discord.findGuildUserById(user.id);
if (!member) {
return;
}
for (const text of message.split("\n")) {
if (messageParse.test(text)) {
const {groups: {cmd, args}} = messageParse.exec(text),
command = cmd.toLocaleLowerCase();
if (Object.getOwnPropertyNames(Commands.prototype).filter((p) => typeof Commands.prototype[p] === "function" && p !== "constructor").indexOf(command) !== -1) {
let success;
try {
await Discord.commands[command](new User(member), args);
} catch (err) {
if (err instanceof Warning) {
Log.warning(`${member}: ${text}\n${err}`);
} else if (err instanceof Exception) {
Log.exception(err.message, err.innerError);
} else {
Log.exception("Unhandled error found.", err);
}
return;
}
if (success) {
Log.log(`${member}: ${text}`);
}
}
}
}
}
// ### # # ## # # ##
// # # # # # ## # # # ##
// # # # # ## # # ##
// ### ### ## ### ##
// #
/**
* Queues a message to be sent.
* @param {string} message The message to be sent.
* @param {DiscordJs.TextChannel|DiscordJs.DMChannel|DiscordJs.GroupDMChannel|DiscordJs.GuildMember} [channel] The channel to send the message to.
* @returns {Promise<DiscordJs.Message>} A promise that resolves with the sent message.
*/
static async queue(message, channel) {
if (!channel) {
channel = sixBotGGChannel;
}
if (channel.id === discord.user.id) {
return void 0;
}
let msg;
try {
msg = await Discord.richQueue(new DiscordJs.RichEmbed({description: message}), channel);
} catch {}
return msg;
}
// # # ##
// # # #
// ### ## ## ### # # # # ## # # ##
// # # # # # # # # # # # ## # # # ##
// # # # # # ## # # # ## # # ##
// # ### ## # # ## ### ## ### ##
// #
/**
* Queues a rich embed message to be sent.
* @param {DiscordJs.RichEmbed} embed The message to be sent.
* @param {DiscordJs.TextChannel|DiscordJs.DMChannel|DiscordJs.GroupDMChannel|DiscordJs.GuildMember} [channel] The channel to send the message to.
* @returns {Promise<DiscordJs.Message>} A promise that resolves with the sent message.
*/
static async richQueue(embed, channel) {
if (!channel) {
channel = sixBotGGChannel;
}
if (channel.id === discord.user.id) {
return void 0;
}
embed.setFooter(embed.footer ? embed.footer.text : "", Discord.icon);
if (embed && embed.fields) {
embed.fields.forEach((field) => {
if (field.value && field.value.length > 1024) {
field.value = field.value.substring(0, 1024);
}
});
}
if (!embed.color) {
embed.setColor(0x16F6F8);
}
if (!embed.timestamp) {
embed.setTimestamp(new Date());
}
let msg;
try {
const msgSend = await channel.send("", embed);
if (msgSend instanceof Array) {
msg = msgSend[0];
} else {
msg = msgSend;
}
} catch {}
return msg;
}
// # ### # #
// # # # #
// ## ### # # ## ### ## ### ### ### ## ###
// # ## ### # # # # # # # ## # # ## # #
// # ## # # # # # # # ## ## # ## #
// ### ### # ## ### ## # # ### ## ## #
/**
* Determins whether the user is a podcaster.
* @param {DiscordJs.GuildMember} user The user to check.
* @returns {boolean} Whether the user is a podcaster.
*/
static isPodcaster(user) {
const member = sixGuild.member(user);
if (member) {
return member.roles.filter((role) => role.name === "Podcasters").size > 0;
}
return false;
}
// # ##
// # #
// ## ### # # # # ### ## ###
// # ## # # # # # # # ## # #
// # ## # # #### # # ## #
// ### ### ## #### # # ## #
/**
* Determines whether the user is the owner.
* @param {DiscordJs.GuildMember} user The user to check.
* @returns {boolean} Whether the user is a podcaster.
*/
static isOwner(user) {
return user && user.user.username === settings.admin.username && user.user.discriminator === settings.admin.discriminator;
}
// # # ## #
// # # # # #
// ## ### ## ## # # # ### ### ## ### # # ###
// # # # # ## # ## # # # # # ## # # #### ##
// # # # ## # # # # # # # ## # ## # # ##
// ## # # ## ## # # ## ## # ## # # # # ###
/**
* Checks what streams are live.
* @returns {Promise} A promise that resolves when the streams are checked.
*/
static async checkStreams() {
// Remove users who left the server.
let streamerList;
try {
streamerList = await Db.getStreamers();
} catch (err) {
Log.exception("Database error getting streamers.", err);
setTimeout(Discord.checkStreams, 60000);
return;
}
if (streamerList) {
streamerList.forEach((streamer) => {
const {discord: id, streamer: name} = streamer;
if (!Discord.findGuildUserById(id)) {
Db.deleteStreamerByDiscord(id).then(() => {
Discord.removeStreamer(name);
}).catch((err) => {
Log.exception(`Database error removing streamer \`${name}\` \`${id}\`.`, err);
});
}
});
}
let streams;
try {
streams = await Twitch.getStreams(["sixgaminggg"].concat(streamers, hosts));
} catch (err) {
// This is commonly not an error, just try again in a minute.
setTimeout(Discord.checkStreams, 60000);
return;
}
const wentOffline = [],
wentLive = [];
let live = [];
// Get the list of live channels.
try {
live = streams.map((stream) => stream.userDisplayName.toLocaleLowerCase());
} catch (err) {
Log.exception("Error checking streams.", err);
setTimeout(Discord.checkStreams, 60000);
return;
}
// Being empty once is usually a sign of an error. Will try again next time.
if (live.length === 0) {
if (!wasEmptyLast) {
Log.log("Live list was empty.");
wasEmptyLast = true;
setTimeout(Discord.checkStreams, 60000);
return;
}
} else {
wasEmptyLast = false;
}
// Detect which streams have gone offline.
for (const key in liveChannels) {
if (live.indexOf(key) === -1) {
wentOffline.push(key);
}
}
// Remove live channel data from offline streams.
for (const name of wentOffline) {
if (name.toLowerCase() === "sixgaminggg") {
discord.user.setStatus("online").catch((err) => {
if (err.code === "ECONNRESET") {
Log.warning("Connection reset while setting status to online.");
} else {
Log.exception("Error setting status to online.", err);
}
});
discord.user.setActivity(null, {}).catch((err) => {
if (err.code === "ECONNRESET") {
Log.warning("Connection reset while removing activity.");
} else {
Log.exception("Error removing activity.", err);
}
});
}
delete liveChannels[name];
}
// Detect which streams have gone online.
live.forEach((name) => {
if (!liveChannels[name] && wentLive.indexOf(name) === -1) {
wentLive.push(name);
}
});
// Save channel data.
for (const stream of streams) {
let channel;
try {
channel = await Twitch.getChannelStream(stream.userId);
} catch (err) {
Log.exception("Error getting the channel stream.", err);
}
try {
liveChannels[stream.userDisplayName.toLocaleLowerCase()] = await channel.getStream();
} catch (err) {
Log.exception("Error getting the channel stream's data.", err);
}
}
// Discord notifications for new live channels.
wentLive.forEach((stream) => {
Discord.announceStream(liveChannels[stream]);
});
// If manual hosting is active, check it. Afterwards, update hosting.
if (manualHosting) {
let hostStreams;
try {
hostStreams = await Twitch.getStreams([currentHost]);
} catch (err) {
Discord.updateHosting(live);
Log.exception(`Error checking current host ${currentHost}.`, err);
}
if (!hostStreams || hostStreams.length === 0) {
Discord.updateHosting(live);
Log.exception(`Host ${currentHost} does not exist.`);
}
let results;
try {
results = await Twitch.getChannelStream(hostStreams[0].userId);
} catch (err) {
// Skip the current round of checking the manual host, and just check again next time.
Discord.updateHosting(live);
Log.exception(`Error checking current host ${currentHost}.`, err);
return;
}
let stream;
try {
stream = await results.getStream();
} catch (err) {
Discord.updateHosting(live);
Log.exception(`Error getting stream while checking current host ${currentHost}.`, err);
return;
}
manualHosting = !!(results && stream);
if (manualHosting) {
liveChannels[currentHost] = stream;
} else {
delete liveChannels[currentHost];
currentHost = "";
}
Discord.updateHosting(live);
} else {
Discord.updateHosting(live);
}
}
// # # # # # #
// # # # # #
// # # ### ### ### ### ## #### ## ### ### ## ### ###
// # # # # # # # # # # ## # # # # ## # # # # # #
// # # # # # # # ## # ## # # # # ## # # # # ##
// ### ### ### # # ## ## # # ## ### ## ### # # #
// # ###
/**
* Updates which channel is being hosted.
* @param {string[]} live An array of live channels.
* @returns {void}
*/
static updateHosting(live) {
let liveStreamers;
if (Discord.isSixGamingLive()) {
// Six Gaming is live, no need to update hosting.
setTimeout(Discord.checkStreams, 60000);
return;
}
if (manualHosting && currentHost && liveChannels[currentHost]) {
// Manual hosting is in effect, no need to update hosting.
setTimeout(Discord.checkStreams, 60000);
return;
}
if (hostingTimestamps.length > 2 && hostingTimestamps[0] + 1805000 > new Date().getTime()) {
// Hosted 3 times in under 30 minutes, cannot update hosting.
setTimeout(Discord.checkStreams, 60000);
return;
}
if (currentHost && !liveChannels[currentHost]) {
lastHost = 0;
}
if (lastHost + 600000 > new Date().getTime()) {
// Last host happened within 10 minutes, don't switch yet.
setTimeout(Discord.checkStreams, 60000);
return;
}
// Get lowercase list of live streamers.
live = live.map((streamer) => streamer.toLowerCase());
// Try to host a live streamer.
liveStreamers = streamers.filter((streamer) => live.indexOf(streamer.toLowerCase()) !== -1);
if (liveStreamers.length > 0) {
if (liveStreamers[0] !== currentHost) {
const host = liveStreamers[0].toLowerCase();
Tmi.host("sixgaminggg", host).then(() => {
currentHost = host;
Tmi.queue(`Now hosting Six Gamer ${currentHost}. Check out their stream at http://twitch.tv/${currentHost}!`);
}).catch((err) => {
if (["bad_host_hosting", "bad_host_error"].indexOf(err) === -1) {
Log.exception("Problem hosting channel.", err);
}
});
lastHost = new Date().getTime();
hostingTimestamps.push(new Date().getTime());
while (hostingTimestamps.length > 3) {
hostingTimestamps.splice(0, 1);
}
streamers.splice(streamers.indexOf(currentHost), 1);
Discord.addHost(currentHost);
}
setTimeout(Discord.checkStreams, 60000);
return;
}
if (lastHost + 3600000 > new Date().getTime()) {
// Last host happened within an hour, don't switch yet.
setTimeout(Discord.checkStreams, 60000);
return;
}
// Try to host a live host.
liveStreamers = hosts.filter((host) => live.indexOf(host.toLowerCase()) !== -1);
if (liveStreamers.length > 0) {
if (liveStreamers[0].toLowerCase() !== currentHost) {
const host = liveStreamers[0].toLowerCase();
Tmi.host("sixgaminggg", host).then(() => {
currentHost = host;
Tmi.queue(`Now hosting ${currentHost}. Check out their stream at http://twitch.tv/${currentHost}!`);
}).catch((err) => {
if (["bad_host_hosting", "bad_host_error"].indexOf(err) === -1) {
Log.exception("Problem hosting channel.", err);
}
});
lastHost = new Date().getTime();
hostingTimestamps.push(new Date().getTime());
while (hostingTimestamps.length > 3) {
hostingTimestamps.splice(0, 1);
}
hosts.splice(hosts.indexOf(currentHost), 1);
Discord.addHost(currentHost);
}
setTimeout(Discord.checkStreams, 60000);
return;
}
setTimeout(Discord.checkStreams, 60000);
}
// ## #
// # # #
// ### ### ### ## # # ### ## ## # ### ### ## ### # #
// # # # # # # # # # # # # # # ## # # # # # ## # # ####
// # ## # # # # # # # # # # # ## # # # # ## # ## # #
// # # # # # # ## ### # # ## ## ## ## # ## # # # #
/**
* Announces a live stream.
* @param {TwitchApi.Stream} stream The stream.
* @returns {void}
*/
static announceStream(stream) {
const message = new DiscordJs.RichEmbed({
timestamp: new Date(),
color: 0x16F6F8,
footer: {icon_url: Discord.icon}, // eslint-disable-line camelcase
thumbnail: {
url: stream.channel.logo,
width: 300,
height: 300
},
image: {
url: stream.channel.profileBanner,
width: 1920,
height: 480
},
url: stream.channel.url,
fields: []
});
message.addField("Stream Title", stream.channel.status);
if (stream.game) {
message.addField("Now Playing", stream.game);
}
if (stream.channel.displayName.toLowerCase() === "sixgaminggg") {
message.setDescription(`${streamNotifyRole} - Six Gaming just went live on Twitch! Watch at ${stream.channel.url}`);
currentHost = "";
manualHosting = false;
Tmi.unhost("sixgaminggg").catch(() => {});
Tmi.queue("What's going on everyone? Six Gaming is live!");
discord.user.setStatus("online").catch((err) => {
if (err.code === "ECONNRESET") {
Log.warning("Connection reset while setting status to online.");
} else {
Log.exception("Error setting status to online.", err);
}
});
discord.user.setActivity(stream.channel.status, {url: "http://twitch.tv/SixGamingGG", type: "STREAMING"}).catch((err) => {
if (err.code === "ECONNRESET") {
Log.warning("Connection reset while setting activity.");
} else {
Log.exception("Error setting activity.", err);
}
});
} else if (streamers.indexOf(stream.channel.displayName.toLowerCase()) !== -1) {
message.setDescription(`${streamNotifyRole} - Six Gamer ${stream.channel.displayName} just went live on Twitch! Watch at ${stream.channel.url}`);
} else if (hosts.indexOf(stream.channel.displayName.toLowerCase()) !== -1) { // eslint-disable-line no-negated-condition
message.setDescription(`${stream.channel.displayName} just went live on Twitch! Watch at ${stream.channel.url}`);
} else {
message.setDescription(`${stream.channel.displayName} has been hosted by Six Gaming on Twitch! Watch at ${stream.channel.url}`);
lastHost = 0;
hostingTimestamps.push(new Date().getTime());
while (hostingTimestamps.length > 3) {
hostingTimestamps.splice(0, 1);
}
}
Discord.richQueue(message, liveStreamAnnouncementsChannel);
}
// # #### # # # # ## # ##
// # # # # # # # # #
// # # ### ### # # ### # # ### ### # # # # ## ## ## ## # ### ### ### ### ## #
// #### # # # # ## # #### # # # # # # # # # # # # ## # # # # # # # # # # ## #
// # # # ## # # # # # # # # # # # ## # # # # ## # # # # # ## # # # # ## #
// # # # # # # # #### # # ### ## # ## ## ### ## ## ## # # # # # # # # ## ###
// # #
/**
* Marks a voice channel as empty, queuing it for deleting in 5 minutes.
* @param {DiscordJs.VoiceChannel} channel The voice channel that is now empty.
* @returns {void}
*/
static markEmptyVoiceChannel(channel) {
channelDeletionTimeouts[channel.id] = setTimeout(async () => {
try {
await channel.delete();
} catch (err) {
Log.exception(`Couldn't delete empty voice channel ${channel}.`, err);
}
delete channelDeletionTimeouts[channel.id];
}, 300000);
}
// # # # ## # ##
// # # # # #
// ### ## ### ## ### ## ## ### # ### ### ### ### ## #
// # # # # ## # # # # # # # # # # # # # # # # # ## #
// # # # # ## # # # # # # # # # # # # ## # # # # ## #
// ### ## ### ### ## ### ## # # ## # # # # # # # # ## ###
// #
/**
* Positions a channel to the specified index.
* @param {number} index The index.
* @param {DiscordJs.GuildChannel[]} channels The guild channels.
* @returns {Promise} A promise that resolves when the channel has been positioned.
*/
static async positionChannel(index, channels) {
const channel = sixGuild.channels.get(channels[index].id);
index++;
try {
await channel.edit({position: index});
} catch (err) {
Log.exception("Problem repositioning channels.", err);
return;
}
if (index < channels.length) {
await Discord.positionChannel(index, channels);
}
}
// # ### # # ## # ##
// # # # # # # # #
// ### ## ### ### # # ## ### ## ## ### ### # ### ### ### ### ## # ###
// ## # # # # # # # # ## # # # # # # # # # # # # # # # # # ## # ##
// ## # # # # # # # ## # # # # # # # # # # # ## # # # # ## # ##
// ### ## # ## ### ### ### ## ## # ### ## # # # # # # # # ## ### ###
/**
* Sorts Discord channels.
* @returns {Promise} A promise that resolves when the Discord channels are sorted.
*/
static async sortDiscordChannels() {
await Discord.positionChannel(0, Array.from(sixGuild.channels.filter((channel) => channel.name.startsWith("twitch-")).values()).sort((a, b) => a.name.localeCompare(b.name)));
}
// # # # # # # ## # ##
// # # # # # # # # #
// ### ## ### # # ### ## ### # # ## ## ## ## # ### ### ### ### ## #
// # # # ## # # # ## # ## # # # # # # # # # ## # # # # # # # # # # ## #
// ## ## # # # ## ## # ## # # # # ## # # # # # ## # # # # ## #
// # ## ## ## ### ## # ## ## ### ## ## ## # # # # # # # # ## ###
// ###
/**
* Get the voice channel the user is in.
* @param {DiscordJs.GuildMember} user The user to check.
* @returns {DiscordJs.VoiceChannel} The voice channel the user is in.
*/
static getUserVoiceChannel(user) {
return sixGuild.member(user).voiceChannel;
}
// # # # ## # ## # # # ### ### #
// # # # # # # # # # # # # #
// # ## ### ### # # # ## # ### # # ### ## ### ### # # # ###
// ### # # # # # # ## # # # # # # # # ## # ## # # # # # # # # #
// # # # # # # # # # # # # # # # # ## ## # # # # # # # #
// # ### # # ### ### ### ### ### ### ## ### ## # ### # ### ###
// #
/**
* Returns the Discord user in the guild by their Discord ID.
* @param {string} id The ID of the Discord user.
* @returns {DiscordJs.GuildMember} The Discord user.
*/
static findGuildUserById(id) {
return sixGuild.members.find((m) => m.id === id);
}
// # # # ## # ## ### # #
// # # # # # # # # # ## #
// # ## ### ### # ### ### ### ### ## # ### # # ## # ### # # ##
// ### # # # # # # # # # # # # # # # ## # # # # # # ## # # #### # ##
// # # # # # # # # # # # ## # # # # ## # # # # # # ## # ## # # ##
// # ### # # ### ## # # # # # # # # ## ### ### # # # # # # # ##
// #
/**
* Finds a Discord channel by its name.
* @param {string} name The name of the channel.
* @returns {DiscordJs.Channel} The Discord channel.
*/
static findChannelByName(name) {
return sixGuild.channels.find((c) => c.name === name);
}
// # # # ### ## ### # #
// # # # # # # # # ## #
// # ## ### ### # # ## # ## ### # # ## # ### # # ##
// ### # # # # # ### # # # # ## # # # # # ## # # #### # ##
// # # # # # # # # # # # ## # # # # # ## # ## # # ##
// # ### # # ### # # ## ### ## ### # # # # # # # ##
// #
/**
* Finds a Discord role by its name.
* @param {string} name The name of the role.
* @returns {DiscordJs.Role} The Discord Role.
*/
static findRoleByName(name) {
return sixGuild.roles.find((r) => r.name === name);
}
// # # ## #
// # # # # #
// ### ### ### # ### ### ## ### # # ## ###
// # # # # # # # # # # # ## # # #### # ## # #
// # ## # # # # # # # # ## # ## # # ## #
// # # ### ### ## ## # ## # # # # ## #
/**
* Adds a streamer to the auto hosting rotation.
* @param {string} name The name of the streamer.