This repository has been archived by the owner on Jul 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
bot-titlechange.js
1436 lines (1249 loc) · 43.2 KB
/
bot-titlechange.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";
const tmi = require("tmi.js");
const IORedis = require("ioredis");
const request = require("request-promise");
const storage = require("node-persist");
const AsyncLock = require("node-async-locks").AsyncLock;
const escapeStringRegexp = require("escape-string-regexp");
const config = require("./config");
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// use in array.filter() to ensure all values are unique
// https://stackoverflow.com/a/14438954
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
const knownCommands = [
events,
notifyme,
removeme,
subscribed,
title,
game,
islive,
help,
titlechangebot_help,
titlechangebothelp,
tcb_help,
tcbhelp,
bot,
titlechange_bot,
titlechangebot,
ping,
tcbping,
setData,
debugData,
tcbdebug,
tcbquit,
];
// the main data storage object.
// stores for each channel (key):
// "forsen": { "title": <title>, "game": <game>, "live": true/false, }
let currentData = {};
// only the events that have a configured format are supported by a channel.
function getChannelAvailableEvents(channelName) {
// available events for signing up for pings
const availableEvents = {
title: {
matcher: function (key, value) {
return key === "title";
},
hasValue: true,
description: "when the title changes",
},
game: {
matcher: function (key, value) {
return key === "game";
},
hasValue: true,
description: "when the game changes",
},
live: {
matcher: function (key, value) {
return key === "live" && value === true;
},
hasValue: false,
description: "when the streamer goes live",
},
offline: {
matcher: function (key, value) {
return key === "live" && value === false;
},
hasValue: false,
description: "when the streamer goes offline",
},
partner: {
matcher: function (key, value) {
return key === "partner" && value === true;
},
hasValue: false,
description: "when this streamer becomes partnered",
},
};
let returnObject = {};
Object.keys(availableEvents)
.filter(
(evName) => evName in config.enabledChannels[channelName]["formats"]
)
.forEach((evName) => (returnObject[evName] = availableEvents[evName]));
return returnObject;
}
function getListOfAvailableEvents(channelName) {
let eventArray = Object.keys(getChannelAvailableEvents(channelName));
eventArray.sort();
return eventArray.join(", ");
}
// print all events
async function events(channelName, context, params) {
let channelAvailableEvents = getChannelAvailableEvents(channelName);
let eventArray = Object.keys(channelAvailableEvents);
let allEventsString = eventArray
.sort()
.map(
(evName) => `${evName} (${channelAvailableEvents[evName].description})`
)
.join(", ");
await sendReply(
channelName,
context,
`Available events: ${allEventsString}. ` +
`Type "${config.commandPrefix}notifyme <event> [optional value]" to subscribe to an event!`
);
}
// requiredValue = null - any value
// requiredValue = "something" - only when new value contains this
// [ { channel: "forsen", user: "n_888", event: "title", requiredValue: null } ]
let userSubscriptions = [];
async function refreshData() {
for (let [channelName, channelConfig] of Object.entries(
config.enabledChannels
)) {
let channelId = channelConfig["id"];
// title, game updates
await doChannelAPIUpdates(channelName, channelId);
// live/offline status
await doStreamAPIUpdates(channelName, channelId);
}
}
// do all the updates possible by calling the /channels/:channelId API endpoint
async function doChannelAPIUpdates(channelName, channelId) {
let options = {
method: "GET",
json: true,
uri: "https://api.twitch.tv/kraken/channels/" + channelId,
headers: {
"Client-ID": config.krakenClientId,
Accept: "application/vnd.twitchtv.v5+json",
},
};
try {
let response = await request(options);
await updateChannelProperty(channelName, "title", response["status"]);
await updateChannelProperty(channelName, "game", response["game"]);
await updateChannelProperty(channelName, "partner", response["partner"]);
await updateChannelProperty(channelName, "id", response["_id"]);
} catch (error) {
if (error.response && error.response.statusCode !== 422) {
console.log(error);
}
await updateChannelProperty(channelName, "title", null);
await updateChannelProperty(channelName, "game", null);
await updateChannelProperty(channelName, "partner", null);
await updateChannelProperty(channelName, "id", null);
}
}
// do all the updates possible by calling the /streams/:channelId API endpoint
async function doStreamAPIUpdates(channelName, channelId) {
let options = {
method: "GET",
json: true,
uri: "https://api.twitch.tv/kraken/streams/" + channelId,
headers: {
"Client-ID": config.krakenClientId,
Accept: "application/vnd.twitchtv.v5+json",
},
};
try {
let response = await request(options);
if (response["stream"] !== null) {
await updateChannelProperty(channelName, "live", true);
} else {
await updateChannelProperty(channelName, "live", false);
}
} catch (error) {
if (error.response && error.response.statusCode !== 422) {
console.log(error);
}
await updateChannelProperty(channelName, "live", null);
}
}
async function updateChannelProperty(channel, key, value) {
let channelData = currentData[channel];
if (typeof channelData === "undefined") {
// initialize channel
channelData = {};
currentData[channel] = channelData;
}
let oldValue = channelData[key];
// If this key doesnt exist, set the value either way (even if it is null).
if (typeof channelData[key] === "undefined") {
channelData[key] = value;
return;
}
// If this key already exists, set the value only if the new value is not null/undefined.
if (typeof value !== "undefined" && value !== null) {
channelData[key] = value;
}
// if this was an actual "update", send the notification message to that channel
// and ping all users that signed up for being pinged.
// oldValue actually needs to be something valid, otherwise
// this is the first run that populates the table
if (oldValue != null && value != null && oldValue !== value) {
await runChangeNotify(channel, key, value);
}
}
const valueRegex = /\$VALUE\$/g;
// in reality the API can sometimes be indecisive at boundary points (e.g. when channel goes offline, it
// can return live -> live -> live -> (channel goes offline) -> offline -> live (causes wrong notify) -> offline
// remember the last dates when notifies were sent, and dont send too fast if key changes again
// this array is indexed by the value key, e.g. "title", "game", "live" (and not "offline")
const lastNotifies = {};
// in milliseconds, for each channel and each value
// 5 minutes, because the live -> offline transition is very inconsistent with the API
const notifyCooldown = 5 * 60 * 1000;
async function runChangeNotify(channelName, key, value) {
console.log(`notify: ${channelName} ${key} ${value}`);
//
// notify cooldown
//
let channelLastNotifies = lastNotifies[channelName];
if (typeof channelLastNotifies === "undefined") {
channelLastNotifies = {};
lastNotifies[channelName] = channelLastNotifies;
}
let lastNotified = channelLastNotifies[key];
if (typeof lastNotified === "undefined") {
lastNotified = 0;
}
let timeNow = Date.now();
let timeSinceLastNotify = timeNow - lastNotified;
if (key === "live" && timeSinceLastNotify <= notifyCooldown) {
// notify wasn't run, don't save the time.
console.log(`lastNotified: ${lastNotified}`);
console.log(`timeSinceLastNotify: ${timeSinceLastNotify}`);
console.log("skipping notify due to cooldown");
return;
}
channelLastNotifies[key] = timeNow;
let channelData = config.enabledChannels[channelName];
let formats = channelData["formats"];
let protection = channelData["protection"] || {};
// do we have a char limit (for whole messages)? otherwise use default limit of globalLengthLimit.
let lengthLimit = protection["lengthLimit"] || config.globalLengthLimit;
// leave two characters for chatterino alternate character (this is added in the sendMessageUnsafe function later)
lengthLimit -= 2;
// do we have a value length limit? (e.g. length limit for the title/game/etc. field)?
// If not use 1/4 of the length limit.
let valueLengthLimit = protection["valueLengthLimit"] || lengthLimit / 4;
// clip value length
if (value.length > valueLengthLimit) {
// shorten value to length - 1, to leave one char space for the ellipsis character
value = value.substring(0, valueLengthLimit - 1);
value += "…";
}
let offlineChatOnly = protection["offlineOnly"];
if (typeof offlineChatOnly === "undefined") {
offlineChatOnly = false;
}
// this is the channel all notify messages for this event are sent to.
// this can be different for offline-only channels that are currently live.
let sendChannel = channelName;
let eventFormatPrefix = "";
if (offlineChatOnly && key !== "live" && currentData[channelName]["live"]) {
sendChannel = config.onlinePrintChannel;
eventFormatPrefix = `[via #${channelName}] `;
console.log(
`Channel #${channelName} is currently live and change occurred, printing notify to #${sendChannel}`
);
}
let noPingMode = protection["noPingMode"];
if (noPingMode == null) {
noPingMode = false;
}
//
// now do the pings.
//
for (let [eventName, eventConfig] of Object.entries(
getChannelAvailableEvents(channelName)
)) {
if (!eventConfig["matcher"](key, value)) {
// event does not match.
continue;
}
let usersToPing = userSubscriptions
.filter((sub) => sub.channel === channelName)
.filter((sub) => sub.event === eventName)
.filter((sub) => {
if (!eventConfig.hasValue) {
return true;
}
return (
String(value)
.toUpperCase()
.indexOf(sub.requiredValue.toUpperCase()) >= 0
);
})
.filter(onlyUnique)
.map((sub) => sub.user);
// get the message format
console.log(`eventName: ${eventName}`);
let eventFormat = formats[eventName];
if (key === "live" && !value) {
eventFormat = formats["offline"];
}
// prepend [via #forsen] if printing to the offline-protection channel
eventFormat = eventFormatPrefix + eventFormat;
eventFormat = ".me " + eventFormat;
// substitute $VALUE$ with the actual value
eventFormat = eventFormat.replace(valueRegex, value);
// send this notify WITHOUT any pings, just one message. return immediately.
if (noPingMode) {
await sendMessage(sendChannel, eventFormat);
return;
}
if (usersToPing.length <= 0) {
// no users signed up for this event, skip
continue;
}
let buildNotifyMsg = function (usersArray) {
let msg = eventFormat;
msg += usersArray.join(" ");
msg = msg.trim();
return msg;
};
// join into individual messages, each up to >lengthLimit< characters long.
// eventFormat is the message prefix.
let messagesToPrint = [];
let currentStartIndex = 0;
// start with one user.
for (let i = 1; i <= usersToPing.length; i++) {
let thisIterationUsers = usersToPing.slice(currentStartIndex, i);
// note that this will technically be out of bounds for the last iteration,
// but JS accepts the too-big end index and just returns the same array as
// thisIterationUsers.
let nextIterationUsers = usersToPing.slice(currentStartIndex, i + 1);
// build message for this iteration
let thisIterationMessage = buildNotifyMsg(thisIterationUsers);
let nextIterationMessage = buildNotifyMsg(nextIterationUsers);
if (nextIterationMessage.length > lengthLimit) {
messagesToPrint.push(thisIterationMessage);
// begin again with one user.
currentStartIndex = i;
}
// if last iteration.
if (thisIterationUsers.length === nextIterationUsers.length) {
messagesToPrint.push(thisIterationMessage);
}
}
if (eventName === "live") {
// print the MOTD
let channelMotd = channelMotds[channelName];
if (channelMotd == null) {
channelMotd = defaultMotd;
}
if (channelMotd != null) {
messagesToPrint.push(channelMotd);
}
}
for (let msgToPrint of messagesToPrint) {
await sendMessage(sendChannel, msgToPrint);
}
}
}
async function saveUserSubscriptions(override = false) {
if (!override) {
let previous = (await storage.getItem("userSubscriptions")) || [];
let removed = previous.length - userSubscriptions.length;
if (removed > 4) {
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
console.error(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX TRIED TO REMOVE TOO MANY SUBS, REFUSING"
);
userSubscriptions = previous;
return;
}
}
await storage.setItem("userSubscriptions", userSubscriptions);
}
async function loadUserSubscriptions() {
let loadedObj = await storage.getItem("userSubscriptions");
if (typeof loadedObj !== "undefined") {
userSubscriptions = loadedObj;
}
}
// the motd is printed after the live notify in a channel as a separate message
let defaultMotd = "";
let channelMotds = {};
async function saveMotd() {
await storage.setItem("defaultMotd", defaultMotd);
await storage.setItem("channelMotds", channelMotds);
}
async function loadMotd() {
let loadedDefaultMotd = await storage.getItem("defaultMotd");
if (typeof loadedDefaultMotd !== "undefined") {
defaultMotd = loadedDefaultMotd;
}
let loadedChannelMotds = await storage.getItem("channelMotds");
if (typeof loadedChannelMotds !== "undefined") {
channelMotds = loadedChannelMotds;
}
}
// call this as the owner with !tcbdebug importPingLists()
async function importPingLists() {
if (userSubscriptions.length > 0) {
return "userSubscriptions array is not empty!";
}
let pingLists = await storage.getItem("pingLists");
// format:
// "forsen": { "title": ['randers00', 'n_888'], "game": [], "live": ['randers00', 'n_888'] }
if (typeof pingLists === "undefined") {
return "No pingLists object found in persistent storage";
}
for (let [channelName, channelPingLists] of Object.entries(pingLists)) {
for (let [eventName, userList] of Object.entries(channelPingLists)) {
for (let username of userList) {
userSubscriptions.push({
channel: channelName,
user: username,
event: eventName,
requiredValue: "",
});
}
}
}
return `Imported ${userSubscriptions.length} subscriptions!`;
}
async function notifyme(channelName, context, params) {
if (params.length < 1) {
await sendReply(
channelName,
context,
`Please specify an event to subscribe to. ` +
`The following events are available: ${getListOfAvailableEvents(
channelName
)}`
);
return;
}
let eventName = params[0];
eventName = eventName.toLowerCase();
if (!(eventName in getChannelAvailableEvents(channelName))) {
await sendReply(
channelName,
context,
`The given event name is not valid. ` +
`The following events are available: ${getListOfAvailableEvents(
channelName
)}`
);
return;
}
let requiredValue = params.slice(1).join(" ");
let eventConfig = getChannelAvailableEvents(channelName)[eventName];
if (!eventConfig.hasValue && requiredValue.length > 0) {
// requesting specific value when this is not an event that takes on a value. (e.g. live/offline)
requiredValue = "";
}
// check if requesting generic sub, and user has specific subs
let specificSubs = userSubscriptions
.filter((sub) => sub.channel === channelName)
.filter((sub) => sub.user === context["username"])
.filter((sub) => sub.event === eventName)
.filter((sub) => sub.requiredValue.length > 0);
if (requiredValue.length <= 0 && specificSubs.length > 0) {
// user is requesting generic sub when they have specific ones on record.
// remove all their subs and replace them with one generic one.
let toRemove = userSubscriptions
.filter((sub) => sub.channel === channelName)
.filter((sub) => sub.user === context["username"])
.filter((sub) => sub.event === eventName);
userSubscriptions = userSubscriptions.filter(
(sub) => !toRemove.includes(sub)
);
userSubscriptions.push({
channel: channelName,
user: context["username"],
event: eventName,
requiredValue: requiredValue,
});
await sendReply(
channelName,
context,
`Successfully subscribed you to the event ` +
`"${eventName}". You previously had ${toRemove.length} subscription(s) for this event that were set to only match specific values. ` +
`These subscriptions have been removed and you will now be notified regardless of the value. SeemsGood`
);
return;
}
// check if a general subscription or this exact sub already exists
let duplicateSubs = userSubscriptions
.filter((sub) => sub.channel === channelName)
.filter((sub) => sub.user === context["username"])
.filter((sub) => sub.event === eventName)
.filter(
(sub) =>
sub.requiredValue.length <= 0 ||
sub.requiredValue.toUpperCase() === requiredValue.toUpperCase()
);
if (duplicateSubs.length > 0) {
if (duplicateSubs.length > 2) {
// this shouldnt (tm) happen because it would mean the user has a general match-all subscription
// (requiredValue="") and a specific one. This method aims to prevent that.
console.warn(
`User has two duplicates for eventName=${eventName} with requiredValue=${requiredValue}, ` +
`found these duplicates: ${JSON.stringify(duplicateSubs)}`
);
}
// following combinations are possible:
// inputRequiredValue="" duplicateRequiredValue="" (duplicate generic sub)
// inputRequiredValue="something" duplicateRequiredValue="" (specific sub when generic one exists)
// this is not possible: inputRequiredValue="" duplicateRequiredValue="something" (handled previously)
// inputRequiredValue="something" duplicateRequiredValue="something" (duplicate specific sub)
let duplicateSub = duplicateSubs[0];
if (duplicateSub.requiredValue.length <= 0) {
// user is trying to add either duplicate generic subscription, or a specific one when they have a generic one.
if (requiredValue.length > 0) {
await sendReply(
channelName,
context,
`You already have a subscription for the ` +
`event "${eventName}" that matches *all* values. Should you want to only get pinged on specific values, ` +
`type "${config.commandPrefix}removeme ${eventName}" and run this command again.`
);
} else {
await sendReply(
channelName,
context,
`You already have a subscription for the ` +
`event "${eventName}". If you want to unsubscribe, type "${config.commandPrefix}removeme ${eventName}".`
);
}
return;
} else {
// user is trying to add specific subscription, and already has this exact specific subscription.
await sendReply(
channelName,
context,
`You already have a subscription for the event ` +
`"${eventName}" with the value "${requiredValue}".`
);
return;
}
}
// by now: user does not have a duplicating subscription on record
// (or a generic one when requesting a specific one)
// we can add this subscription now without issue.
userSubscriptions.push({
channel: channelName,
user: context["username"],
event: eventName,
requiredValue: requiredValue,
});
await saveUserSubscriptions();
if (requiredValue.length <= 0) {
// new generic sub
await sendReply(
channelName,
context,
`I will now ping you in chat when ${eventConfig.description}!`
);
} else {
// new specific sub
await sendReply(
channelName,
context,
`I will now ping you in chat when ${eventConfig.description}, but only when the value contains ` +
`"${requiredValue}"!`
);
}
}
async function removeme(channelName, context, params) {
if (params.length < 1) {
await sendReply(
channelName,
context,
`Please specify an event to unsubscribe from. ` +
`The following events are available: ${getListOfAvailableEvents(
channelName
)}`
);
return;
}
let eventName = params[0];
eventName = eventName.toLowerCase();
if (!(eventName in getChannelAvailableEvents(channelName))) {
await sendReply(
channelName,
context,
`The given event name is not valid. ` +
`The following events are available: ${getListOfAvailableEvents(
channelName
)}. You can view all your subscriptions `
);
return;
}
let requiredValue = params.slice(1).join(" ");
let eventConfig = getChannelAvailableEvents(channelName)[eventName];
if (!eventConfig.hasValue && requiredValue.length > 0) {
// requesting specific value when this is not an event that takes on a value. (e.g. live/offline)
requiredValue = "";
}
// if requiredValue is empty, remove the user from all subscriptions to this event.
// if requiredValue is non-empty, only remove the subscription that matches that value.
let toRemove = userSubscriptions
.filter((sub) => sub.channel === channelName)
.filter((sub) => sub.user === context["username"])
.filter((sub) => sub.event === eventName)
.filter((sub) => {
if (requiredValue.length <= 0) {
// no value passed to the function, match all
return true;
}
// value passed, match only on case-insensitive match
return requiredValue.toUpperCase() === sub.requiredValue.toUpperCase();
});
if (toRemove.length < 1) {
if (requiredValue.length <= 0) {
// user was not subbed to this event at all
await sendReply(
channelName,
context,
`You are not subscribed to the event "${eventName}". You can view all your ` +
`subscriptions with "${config.commandPrefix}subscribed".`
);
} else {
// did not match that requiredValue
await sendReply(
channelName,
context,
`You are not subscribed to the event "${eventName}" with the value "${requiredValue}" o_O ` +
`You can view all your subscriptions with "${config.commandPrefix}subscribed".`
);
}
return;
}
userSubscriptions = userSubscriptions.filter(
(sub) => !toRemove.includes(sub)
);
await saveUserSubscriptions();
await sendReply(
channelName,
context,
`Successfully unsubscribed you from the event "${eventName}" ` +
`${requiredValue.length > 0 ? `for the value "${requiredValue}" ` : ""}` +
`(removed ${toRemove.length} ` +
`subscription${toRemove.length === 1 ? "" : "s"})`
);
}
async function subscribed(channelName, context, params) {
let activeSubscriptions = userSubscriptions
.filter((sub) => sub.channel === channelName)
.filter((sub) => sub.user === context["username"]);
let eventNames = activeSubscriptions
.map((sub) => sub.event)
.filter(onlyUnique);
let msgParts = [];
for (let eventName of eventNames) {
let eventConfig = getChannelAvailableEvents(channelName)[eventName];
if (typeof eventConfig === "undefined") {
continue;
}
let eventSubscriptions = activeSubscriptions.filter(
(sub) => sub.event === eventName
);
if (!eventConfig.hasValue) {
// the user has a subscription for this event, but this is a event type
// without a value so only possible situation is that the user has exactly one generic sub to this event.
msgParts.push(`${eventName} (${eventConfig.description})`);
continue;
}
// this is an event that has a value (game/title for example), and the user has at least 1 sub to this event.
if (
eventSubscriptions.length === 1 &&
eventSubscriptions[0].requiredValue.length <= 0
) {
// generic sub
msgParts.push(`${eventName} (${eventConfig.description})`);
continue;
}
// user has 1 or more specific subs
let requiredValues = [];
for (let sub of eventSubscriptions) {
requiredValues.push(`"${sub.requiredValue}"`);
}
msgParts.push(
`${eventName} (${
eventConfig.description
}) for the values ${requiredValues.join(", ")}`
);
}
if (msgParts.length < 1) {
await sendReply(
channelName,
context,
`You are not subscribed to any events. Use ${config.commandPrefix}notifyme <event> [optional value] to subscribe. ` +
`Valid events are: ${getListOfAvailableEvents(channelName)}`
);
return;
}
await sendReply(
channelName,
context,
`Your subscriptions in this channel: ${msgParts.join(", ")}`
);
}
async function title(channelName, context, params) {
if (!(channelName in config.enabledChannels)) {
await sendReply(
channelName,
context,
"Error: This channel is not enabled."
);
return;
}
await sendReply(
channelName,
context,
`Current title: ${currentData[channelName]["title"]}`
);
}
async function game(channelName, context, params) {
if (!(channelName in config.enabledChannels)) {
await sendReply(
channelName,
context,
"Error: This channel is not enabled."
);
return;
}
await sendReply(
channelName,
context,
`Current game: ${currentData[channelName]["game"]}`
);
}
async function islive(channelName, context, params) {
if (!(channelName in config.enabledChannels)) {
await sendReply(
channelName,
context,
"Error: This channel is not enabled."
);
return;
}
await sendReply(
channelName,
context,
`Current live status: ${
currentData[channelName]["live"]
? "The channel is live!"
: "The channel is offline :("
}`
);
}
async function help(channelName, context, params) {
if (!(channelName in config.enabledChannels)) {
await sendReply(
channelName,
context,
"Error: This channel is not enabled."
);
return;
}
await sendReply(
channelName,
context,
`Available commands: ${config.commandPrefix}notifyme <event> [optional value], ` +
`${config.commandPrefix}removeme <event> [optional value], ${config.commandPrefix}subscribed, ${config.commandPrefix}events, ${config.commandPrefix}title, ${config.commandPrefix}game, ${config.commandPrefix}islive, ${config.commandPrefix}help`
);
}
async function titlechangebot_help(channelName, context, params) {
await help(channelName, context, params);
}
async function titlechangebothelp(channelName, context, params) {
await help(channelName, context, params);
}
async function tcb_help(channelName, context, params) {
await help(channelName, context, params);
}
async function tcbhelp(channelName, context, params) {
await help(channelName, context, params);
}
async function bot(channelName, context, params) {
if (!(channelName in config.enabledChannels)) {
await sendReply(