forked from Mimickal/ReactionRoleBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
841 lines (742 loc) · 24.2 KB
/
main.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
/*******************************************************************************
* This file is part of ReactionRoleBot, a role-assigning Discord bot.
* Copyright (C) 2020 Mimickal (Mia Moretti).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
******************************************************************************/
const fs = require('fs');
const Discord = require('discord.js');
const cache = require('./cache');
const database = require('./database');
// Everything operates on IDs, so we can safely rely on partials.
// This causes reaction events to fire for uncached messages.
const client = new Discord.Client({
partials: [
Discord.Constants.PartialTypes.MESSAGE,
Discord.Constants.PartialTypes.CHANNEL,
Discord.Constants.PartialTypes.REACTION
]
});
const token = process.env.DISCORD_TOKEN;
// Map of command names to handling functions. Doubles as a validator.
const COMMANDS = new Map();
cmdDef(selectMessage,
'select', '<channel|channel_id> <message_id>',
`Selects the message to perform actions on. This is per-user, so multiple
people can be setting up roles on different messages (or the same one).`
);
cmdDef(setupReactRole,
'role-add', '<emoji> <role|role_id>',
`Creates an emoji-role on the selected message. The bot will automatically
react to the message with this emoji.`
);
cmdDef(removeReactRole,
'role-remove', '<emoji>',
`Removes the emoji-role from the message. The bot will remove all reactions
of this emoji from the message.`
);
cmdDef(removeAllReacts,
'role-remove-all', '',
`Removes all emoji-roles and reactions from the message. This will **not**
remove existing roles from users.`
);
cmdDef(addPermissionRole,
'perm-add', '<role|role_id>',
`Adds a role that is allowed to configure this bot in this server. Note that
this role will be allowed to add more roles with this same permission.`
);
cmdDef(removePermissionRole,
'perm-remove', '<role|role_id>',
`Removes a role from being allowed to configure this bot in this server.
Note that allowed roles can remove their own ability to configure this bot,
and will then be unable to make further changes until an administrator
re-adds their permission.`
);
cmdDef(addMutexRoles,
'mutex-add', '<role1|role1_id> <role2|role2_id>',
`Makes two roles mutually exclusive. If a user attempts to add two mutually
exclusive roles, they will lose the first one they had.`
);
cmdDef(removeMutexRoles,
'mutex-remove', '<role1|role1_id> <role2|role2_id>',
`Removes the mutually exclusive restriction on two roles.`
);
cmdDef(sayInfo,
'info', '',
'Prints description, version, and link to source code for the bot'
);
cmdDef(sayHelp,
'help', '',
'Prints this help text'
);
const Events = Discord.Constants.Events;
client.on(Events.CLIENT_READY, onReady);
client.on(Events.GUILD_CREATE, onGuildJoin);
client.on(Events.GUILD_DELETE, onGuildLeave);
client.on(Events.MESSAGE_CREATE, onMessage);
client.on(Events.MESSAGE_REACTION_ADD, onReactionAdd);
client.on(Events.MESSAGE_REACTION_REMOVE, onReactionRemove);
client.login(token).catch(err => {
logError(err);
process.exit(1);
});
/**
* Event handler for when the bot is logged in.
*/
function onReady() {
console.log(`Logged in as ${client.user.tag}`);
// No idea why Discord.js does stuff like this...
// https://github.com/discordjs/discord.js/blob/master/src/util/Constants.js#L431
// const LISTENING = 2;
// client.user.setPresence({
// activity: {
// name: "'help' for commands",
// type: Discord.Constants.ActivityTypes[LISTENING]
// }
// }).catch(logError);
}
/**
* Event handler for when the bot joins a new guild.
*/
function onGuildJoin(guild) {
guild.members.fetch(client.user.id)
.then(clientMember => {
let info = unindent(`Hi there! My role needs to be ordered above any
role you would like me to assign. You're getting this message
because you are the server owner, but anybody with Administrator
permissions or an allowed role can configure me.`);
const Perms = Discord.Permissions.FLAGS;
const requiredPermMap = {
[Perms.ADD_REACTIONS]: 'Add Reactions',
[Perms.MANAGE_MESSAGES]: 'Manage Messages',
[Perms.MANAGE_ROLES]: 'Manage Roles',
[Perms.READ_MESSAGE_HISTORY]: 'Read Message History',
[Perms.USE_EXTERNAL_EMOJIS]: 'Use External Emojis',
[Perms.VIEW_CHANNEL]: 'Read Text Channels & See Voice Channels'
};
// This bot probably shouldn't be given the admin permission, but if
// we have it then the other ones don't matter.
// Also, these permissions can also be inherited from the server's
// @everyone permissions.
let missingPermNames = Object.entries(requiredPermMap)
.filter(([perm, name]) => !clientMember.hasPermission(
parseInt(perm),
{ checkAdmin: true }
))
.map(([perm, name]) => name);
if (missingPermNames.length > 0) {
info += '\n\n' + unindent(`Also, I am missing the following
permissions. Without them, I probably won't work right:`) +
'\n' + missingPermNames.join('\n');
}
return guild.owner.createDM()
.then(dmChannel => dmChannel.send(info));
})
.catch(logError);
}
/**
* Event handler for when the bot leaves (or is kicked from) a guild.
*/
function onGuildLeave(guild) {
database.clearGuildInfo(guild.id)
.catch(logError);
}
/**
* Event handler for getting a new message.
* Parses and delegates any role bot command.
*/
function onMessage(msg) {
// Ignore DMs
if (msg.channel instanceof Discord.DMChannel) {
return;
}
// Ignore anything where we're not even mentioned
if (!msg.mentions.has(client.user)) {
return;
}
let msgParts = msg.content.split(/\s+/);
// Only pay attention to messages where we're mentioned first.
let mentionUserId = extractId(msgParts.shift());
if (mentionUserId !== client.user.id) {
return;
}
let cmdName = msgParts.shift();
// Only pay attention to messages that are known commands.
if (!COMMANDS.has(cmdName)) {
logError('Possible unrecognized command: ' + msg.content);
return;
}
userHasPermission(msg, cmdName)
.then(hasPerm => {
if (hasPerm) {
COMMANDS.get(cmdName).get('handler')(msg, msgParts);
} else {
msg.reply("You don't have permission to use that command");
}
})
.catch(logError);
}
/**
* Selects a message to associate with any subsequent role commands.
* Previously selected message is cleared if the user gives bad input for this.
*/
function selectMessage(msg, parts) {
// TODO support selection by URL
let maybeChannelId = parts.shift();
let maybeMessageId = parts.shift();
let channelId = extractId(maybeChannelId);
let messageId = extractId(maybeMessageId);
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
else if (!maybeChannelId) issue = 'Missing channel!';
else if (!maybeMessageId) issue = 'Missing message_id!';
else if (!channelId) issue = `Invalid channel_id \`${maybeChannelId}\`!`;
else if (!messageId) issue = `Invalid message_id \`${maybeMessageId}\`!`;
if (issue) {
msg.reply(issue + usage('select'));
cache.clearSelectedMessage(msg.author.id);
return;
}
client.channels.fetch(channelId)
.then(channel => channel.messages.fetch(messageId))
.then(message => {
cache.selectMessage(msg.author.id, message);
return msg.reply(
`selected message with ID \`${message.id}\` ` +
`in channel <#${channelId}>. Link: ${message.url}`
);
})
.catch(err => {
// The user is trying to select a new message, so at least clear
// their old selection. Principle of least surprise, and all that...
cache.clearSelectedMessage(msg.author.id);
let errMsg;
if (err.message === 'Unknown Channel') {
errMsg = "I can't find a channel in this server with ID "
+ `\`${channelId}\`.`;
}
else if (err.message === 'Unknown Message') {
errMsg = `I can't find a message with ID \`${messageId}\` `
+ `in channel <#${channelId}>.`;
}
else {
errMsg = `I got an error I don't recognize:\n\`${err.message}\``;
logError(err, 'For message', msg.content);
}
errMsg += usage('select');
msg.reply(errMsg);
});
}
/**
* Associate an emoji reaction with a role for the currently selected message.
*/
function setupReactRole(msg, parts) {
// TODO do we want to warn when two emojis map to the same role?
let rawEmoji = parts.shift(); // Needed to print emoji in command response
let maybeRole = parts.shift();
let emoji = extractEmoji(rawEmoji);
let roleId = extractId(maybeRole);
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
else if (!emoji) issue = 'Missing emoji!';
else if (!maybeRole) issue = 'Missing role!';
else if (!roleId) issue = `Invalid role \`${maybeRole}\`!`;
if (issue) {
msg.reply(issue + usage('role-add'));
return;
}
let userId = msg.author.id;
msg.guild.roles.fetch(roleId)
.then(role => {
if (!role) {
throw new Error('Invalid Role');
}
return cache.addEmojiRole(userId, emoji, roleId);
})
.then(() => cache.getSelectedMessage(userId))
.then(selectedMessage => selectedMessage.react(emoji))
.then(reaction => msg.reply(
`mapped ${rawEmoji} to <@&${roleId}> on message \`${reaction.message.id}\``
))
.catch(err => {
if (err.message === 'No message selected!') {
msg.reply('You need to select a message first!');
}
else if (err.message === 'Invalid Role') {
msg.reply(`I can't find a role with ID \`${roleId}\``);
}
else if (err.message === 'Unknown Emoji') {
msg.reply(
`I can't find an emoji with ID \`${emoji}\``
+ usage('role-add')
);
}
else if (err.message === 'Missing Permissions') {
msg.reply("I don't have permission to react to the selected message");
}
else {
msg.reply(`I got an error I don't recognize:\n\`${err.message}\``);
logError(err, 'For message', msg.content);
}
});
}
/**
* Removes an emoji reaction role association from the currently selected
* message.
*/
function removeReactRole(msg, parts) {
let rawEmoji = parts.shift();
let emoji = extractEmoji(rawEmoji);
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
else if (!emoji) issue = 'Missing emoji!';
if (issue) {
msg.reply(issue + usage('role-remove'));
return;
}
let userId = msg.author.id;
Promise.resolve() // Hack to pass error from getSelectedMessage to .catch
.then(() => cache.getSelectedMessage(userId))
.then(selectedMessage => {
let emojiReacts = selectedMessage.reactions.cache.get(emoji);
return Promise.all([
emojiReacts ? emojiReacts.remove() : Promise.resolve(),
cache.removeEmojiRole(userId, emoji)
])
.then(() => msg.reply(
`removed ${rawEmoji} role from message \`${selectedMessage.id}\``
));
})
.catch(err => {
if (err.message === 'No message selected!') {
msg.reply('You need to select a message first!');
}
else if (err.message === 'No role mapping found') {
msg.reply(
`Selected message does not have ${rawEmoji} reaction.\n` +
'If that displayed as a raw ID instead of an emoji, you ' +
'might be using the wrong ID.'
);
}
else if (err.message === 'Missing Permissions') {
msg.reply("I don't have permission to modify the selected message");
}
else {
msg.reply(`I got an error I don't recognize:\n\`${err.message}\``);
logError(err, 'For message', msg.content);
}
});
}
/**
* Removes all emoji-role associations from the currently selected message.
*/
function removeAllReacts(msg, parts) {
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
if (issue) {
msg.reply(issue + usage('role-remove-all'));
return;
}
let userId = msg.author.id;
Promise.resolve() // Hack to pass all errors to .catch
.then(() => cache.getSelectedMessage(userId))
.then(selectedMessage => selectedMessage.reactions.removeAll())
.then(() => cache.removeAllEmojiRoles(userId))
.then(selectedMessage => msg.reply(
`removed all roles from message \`${selectedMessage.id}\``
))
.catch(err => {
if (err.message === 'No role mapping found') {
msg.reply('Selected message does not have any role reactions.');
}
else if (err.message === 'No message selected!') {
msg.reply('You need to select a message first!');
}
else if (err.message === 'Missing Permissions') {
msg.reply("I don't have permission to modify the selected message");
}
else {
msg.reply(`I got an error I don't recognize:\n\`${err.message}\``);
logError(err, 'For message', msg.content);
}
});
}
/**
* Adds a role that is allowed to configure this bot's settings for a guild.
*/
function addPermissionRole(msg, parts) {
let maybeRole = parts.shift();
let roleId = extractId(maybeRole);
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
else if (!maybeRole) issue = 'Missing role!';
else if (!roleId) issue = `Invalid role \`${maybeRole}\`!`;
if (issue) {
msg.reply(issue + usage('perm-add'));
return;
}
msg.guild.roles.fetch(roleId)
.then(role => {
if (!role) {
throw new Error('Invalid Role');
}
return database.addAllowedRole({
guild_id: msg.guild.id,
role_id: role.id
});
})
.then(() => msg.reply(`Role <@&${roleId}> can now configure me!`))
.catch(err => {
if (err.message === 'Invalid Role') {
msg.reply(`I can't find a role with ID \`${roleId}\``);
}
else if (err.message.includes('UNIQUE constraint failed')) {
msg.reply(`Role <@&${roleId}> was already added.`);
}
else {
msg.reply(`I got an error I don't recognize:\n\`${err.message}\``);
logError(err, 'For message', msg.content);
}
});
}
/**
* Removes a role from being allowed to configure this bot's settings for a
* guild. A role can remove itself, which is dumb but whatever.
*/
function removePermissionRole(msg, parts) {
let maybeRole = parts.shift();
let roleId = extractId(maybeRole);
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
else if (!maybeRole) issue = 'Missing role!';
else if (!roleId) issue = `Invalid role \`${maybeRole}\`!`;
if (issue) {
msg.reply(issue + usage('perm-remove'));
return;
}
msg.guild.roles.fetch(roleId)
.then(role => {
if (!role) {
throw new Error('Invalid Role');
}
return database.removeAllowedRole({
guild_id: msg.guild.id,
role_id: role.id
});
})
.then(numRemoved => msg.reply(
`Role <@&${roleId}> ${
numRemoved === 1 ? 'is no longer' : 'was already not'
} allowed to configure me.`
))
.catch(err => {
if (err.message === 'Invalid Role') {
msg.reply(`I can't find a role with ID \`${roleId}\``);
}
else {
msg.reply(`I got an error I don't recognize:\n\`${err.message}\``);
logError(err, 'For message', msg.content);
}
});
}
/**
* Makes two roles mutually exclusive for a guild.
*/
function addMutexRoles(msg, parts) {
let maybeRole1 = parts.shift();
let maybeRole2 = parts.shift();
let roleId1 = extractId(maybeRole1);
let roleId2 = extractId(maybeRole2);
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
else if (!maybeRole1) issue = 'Missing role 1!';
else if (!maybeRole2) issue = 'Missing role 2!';
else if (!roleId1) issue = `Invalid role \`${maybeRole1}\`!`;
else if (!roleId2) issue = `Invalid role \`${maybeRole2}\`!`;
else if (roleId1 == roleId2)
issue = 'Cannot make a role mutually exclusive with itself!';
if (issue) {
msg.reply(issue + usage('mutex-add'));
return;
}
Promise.all([
msg.guild.roles.fetch(roleId1),
msg.guild.roles.fetch(roleId2)
])
.then(([role1, role2]) => {
if (!role1) throw new Error('Invalid Role 1');
if (!role2) throw new Error('Invalid Role 2');
return database.addMutexRole({
guild_id: msg.guild.id,
role_id_1: role1.id,
role_id_2: role2.id
});
})
.then(() => msg.reply(
`Roles <@&${roleId1}> and <@&${roleId2}> are now mutually exclusive`
))
.catch(err => {
let match;
if (match = err.message.match(/Invalid Role (\d)/)) {
let cantFind = match[1] === '1' ? roleId1 : roleId2;
msg.reply(`I can't find a role with ID \`${cantFind}\``);
}
else if (err.message.includes('UNIQUE constraint failed')) {
msg.reply(unindent(
`Roles <@&${roleId1}> and <@&${roleId2}> are
already mutually exclusive`
));
}
else {
msg.reply(`I got an error I don't recognize:\n\`${err.message}\``);
logError(err, 'For message', msg.content);
}
});
}
/**
* Removes the mutually exclusive restriction for two roles in a guild.
*/
function removeMutexRoles(msg, parts) {
let maybeRole1 = parts.shift();
let maybeRole2 = parts.shift();
let roleId1 = extractId(maybeRole1);
let roleId2 = extractId(maybeRole2);
let issue;
if (parts.length > 0) issue = 'Too many arguments!';
else if (!maybeRole1) issue = 'Missing role 1!';
else if (!maybeRole2) issue = 'Missing role 2!';
else if (!roleId1) issue = `Invalid role \`${maybeRole1}\`!`;
else if (!roleId2) issue = `Invalid role \`${maybeRole2}\`!`;
if (issue) {
msg.reply(issue + usage('mutex-remove'));
return;
}
Promise.all([
msg.guild.roles.fetch(roleId1),
msg.guild.roles.fetch(roleId2)
])
.then(([role1, role2]) => {
if (!role1) throw new Error('Invalid Role 1');
if (!role2) throw new Error('Invalid Role 2');
return database.removeMutexRole({
guild_id: msg.guild.id,
role_id_1: role1.id,
role_id_2: role2.id
});
})
.then(numRemoved => msg.reply(
`Roles <@&${roleId1}> and <@&${roleId2}> ${
numRemoved === 1 ? 'are no longer' : 'were already not'
} mutually exclusive`
))
.catch(err => {
let match;
if (match = err.message.match(/Invalid Role (\d)/)) {
let cantFind = match[1] === '1' ? roleId1 : roleId2;
msg.reply(`I can't find a role with ID \`${cantFind}\``);
}
else {
msg.reply(`I got an error I don't recognize:\n\`${err.message}\``);
logError(err, 'For message', msg.content);
}
});
}
/**
* Replies with info about this bot, including a link to the source code to be
* compliant with the AGPLv3 this bot is licensed under.
*/
function sayInfo(msg) {
const info = require('./package.json');
database.getMetaStats().then(stats => msg.reply(
`${info.description}\n` +
`**Running version:** ${info.version}\n` +
`**Source code:** ${info.homepage}\n\n` +
'```Stats For Nerds\n' +
` - Servers bot is active in: ${stats.guilds}\n` +
` - Reaction role mappings: ${stats.roles}\n` +
` - Total role assignments: ${stats.assignments}\n` +
'```'
));
}
/**
* Replies with a list of commands and their usage information.
*/
function sayHelp(msg) {
let embed = new Discord.MessageEmbed()
.setTitle('Commands Help');
COMMANDS.forEach(def => embed.addField(
def.get('usage'), def.get('description')
));
msg.reply(embed).catch(logError);
}
/**
* Event handler for when a reaction is added to a message.
* Checks if the message has any reaction roles configured, assigning a role to
* the user who added the reaction, if applicable. Ignores reacts added by this
* bot, of course. If a user attempts to assign a role that is mutually
* exclusive with a role they already have, they will lose that first role, and
* their reaction to the message for that role will be removed.
*/
function onReactionAdd(reaction, user) {
if (user === client.user) {
return;
}
let emoji = emojiIdFromEmoji(reaction.emoji);
cache.getReactRole(reaction.message.id, emoji)
.then(roleId => {
if (!roleId) {
return;
}
// TODO if ever there was a time for async-await, this is it.
// TODO Also this seems to hit Discord's rate limit almost
// immediately because of each mutex react removal being its own
// request. Might need to look into .set
return Promise.all([
reaction.message.guild.members.fetch(user.id),
database.getMutexRoles({
guild_id: reaction.message.guild.id,
role_id: roleId
})
])
.then(([member, mutexRoles]) =>
member.roles.remove(mutexRoles, 'Role bot removal (mutex)')
.then(() => member.roles.add(roleId, 'Role bot assignment'))
.then(() => database.getMutexEmojis(mutexRoles))
.then(mutexEmojis =>
asyncForEach(mutexEmojis, function(emoji) {
let mesRec = reaction.message.reactions.resolve(emoji);
if (mesRec) return mesRec.users.remove(user);
})
)
)
.then(() => database.incrementAssignCounter())
.then(() => console.log(`added role ${roleId} to ${user}`));
})
.catch(logError);
}
/**
* Event handler for when a reaction is removed from a message.
* Checks if the message has any reaction roles configured, removing a role from
* the user who removed their reaction, if applicable. Ignored reacts removed by
* this bot, of course.
*/
function onReactionRemove(reaction, user) {
// TODO How do we handle two emojis mapped to the same role?
// Do we only remove the role if the user doesn't have any of the mapped
// reactions? Or do we remove when any of the emojis are un-reacted?
if (user === client.user) {
return;
}
let emoji = emojiIdFromEmoji(reaction.emoji);
cache.getReactRole(reaction.message.id, emoji)
.then(roleId => {
if (!roleId) {
return;
}
return reaction.message.guild.members.fetch(user.id)
.then(member => member.roles.remove(roleId, 'Role bot removal'))
.then(() => console.log(`removed role ${roleId} from ${user}`))
})
.catch(logError);
}
/**
* Given a message, determines if the sender has permission to use the bot.
* This may involve a database check, so it returns a Promise.
*/
function userHasPermission(msg, command_name) {
const everyoneCommands = ['info'];
if (
msg.member.hasPermission(Discord.Permissions.FLAGS.ADMINISTRATOR) ||
everyoneCommands.includes(command_name)
) {
return Promise.resolve(true);
}
return database.getAllowedRoles(msg.guild.id)
.then(roles => roles.some(role => msg.member.roles.cache.has(role)));
}
/**
* Takes an array of items and a function that may return a promise, then runs
* the promise function for each item in the array, in sequence. Returns a
* promise that resolves once every element has been processed.
* Does not return the results because we don't need them.
*/
async function asyncForEach(arr, promiseFunc) {
for await (let elem of arr) {
promiseFunc(elem);
}
}
// I'm aware Discord.MessageMentions.*_PATTERN constants exist, but they all
// have the global flag set, which screws up matching groups. For this reason we
// need to construct our own.
//
// Also, for flexibility's sake we just don't care about what type of ID this
// is. This could have collisions but it's unlikely.
function extractId(str) {
if (!str) {
return null;
}
let match = str.match(/(\d{17,19})/);
return match ? match[1] : null;
}
/**
* Allows us to handle custom server emojis. They are encoded in messages like
* this: <:flagtg:681985787864416286>. Discord.js can add emojis using a
* unicode string for built-in emojis, or the ID portion of the name
* (e.g. 681985787864416286) for custom server emojis.
*/
function extractEmoji(emoji) {
if (!emoji) {
return null;
}
let match = emoji.match(/<:.+:(\d{17,19})>/);
return match ? match[1] : emoji;
}
/**
* Built-in emojis are identified by name. Custom emojis are identified by ID.
* This function handles that nuance for us.
*/
function emojiIdFromEmoji(emoji) {
return emoji.id || emoji.name;
}
/**
* Helper for creating command definitions. We could nest these in raw objects,
* but Maps are nicer.
*/
function cmdDef(handler, name, usage, description) {
let map = new Map();
map.set('handler', handler);
map.set('usage', `\`${name} ${usage}\``);
map.set('description', unindent(description));
COMMANDS.set(name, map);
}
/**
* Dress up usage string for a command.
*/
function usage(name) {
return `\nUsage: ${COMMANDS.get(name).get('usage')}`;
}
/**
* Allows us to treat multi-line template strings as a single continuous line.
*/
function unindent(str) {
return str
.replace(/^\s*/, '')
.replace(/\n\t*/g, ' ');
}
/**
* Single function to make error redirection easier in the future.
* Maybe some day we'll do something more intelligent with errors.
*/
function logError(err) {
console.error(err);
}