-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathruncommand.js
1700 lines (1645 loc) · 82.1 KB
/
runcommand.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
const request = require("request");
const fs = require("fs");
const Entities = require("html-entities").XmlEntities;
const jimp = require("jimp");
const botcore = require("messenger-botcore");
const config = require("./config");
const utils = require("./utils");
const cutils = require("./configutils");
const commands = require("./commands");
const entities = new Entities();
let credentials;
try {
// Login creds from local dir
credentials = require("./credentials");
} catch (e) {
// Deployed to Heroku or config file is missing
credentials = process.env;
}
// Spotify API (requires credentials)
const spotify = new (require("spotify-web-api-node"))({
"clientId": credentials.SPOTIFY_CLIENTID,
"clientSecret": credentials.SPOTIFY_CLIENTSECRET
}); // Spotify API
// Stores user commands (accessible via trigger word set in config.js)
// Command order indicates (and determines) precedence
const funcs = {
"help": (threadId, cmatch) => { // Check help first to avoid command conflicts
const cats = commands.categories;
let input;
if (cmatch[1]) {
input = cmatch[1].trim().toLowerCase();
}
if (input && input.length > 0) {
// Give details of specific command or category
const cat = utils.getHelpCategory(input);
const entry = utils.getHelpEntry(input);
if (cat) {
const name = cat.display_name;
const desc = cat.description;
const commands = cat.commands;
let mess = `_${name} commands: ${desc}_\n\n`;
for (let c in commands) {
if (commands.hasOwnProperty(c)) {
const curEntry = commands[c];
if (curEntry.display_names.length > 0) { // Don't display if no display names (secret command)
// Only display short description if one exists
mess += `${curEntry.syntax}${curEntry.short_description ? `: ${curEntry.short_description}` : ""}${curEntry.sudo ? " [OWNER]" : ""}\n`;
mess += "------------------\n"; // Suffix for separating commands
}
}
}
mess += `Contact ${config.owner.names.long} with any questions, or use "${config.trigger} bug" to report bugs directly.\n\nTip: for more detailed descriptions, use "${config.trigger} help {command}"`;
utils.sendMessage(mess, threadId);
} else if (entry) {
const info = entry.entry;
const example = {}; // Fill example data (sometimes array; sometimes string)
if (Array.isArray(info.example)) {
example.header = "Examples:\n";
example.body = info.example.map(e => {
return `${config.trigger} ${e}`; // Add trigger to example
}).join("\n");
} else if (info.example.length > 0) {
example.header = "Example: ";
example.body = `${config.trigger} ${info.example}`;
}
const helpMsg = `Entry for command "${info.pretty_name}":\n${info.description}\n\nSyntax: ${config.trigger} ${info.syntax}${example.header ? `\n\n${example.header}${example.body}` : ""}`;
const addenda = `${info.attachments ? "\n\n(This command accepts attachments)" : ""}${info.sudo ? "\n\n(This command requires owner privileges)" : ""}${info.experimental ? "\n\n(This command is experimental)" : ""}`;
utils.getStats(entry.key, false, (err, stats) => {
if (err) { // Couldn't retrieve stats; just show help message
utils.sendMessage(`${helpMsg}${addenda}`, threadId);
} else {
const perc = (((stats.count * 1.0) / stats.total) * 100) || 0;
utils.sendMessage(`${helpMsg}\n\nThis command has been used ${stats.count} ${stats.count == 1 ? "time" : "times"}, representing ${perc.toFixed(3)}% of all invocations.${addenda}`, threadId);
}
});
} else {
utils.sendError(`Help entry not found for "${input}"`, threadId);
}
} else {
// No command passed; give overview of categories
let mess = `Quick Help for ${config.bot.names.short || config.bot.names.long}\n\nSelect a category from below with "${config.trigger} help {category}"\n\n`;
for (let c in cats) {
if (cats.hasOwnProperty(c)) {
const cat = cats[c];
if (cat.display_name) { // Don't display hidden categories
mess += `*${cat.display_name}*: ${cat.description}\n`;
}
}
}
utils.sendMessage(mess, threadId);
}
},
"stats": (threadId, cmatch, groupInfo) => {
const command = cmatch[1];
utils.getStats(command, true, () => {
let input;
if (cmatch[1]) {
input = cmatch[1].trim().toLowerCase();
}
if (input && input.length > 0) {
// Give details of specific command
const entry = utils.getHelpEntry(input);
if (entry) {
const key = entry.key;
const info = entry.entry;
utils.getStats(key, true, (err, stats) => {
if (!err) {
stats = utils.getComputedStats(stats);
let m = `'${info.pretty_name}' has been used ${stats.count} ${stats.count == 1 ? "time" : "times"} out of a total of ${stats.total} ${stats.total == 1 ? "call" : "calls"}, representing ${stats.usage.perc.toFixed(3)}% of all bot invocations.`;
m += `\n\nIt was used ${stats.usage.day} ${stats.usage.day == 1 ? "time" : "times"} within the last day and ${stats.usage.month} ${stats.usage.month == 1 ? "time" : "times"} within the last month.`;
const user = utils.getHighestUser(stats.record);
if (user) { // Found a user with highest usage
const name = groupInfo.names[user] || "not in this chat";
m += `\n\nIts most prolific user is ${name}.`;
}
utils.sendMessage(m, threadId);
}
});
} else {
utils.sendError(`Entry not found for ${input}`, threadId);
}
} else {
// No command passed; show all
utils.getAllStats((success, data) => {
if (!success) {
console.log("Failed to retrieve all stats");
}
for (let i = 0; i < data.length; i++) {
data[i].stats = utils.getComputedStats(data[i].stats); // Get usage stats for sorting
}
data = data.sort((a, b) => {
return (b.stats.usage.perc - a.stats.usage.perc); // Sort greatest to least
});
let msg = "Command: % of total usage | # today | # this month\n";
data.forEach(co => {
msg += `\n${co.pretty_name}: ${co.stats.usage.perc.toFixed(3)}% | ${co.stats.usage.day} | ${co.stats.usage.month}`;
});
utils.sendMessage(msg, threadId);
});
}
});
},
"psa": (_, cmatch) => {
utils.sendToAll(`"${cmatch[1]}"\n\nThis has been a public service announcement from ${config.owner.names.short}.`);
},
"bug": (_, cmatch, groupInfo, __, fromUserId) => {
const msg = cmatch[1] || "none";
if (msg.toLowerCase().trim() == "thread") {
utils.sendMessage(`Thread ID: ${groupInfo.threadId}`, groupInfo.threadId);
} else {
utils.sendMessage(`-------BUG-------\nMessage: ${msg}\nSender: ${groupInfo.names[fromUserId]}\nTime: ${utils.getTimeString()} (${utils.getDateString()})\nGroup: ${groupInfo.name}\nID: ${groupInfo.threadId}\nInfo: ${JSON.stringify(groupInfo)}`, config.owner.id, err => {
if (!err) {
if (groupInfo.isGroup && !cutils.contains(config.owner.id, groupInfo.members)) { // If is a group and owner is not in it, add
utils.sendMessage(`Report sent. Adding ${config.owner.names.short} to the chat for debugging purposes...`, groupInfo.threadId, () => {
utils.addUser(config.owner.id, groupInfo, false);
});
} else { // Otherwise, just send confirmation
utils.sendMessage(`Report sent to ${config.owner.names.short}.`, groupInfo.threadId);
}
} else {
utils.sendMessage(`Report could not be sent; please message ${config.owner.names.short} directly.`, groupInfo.threadId);
}
});
}
},
"kick": (_, cmatch, groupInfo, __, senderId) => {
const user = cmatch[1].toLowerCase();
const optTime = cmatch[2] ? parseInt(cmatch[2]) : undefined;
try {
// Make sure already in group
if (groupInfo.members[user]) {
// Kick with optional time specified in call only if specified in command
utils.kick(groupInfo.members[user], senderId, groupInfo, optTime);
} else {
utils.sendError(`Couldn't find user "${cmatch[1]}".`, groupInfo.threadId);
}
} catch (e) {
utils.sendError(e, groupInfo.threadId);
}
},
"xkcd": (threadId, cmatch) => { // Check before regular searches to prevent collisions
if (cmatch[1]) { // Parameter specified
const query = cmatch[2];
const param = cmatch[1].split(query).join("").trim(); // Param = 1st match - 2nd
if (query && param == "search") {
// Perform search using Google Custom Search API (provide API key / custom engine in config.js)
const url = `https://www.googleapis.com/customsearch/v1?key=${config.xkcd.key}&cx=${config.xkcd.engine}&q=${encodeURIComponent(query)}`;
request(url, (err, res, body) => {
if (!err && res.statusCode == 200) {
const results = JSON.parse(body).items;
if (results.length > 0) {
utils.sendMessage({
"url": results[0].formattedUrl // Best match
}, threadId);
} else {
utils.sendError("No results found", threadId);
}
} else {
console.log(err);
}
});
} else if (param == "new") { // Get most recent (but send as permalink for future reference)
request("http://xkcd.com/info.0.json", (err, res, body) => {
if (!err && res.statusCode == 200) {
const num = parseInt(JSON.parse(body).num); // Number of most recent xkcd
utils.sendMessage({
"url": `http://xkcd.com/${num}`
}, threadId);
} else {
// Just send to homepage for newest as backup
utils.sendMessage({
"url": "http://xkcd.com/"
}, threadId);
}
});
} else if (param) { // If param != search or new, it should be either a number or valid sub-URL for xkcd.com
utils.sendMessage({
"url": `http://xkcd.com/${param}`
}, threadId);
}
} else { // No parameter passed; send random xkcd
// Get info of most current xkcd to find out the number of existing xkcd (i.e. the rand ceiling)
request("http://xkcd.com/info.0.json", (err, res, body) => {
if (!err && res.statusCode == 200) {
const num = parseInt(JSON.parse(body).num); // Number of most recent xkcd
const randxkcd = Math.floor(Math.random() * num) + 1;
utils.sendMessage({
"url": `http://xkcd.com/${randxkcd}`
}, threadId);
}
});
}
},
"wiki": (threadId, cmatch) => {
const query = cmatch[1];
// Perform search using Google Custom Search API (provide API key / custom engine in config.js)
const url = `https://www.googleapis.com/customsearch/v1?key=${config.wiki.key}&cx=${config.wiki.engine}&q=${encodeURIComponent(query)}`;
request(url, (err, res, body) => {
if (!err && res.statusCode == 200) {
const results = JSON.parse(body).items;
if (results.length > 0) {
utils.sendMessage({
"url": results[0].formattedUrl // Best match
}, threadId);
} else {
utils.sendError("No results found.", threadId);
}
} else {
console.log(err);
}
});
},
"spotsearch": (threadId, cmatch) => {
utils.loginSpotify(spotify, err => {
if (!err) {
const query = cmatch[2];
if (cmatch[1].toLowerCase() == "artist") {
// Artist search
spotify.searchArtists(query, {}, (err, data) => {
if (!err && data.body) {
const bestMatch = data.body.artists.items[0];
const id = bestMatch.id;
if (id) {
spotify.getArtistTopTracks(id, "US", (err, data) => {
if (!err) {
const tracks = data.body.tracks;
const link = bestMatch.external_urls.spotify;
const image = bestMatch.images[0];
const popularity = bestMatch.popularity;
let message = `Best match: ${bestMatch.name}\nPopularity: ${popularity}%\n\nTop tracks:\n`;
for (let i = 0; i < config.spotifySearchLimit; i++) {
if (tracks[i]) {
message += `${tracks[i].name}${tracks[i].explicit ? " (Explicit)" : ""} (from ${tracks[i].album.name})${(i != config.spotifySearchLimit - 1) ? "\n" : ""}`;
}
}
if (image) {
// Send image of artist
utils.sendFilesFromUrl(image, threadId, message);
} else if (link) {
// Just send link
utils.sendMessage({
"body": message,
"url": bestMatch
}, threadId);
} else {
// Just send message
utils.sendMessage(message, threadId);
}
}
});
} else {
utils.sendError(`No results found for query "${query}"`, threadId);
}
} else {
utils.sendError(err, threadId);
}
});
} else {
// Song search
spotify.searchTracks(query, {}, (err, data) => {
if (!err) {
const bestMatch = data.body.tracks.items[0];
if (bestMatch) {
const message = `Best match: ${bestMatch.name} by ${utils.getArtists(bestMatch)} (from ${bestMatch.album.name})${bestMatch.explicit ? " (Explicit)" : ""}`;
const url = bestMatch.external_urls.spotify;
const preview = bestMatch.preview_url;
if (preview) {
// Upload preview
utils.sendFilesFromUrl(preview, threadId, message);
} else {
// Just send Spotify URL
utils.sendMessage({
"body": message,
"url": url
}, threadId);
}
} else {
utils.sendError(`No results found for query "${query}"`, threadId);
}
} else {
utils.sendError(err, threadId);
}
});
}
} else {
console.log(err);
}
});
},
"song": (threadId, cmatch, groupInfo) => {
utils.loginSpotify(spotify, err => {
if (!err) {
const user = cmatch[1] ? cmatch[1].toLowerCase() : null;
const userId = groupInfo.members[user];
const playlists = groupInfo.playlists;
const ids = Object.keys(playlists);
let playlist; // Determine which to use
if (playlists && ids.length > 0) { // At least 1 playlist stored
// Find random playlist in case one isn't specified or can't be found
const randPlaylist = playlists[ids[Math.floor(Math.random() * ids.length)]];
if (user && userId) {
// User specified
if (playlists[userId]) {
// User has a playlist
playlist = playlists[userId];
} else {
// User doesn't have playlist; use random one
playlist = randPlaylist;
utils.sendMessage(`User ${groupInfo.names[userId]} does not have a stored playlist; using ${playlist.name}'s instead.`, threadId);
}
} else {
// No playlist specified; grab random one from group
playlist = randPlaylist;
}
} else {
playlist = config.defaultPlaylist;
utils.sendMessage(`No playlists found for this group. To add one, use "${config.trigger} playlist" (see help for more info).\nFor now, using the default playlist.`, threadId);
}
spotify.getPlaylist(playlist.uri, {}, (err, data) => {
if (!err) {
const name = data.body.name;
const songs = data.body.tracks.items;
let track = songs[Math.floor(Math.random() * songs.length)].track;
let buffer = 0;
while (!track.preview_url && buffer < songs.length) { // Don't use songs without previews if possible
track = songs[Math.floor(Math.random() * songs.length)].track;
buffer++;
}
utils.sendMessage(`Grabbing a song from ${playlist.name}'s playlist, "${name}"...`, threadId);
const msg = `How about ${track.name} (from "${track.album.name}") by ${utils.getArtists(track)}${track.explicit ? " (Explicit)" : ""}?`;
if (track.preview_url) {
// Send preview MP3 to chat if exists
utils.sendFilesFromUrl(track.preview_url, threadId, msg);
} else {
utils.sendMessage({
"body": msg,
"url": track.external_urls.spotify // Should always exist
}, threadId);
}
} else {
console.log(err);
}
});
}
});
},
"playlist": (threadId, cmatch, groupInfo) => {
const playlists = groupInfo["playlists"];
if (cmatch[1]) { // User provided
const user = cmatch[1].toLowerCase();
const userId = groupInfo.members[user];
const name = groupInfo.names[userId];
if (cmatch[2]) { // Data provided
const newPlaylist = {
"name": name,
"id": userId,
"user": cmatch[3],
"uri": cmatch[4]
};
playlists[userId] = newPlaylist;
utils.setGroupProperty("playlists", playlists, groupInfo, err => {
if (!err) {
utils.loginSpotify(spotify, err => {
if (!err) {
spotify.getPlaylist(newPlaylist.uri, {}, (err, data) => {
if (!err) {
let message = `Playlist "${data.body.name}" added to the group. Here are some sample tracks:\n`;
const songs = data.body.tracks.items;
for (let i = 0; i < config.spotifySearchLimit; i++) {
if (songs[i]) {
let track = songs[i].track;
message += `– ${track.name}${track.explicit ? " (Explicit)" : ""} (from ${track.album.name})${(i != config.spotifySearchLimit - 1) ? "\n" : ""}`;
}
}
utils.sendMessage(message, threadId);
} else {
utils.sendError("Playlist couldn't be added; check the URI and make sure that you've set the playlist to public.", threadId);
}
});
} else {
console.log(err);
}
});
}
});
} else {
const playlist = groupInfo.playlists[userId];
if (playlist) {
utils.loginSpotify(spotify, err => {
if (!err) {
spotify.getPlaylist(playlist.uri, {}, (err, data) => {
if (!err) {
const pname = data.body.name;
const desc = entities.decode(data.body.description); // Can have HTML entities in text
const image = data.body.images[0];
const owner = data.body.owner;
const id = data.body.id;
const url = `https://open.spotify.com/playlist/${id}`;
const message = `${pname} by ${owner.display_name} (${owner.id}):\n\n"${desc}"\n\n${url}`;
if (image) {
utils.sendFilesFromUrl(image.url, threadId, message);
} else {
utils.sendMessage(message);
}
} else {
utils.sendError(`Couldn't find playlist with URI ${playlist.uri} for user ${playlist.name}`, threadId);
}
});
}
});
} else {
utils.sendError("Please include a Spotify URI to add a playlist (see help for more info)", threadId);
}
}
} else { // No user provided; just display current playlists
const pArr = Object.keys(playlists).map(p => {
return playlists[p];
});
if (pArr.length === 0) {
utils.sendMessage(`No playlists for this group. To add one, use "${config.trigger} playlist" (see help).`, threadId);
} else {
utils.loginSpotify(spotify, err => {
if (!err) {
let results = [];
const now = (new Date()).getTime();
let current = now;
// eslint-disable-next-line no-inner-declarations
function updateResults(value) {
results.push(value);
const success = (results.length == pArr.length);
current = (new Date()).getTime();
if (success || (current - now) >= config.asyncTimeout) {
const descs = results.map(p => {
return `"${p.name}" by ${p.user} (${p.length} songs)`;
});
utils.sendMessage(`Playlists for this group:\n— ${descs.join("\n— ")}`, threadId);
}
}
for (let i = 0; i < pArr.length; i++) {
spotify.getPlaylist(pArr[i].uri, {}, (err, data) => {
if (!err) {
updateResults({
"name": data.body.name,
"user": pArr[i].name,
"length": data.body.tracks.items.length
});
}
});
}
}
});
}
}
},
"pin": (threadId, cmatch, groupInfo, _, fromUserId, __, msgObj) => {
const name = cmatch[1];
const msg = cmatch[2];
const reply = msgObj.messageReply;
if (groupInfo.pinned) {
if (name == "delete") { // Delete pins
utils.deletePin(msg, groupInfo, threadId);
} else if (name == "rename") {
utils.renamePin(msg, groupInfo, threadId);
} else if (!msg && !reply) { // No new pin message; display pins
if (name) { // Requested specific pin
const pin = groupInfo.pinned[name];
if (pin) {
utils.sendMessage(utils.stringifyPin(pin), threadId);
} else {
utils.sendError("Couldn't find that pin.", threadId);
}
} else {
const pins = Object.keys(groupInfo.pinned);
if (pins.length > 0) {
if (pins.length == 1) { // Display pin if only one; otherwise list pins
const pin = pins[0];
utils.sendMessage(utils.stringifyPin(groupInfo.pinned[pin]), threadId);
} else {
let msg = pins.reduce((m, pin) => `${m}\n${pin}`, "Available pins:");
utils.sendMessage(msg, threadId);
}
} else {
utils.sendError("No pinned messages in this chat.", threadId);
}
}
} else { // Pin new message (or append to existing pin)
let pin = msg;
let sender = groupInfo.names[fromUserId];
let time = msgObj.timestamp;
if (reply) { // If reply provided, pin the reply instead
pin = reply.body;
sender = reply.senderID == config.bot.id ? config.bot.names.short :
(groupInfo.names[reply.senderID] || "Unknown");
time = reply.timestamp;
}
const date = new Date(parseInt(time));
if (name == "append") {
// -- Appending an existing pin --
// Need to extract existing pin name and content to append, which
// comes from different places in the case of a reply pin
// (regex designed to capture multiple lines)
const match = msg ? (msg.match(/(\S+)(?:\s|$)([\s\S]+)/m) || []) : [];
const existing = reply ? msg : match[1];
const content = reply ? pin : match[2];
if (existing && content) {
utils.appendPin(content, existing, date, sender, groupInfo);
} else {
utils.sendError("Please provide a pin and content to append to it.", threadId);
}
} else {
// Just a regular fresh pin creation (or overwrite)
if (pin && name) {
utils.addPin(pin, name, date, sender, groupInfo);
} else {
utils.sendError("Please provide a pin name and message to pin.", threadId);
}
}
}
} else {
console.log("Unable to pin message due to malformed db entry");
}
},
"tab": (threadId, cmatch, groupInfo) => {
const op = cmatch[1];
const amt = parseFloat(cmatch[2]) || 1;
const cur = groupInfo.tab || 0;
const numMembers = Object.keys(groupInfo.members).length;
if (!op) { // No operation – just display total
utils.sendMessage(`$${cur.toFixed(2)} ($${(cur / numMembers).toFixed(2)} per person in this group)`, threadId);
} else if (op == "split") {
const num = parseFloat(cmatch[2]) || numMembers;
utils.sendMessage(`$${cur.toFixed(2)}: $${(cur / num).toFixed(2)} per person for ${num} ${(num == 1) ? "person" : "people"}`, threadId);
} else if (op == "clear") { // Clear tab
utils.setGroupProperty("tab", 0, groupInfo, err => {
if (!err) { utils.sendMessage("Tab cleared.", threadId); }
});
} else {
const newTab = (op == "add") ? (cur + amt) : (cur - amt);
utils.setGroupProperty("tab", newTab, groupInfo, err => {
if (!err) { utils.sendMessage(`Tab updated to $${newTab.toFixed(2)}.`, threadId); }
});
}
},
"addsearch": (threadId, cmatch, groupInfo, api) => {
// Fields 1 & 3 are are for the command and the user, respectively
// Field 2 is for an optional number parameter specifying the number of search results
// for a search command (default is 1)
const user = cmatch[3];
const command = cmatch[1].split(" ")[0].toLowerCase(); // Strip opt parameter from match if present
try {
api.getUserID(user, (err, data) => {
if (!err) {
const filteredData = data.filter(m => m.type == "user");
const bestMatch = filteredData[0]; // Hopefully the right person
const numResults = parseInt(cmatch[2]) || 1; // Number of results to display
if (command == "search") { // Is a search command
// Output search results / propic
const descriptions = filteredData.slice(0, numResults).map((match, num) => {
return `${(num === 0) ? "Best match" : "Match " + (num + 1)}: ${match.name}\n${match.profileUrl}\nRank: ${match.score}\nUser ID: ${match.userID}`;
}).join("\n\n");
utils.sendFilesFromUrl(bestMatch.photoUrl, threadId, descriptions);
} else { // Is an add command
// Add best match to group and update log of member IDs
utils.addUser(bestMatch.userID, groupInfo);
}
} else {
if (err.error) {
// Fix typo in API error message
utils.sendError(`${err.error.replace("Bes", "Best")}`, threadId);
}
}
});
} catch (e) {
utils.sendError(`User ${user} not recognized`);
}
},
"order66": (threadId, _, groupInfo, __, senderId) => {
// Remove everyone from the chat for configurable amount of time (see config.js)
// Use stored threadId in case it changes later (very important)
if (groupInfo.isGroup) {
if (groupInfo.admins.includes(config.bot.id)) {
utils.sendMessage("I hate you all.", threadId);
setTimeout(() => {
utils.kickMultiple(Object.keys(groupInfo.names), senderId, groupInfo, config.order66Time, () => {
utils.sendMessage("Balance is restored to the Force.", threadId);
});
}, 2000); // Make sure people see the message (and impending doom)
} else {
utils.sendMessage("Not. Yet. The Senate will decide your fate.", threadId);
}
} else {
utils.sendMessage("Cannot execute Order 66 on a non-group chat. Safe for now, you are, Master Jedi.", threadId);
}
},
"color": (threadId, cmatch, groupInfo, api) => {
// Extract input and pull valid colors from API as well as current thread color
const apiColors = api.threadColors;
const hexToName = Object.keys(apiColors).reduce((obj, key) => { obj[apiColors[key]] = key; return obj; }, {}); // Flip the map
const ogColor = hexToName[groupInfo.color ? groupInfo.color.toLowerCase() : groupInfo.color]; // Will be null if no custom color set
if (cmatch[1]) {
const inputColor = cmatch[2];
const colorToSet = (inputColor.match(/rand(om)?/i)) ? utils.getRandomColor() : inputColor.toLowerCase();
// Construct a lowercased-key color dictionary to make input case insensitive
const colors = {};
for (let color in apiColors) {
if (apiColors.hasOwnProperty(color)) {
colors[color.toLowerCase()] = apiColors[color];
}
}
// Extract color values
const hexVals = Object.keys(colors).map(n => colors[n]);
const usableVal = hexVals.includes(colorToSet) ? colorToSet : colors[colorToSet];
if (usableVal === undefined) { // Explicit equality check b/c it might be null (i.e. MessengerBlue)
utils.sendError("Couldn't find this color. See help for accepted values.", threadId);
} else {
api.changeThreadColor(usableVal, threadId, err => {
if (!err) {
utils.sendMessage(`Last color was ${ogColor}.`, threadId);
}
});
}
} else { // No color requested – show current color
utils.sendMessage(`The current chat color is ${ogColor} (hex value: ${groupInfo.color ? groupInfo.color : "empty"}).`, threadId);
}
},
"hitlights": (threadId, _, groupInfo, api) => {
const ogColor = groupInfo.color || config.defaultColor; // Will be null if no custom color set
const delay = 500; // Delay between color changes (half second is a good default)
for (let i = 0; i < config.numColors; i++) { // Need block scoping for timeout
setTimeout(() => {
api.changeThreadColor(utils.getRandomColor(), threadId);
if (i == (config.numColors - 1)) { // Set back to original color on last
setTimeout(() => {
api.changeThreadColor(ogColor, threadId);
}, delay);
}
}, delay + (i * delay)); // Queue color changes
}
},
"clearnick": (threadId, cmatch, groupInfo, api) => {
const user = cmatch[1].toLowerCase();
api.changeNickname("", threadId, groupInfo.members[user]);
},
"setnick": (threadId, cmatch, groupInfo, api) => {
const user = cmatch[1].toLowerCase();
const newName = cmatch[2];
api.changeNickname(newName, threadId, groupInfo.members[user]);
},
"wakeup": (threadId, cmatch, groupInfo) => {
const user = cmatch[1].toLowerCase();
const members = groupInfo.members; // Save in case it changes
for (let i = 0; i < config.wakeUpTimes; i++) {
setTimeout(() => {
utils.sendMessage("Wake up", members[user]);
}, 500 + (500 * i));
}
utils.sendMessage(`Messaged ${user.substring(0, 1).toUpperCase()}${user.substring(1)} ${config.wakeUpTimes} times`, threadId);
},
"randmess": (threadId, _, __, api) => {
// Get thread length
api.getThreadInfo(threadId, (err, data) => {
if (!err) {
const count = data.messageCount; // Probably isn't that accurate
let randMessage = Math.floor(Math.random() * (count + 1));
api.getThreadHistory(threadId, count, null, (err, data) => {
if (err) {
utils.sendMessage("Error: Messages could not be loaded", threadId);
} else {
let m = data[randMessage];
while (!(m && m.body)) {
randMessage = Math.floor(Math.random() * (count + 1));
m = data[randMessage];
}
let b = m.body,
name = m.senderName,
time = new Date(m.timestamp);
utils.sendMessage(`${b} - ${name} (${time.toLocaleDateString()})`, threadId);
}
});
}
});
},
"alive": (_, __, groupInfo) => {
utils.sendGroupEmoji(groupInfo, "large"); // Send emoji and react to message in response
},
"emoji": (threadId, cmatch, groupInfo, api) => {
api.changeThreadEmoji(cmatch[1], threadId, err => {
if (err) {
// Set to default as backup if errors
api.changeThreadEmoji(groupInfo.emoji, threadId);
}
});
utils.updateGroupInfo(threadId); // Update emoji
},
"echo": (threadId, cmatch, _, api, fromUserId) => {
const command = cmatch[1].toLowerCase();
let message = `${cmatch[2]}`;
if (command == "echo") {
// Just an echo – repeat message
utils.sendMessage(message, threadId);
} else {
// Quote - use name
api.getUserInfo(fromUserId, (err, data) => {
if (!err) {
// Date formatting
const now = new Date();
const date = now.getDate();
const day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][now.getDay()];
const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][now.getMonth()];
const year = now.getFullYear();
message = `"${message}" – ${data[fromUserId].name}\n${day}, ${month} ${date}, ${year}`;
utils.sendMessage(message, threadId);
}
});
}
},
"ban": (threadId, cmatch, groupInfo) => {
const user = cmatch[2].toLowerCase();
const userId = groupInfo.members[user];
if (user) {
if (cmatch[1]) { // Unban
botcore.banned.removeUser(userId, success => {
if (success) {
utils.sendMessage(`Successfully unbanned ${groupInfo.names[userId]}.`, threadId);
} else {
utils.sendError(`Unable to unban ${groupInfo.names[userId]} because they're not currently banned.`, threadId);
}
});
} else { // Ban
botcore.banned.addUser(userId, success => {
if (success) {
utils.sendMessage(`Successfully banned ${groupInfo.names[userId]}.`, threadId);
} else {
utils.sendError(`Unable to ban ${groupInfo.names[userId]} because they've already been banned.`, threadId);
}
});
}
} else {
utils.sendError(`User ${user} not found`, threadId);
}
},
"vote": (threadId, cmatch, groupInfo) => {
const user = cmatch[2].toLowerCase();
const userId = groupInfo.members[user];
const user_cap = user.substring(0, 1).toUpperCase() + user.substring(1);
const getCallback = () => {
return (err, success, newScore) => {
if (success) {
utils.sendMessage(`${user_cap}'s current score is now ${newScore}.`, threadId);
} else {
utils.sendError("Score update failed.", threadId);
}
};
};
if (userId) {
if (cmatch[1] == ">") {
// Upvote
utils.updateScore(true, userId, getCallback(true));
} else {
// Downvote
utils.updateScore(false, userId, getCallback(false));
}
} else {
utils.sendError(`User ${user_cap} not found`, threadId);
}
},
"score": (threadId, cmatch, groupInfo) => {
if (cmatch[1]) { // Display scoreboard
utils.getAllScores(groupInfo, (success, scores) => {
if (success) {
scores = scores.sort((a, b) => {
return (b.score - a.score); // Sort greatest to least
});
let message = `Rankings for ${groupInfo.name}:`;
for (let i = 0; i < scores.length; i++) {
message += `\n${i + 1}. ${scores[i].name}: ${scores[i].score}`;
}
utils.sendMessage(message, threadId);
} else {
utils.sendError("Scores couldn't be retrieved for this group.", threadId);
}
});
} else if (cmatch[2]) {
const user = cmatch[2].toLowerCase();
const userId = groupInfo.members[user];
const user_cap = user.substring(0, 1).toUpperCase() + user.substring(1);
if (userId) {
const new_score = cmatch[3];
if (new_score || new_score == "0") { // Set to provided score if valid (0 is falsey)
utils.setScore(userId, new_score, (err, success) => {
if (success) {
utils.sendMessage(`${user_cap}'s score updated to ${new_score}.`, threadId);
} else {
utils.sendError(err, threadId);
}
});
} else { // No value provided; just display score
utils.getScore(`${userId}`, (err, val) => {
if (!err) {
const stored_score = val ? val.toString() : 0;
utils.sendMessage(`${user_cap}'s current score is ${stored_score}.`, threadId);
} else {
console.log(err);
}
});
}
} else {
utils.sendError(`User ${user_cap} not found`, threadId);
}
}
},
"restart": (threadId,) => {
utils.restart(() => {
utils.sendMessage("Restarting...", threadId);
});
},
"photo": (threadId, cmatch, groupInfo, _, __, attachments, messageObj) => {
// Set group photo to photo at provided URL
const url = cmatch[1];
if (url) {
// Use passed URL
utils.setGroupImageFromUrl(url, threadId, "Can't set group image for this chat.");
} else if (attachments && attachments[0]) {
if (attachments[0].type == "photo") {
// Use photo attachment
utils.setGroupImageFromUrl(attachments[0].largePreviewUrl, threadId, "Attachment is invalid.");
} else {
utils.sendError("This command only accepts photo attachments.", threadId);
}
} else if (messageObj.type == "message_reply") {
const msg = messageObj.messageReply;
if (msg.attachments && msg.attachments.length > 0) {
const photo = msg.attachments[0];
if (photo.type == "photo") {
utils.setGroupImageFromUrl(photo.largePreviewUrl, threadId, "Attachment is invalid.");
} else {
utils.sendError("This command only accepts photo attachments.", threadId);
}
} else {
utils.sendError("The message you're replying to must ahve a photo attachment.", threadId);
}
} else {
// If no photo provided, just display current group photo if it exists
if (groupInfo.image) {
utils.sendFilesFromUrl(groupInfo.image, threadId);
} else {
utils.sendError("This group currently has no photo set. To add one, use this command with either a valid image URL or a photo attachment.", threadId);
}
}
},
"poll": (threadId, cmatch, _, api) => {
const title = cmatch[1];
const opts = cmatch[2];
let optsObj = {};
if (opts) {
const items = opts.split(",");
for (let i = 0; i < items.length; i++) {
optsObj[items[i]] = false; // Initialize options to unselected in poll
}
}
api.createPoll(title, threadId, optsObj, err => { // I contributed this func to the API!
if (err) {
utils.sendError("Cannot create a poll in a non-group chat.", threadId);
}
});
},
"title": (threadId, cmatch, _, api) => {
const title = cmatch[1];
api.setTitle(title, threadId, err => {
if (err) {
utils.sendError("Cannot set title for non-group chats.", threadId);
}
});
},
"answer": threadId => {
utils.sendMessage(config.answerResponses[Math.floor(Math.random() * config.answerResponses.length)], threadId);
},
"space": (threadId, cmatch) => {
const search = cmatch[2];
request.get(`https://images-api.nasa.gov/search?q=${encodeURIComponent(search)}&media_type=image`, (err, res, body) => {
if (!err) {
const results = JSON.parse(body).collection.items;
if (results && results.length > 0) {
const chosen = cmatch[1] ? Math.floor(Math.random() * results.length) : 0; // If rand not specified, use top result
const link = results[chosen].links[0].href;
const data = results[chosen].data[0];
utils.sendFilesFromUrl(link, threadId, `"${data.title}"\n${data.description}`);
} else {
utils.sendError(`No results found for ${search}`, threadId);
}
} else {
utils.sendError(`No results found for ${search}`, threadId);
}
});
},
"rng": (threadId, cmatch) => {
let lowerBound, upperBound;
if (cmatch[2]) {
lowerBound = parseInt(cmatch[1]); // Assumed to exist if upperBound was passed
upperBound = parseInt(cmatch[2]);
} else { // No last parameter
lowerBound = config.defaultRNGBounds[0];
if (cmatch[1]) { // Only parameter passed becomes upper bound
upperBound = parseInt(cmatch[1]);
} else { // No params passed at all
upperBound = config.defaultRNGBounds[1];
}
}
const rand = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
const chance = Math.abs(((1.0 / (upperBound - lowerBound + 1)) * 100).toFixed(2));
utils.sendMessage(`${rand}\n\nWith bounds of (${lowerBound}, ${upperBound}), the chances of receiving this result were ${chance}%`, threadId);
},
"bw": (threadId, cmatch, groupInfo, _, __, attachments) => {
const url = cmatch[1];
utils.processImage(url, attachments, groupInfo, (img, filename, path) => {
img.greyscale().write(path, err => {
if (!err) {
utils.sendFile(filename, threadId, "", () => {
fs.unlink(path, () => { });
});
}
});
});
},
"sepia": (threadId, cmatch, groupInfo, _, __, attachments) => {
const url = cmatch[1];
utils.processImage(url, attachments, groupInfo, (img, filename, path) => {
img.sepia().write(path, err => {
if (!err) {