-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlib.js
600 lines (524 loc) · 21.5 KB
/
lib.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
const { Client, Guild, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder,
ButtonStyle} = require('discord.js');
const mysql = require('mysql2');
const config = require('./config.json');
const { generalErrorHandler } = require('./errorHandlers');
module.exports = {
// Function which returns a promise which will resolve to true or false
verifyModeratorRole: (guildMember) => new Promise(async (resolve) => {
if (module.exports.verifyIsAdmin(guildMember)) { resolve(true); }
const moderatorRole = await module.exports.getModeratorRole(guildMember.guild);
resolve(moderatorRole.position <= guildMember.roles.highest.position);
}),
verifyIsAdmin: (guildMember) => {
if (!guildMember) { return false; }
return guildMember.permissions.has(PermissionFlagsBits.Administrator);
},
getModeratorRole: (guild) => new Promise(async (resolve) => {
let modRole = null;
// If this guild has a known moderator role id, fetch that role
let sql = 'SELECT moderatorRoleId FROM guild_data WHERE guildId=?';
let result = await module.exports.dbQueryOne(sql, [guild.id]);
if (result && result.hasOwnProperty('moderatorRoleId') && result.moderatorRoleId) {
modRole = guild.roles.resolve(result.moderatorRoleId);
if (modRole) {
return resolve(modRole);
}
}
// The guild's moderator role is not known, or it has been deleted. Attempt to find a moderator role
// and update the database
modRole = await module.exports.discoverModeratorRole(guild);
if (modRole) {
await module.exports.dbExecute('UPDATE guild_data SET moderatorRoleId=? WHERE guildId=?',
[modRole.id, guild.id]);
}
// Resolve with the newly found moderator role, or with null of no role could be found
return resolve(modRole || null);
}),
/**
* Search a guild for a role with whose name matches config.moderatorRole
* @param guild
* @returns Promise which resolves to a Discord Role object, or null if no role could be found
*/
discoverModeratorRole: async (guild) => {
let modRole = null;
await guild.roles.cache.each((role) => {
if (modRole !== null) { return; }
if (role.name === config.moderatorRole) {
modRole = role;
}
});
return modRole;
},
handleGuildCreate: async (client, guild) => {
console.info(`Creating db structure after joining guild ${guild.id}`);
// Find this guild's moderator role id
let moderatorRole = await module.exports.getModeratorRole(guild);
if (!moderatorRole) {
return guild.roles.create({
name: config.moderatorRole,
reason: `AginahBot requires a ${config.moderatorRole} role.`
}).then(async (moderatorRole) => {
let sql = 'INSERT INTO guild_data (guildId, moderatorRoleId) VALUES (?, ?)';
await module.exports.dbExecute(sql, [guild.id, moderatorRole.id]);
}).catch((err) => generalErrorHandler(err));
}
// Create guild data
let sql = 'INSERT INTO guild_data (guildId, moderatorRoleId) VALUES (?, ?)';
await module.exports.dbExecute(sql, [guild.id, moderatorRole.id]);
// Create guild options
const guildData = await module.exports.dbQueryOne('SELECT id FROM guild_data WHERE guildId=?', [guild.id]);
await module.exports.dbExecute('INSERT INTO guild_options (guildDataId) VALUES (?)', [guildData.id]);
},
handleGuildDelete: async (client, guild) => {
console.info(`Cleaning up guild data after leaving guild ${guild.id}`);
const guildData = await module.exports.dbQueryOne('SELECT id FROM guild_data WHERE guildId=?', [guild.id]);
if (!guildData) {
console.warn('No guild_data entry could be found when trying to handleGuildDelete for ' +
`guild: ${guild.name} (${guild.id}).`);
return;
}
// Delete dynamic game system data
const roomSystems = await module.exports.dbQueryAll('SELECT id FROM room_systems WHERE guildDataId=?',
[guildData.id]);
roomSystems.forEach((roomSystem) => {
module.exports.dbExecute('DELETE FROM room_system_channels WHERE roomSystemId=?', [roomSystem.id]);
module.exports.dbExecute('DELETE FROM room_systems WHERE id=?', [roomSystem.id]);
});
// Delete role requestor system data
const roleSystem = await module.exports.dbQueryOne('SELECT id FROM role_systems WHERE guildDataId=?',
[guildData.id]);
if (roleSystem) {
const categories = await module.exports.dbQueryAll('SELECT id FROM role_categories WHERE roleSystemId=?',
[roleSystem.id]);
categories.forEach((category) => {
module.exports.dbExecute('DELETE FROM roles WHERE categoryId=?', [category.id]);
});
await module.exports.dbExecute('DELETE FROM role_categories WHERE roleSystemId=?', [roleSystem.id]);
await module.exports.dbExecute('DELETE FROM role_systems WHERE id=?', [roleSystem.id]);
}
// Delete guild data and options
await module.exports.dbExecute('DELETE FROM guild_options WHERE guildDataId=?', [guildData.id]);
await module.exports.dbExecute('DELETE FROM guild_data WHERE id=?', [guildData.id]);
},
verifyGuildSetups: async (client) => {
client.guilds.cache.each(async (guild) => {
// Ensure guild_data exists
const guildData = await module.exports.dbQueryOne('SELECT id FROM guild_data WHERE guildId=?', [guild.id]);
if (!guildData) { await module.exports.handleGuildCreate(client, guild); }
// Ensure guild_options exists
const guildOptions = await module.exports.dbQueryOne(
'SELECT 1 FROM guild_options WHERE guildDataId=?',
[guildData.id]
);
if (!guildOptions) {
await module.exports.dbExecute('INSERT INTO guild_options (guildDataId) VALUES (?)', [guildData.id]);
}
});
},
/**
* Get an emoji object usable with Discord. Null if the Emoji is not usable in the provided guild.
* @param guild
* @param emoji
* @param force
* @returns String || Object || null
*/
parseEmoji: async (guild, emoji, force = false) => {
const match = emoji.match(/^<:(.*):(\d+)>$/);
if (match && match.length > 2) {
const emojis = await guild.emojis.fetch(null, { force });
const emojiObj = emojis.get(match[2]);
return emojiObj ? emojiObj : null;
}
const nodeEmoji = require('node-emoji');
return nodeEmoji.has(emoji) ? emoji : null;
},
cachePartial: (partial) => new Promise((resolve, reject) => {
if (!partial.partial) { resolve(partial); }
partial.fetch()
.then((full) => resolve(full))
.catch((error) => reject(error));
}),
dbConnect: () => mysql.createConnection({
host: config.dbHost,
user: config.dbUser,
password: config.dbPass,
database: config.dbName,
supportBigNumbers: true,
bigNumberStrings: true,
}),
dbQueryOne: (sql, args = []) => new Promise((resolve, reject) => {
const conn = module.exports.dbConnect();
conn.query(sql, args, (err, result) => {
if (err) { reject(err); }
else if (result.length > 1) { reject('More than one row returned'); }
else { resolve(result.length === 1 ? result[0] : null); }
return conn.end();
});
}),
dbQueryAll: (sql, args = []) => new Promise((resolve, reject) => {
const conn = module.exports.dbConnect();
conn.query(sql, args, (err, result) => {
if (err) { reject(err); }
else { resolve(result); }
return conn.end();
});
}),
dbExecute: (sql, args = []) => new Promise((resolve, reject) => {
const conn = module.exports.dbConnect();
conn.execute(sql, args, (err) => {
if (err) { reject(err); }
else { resolve(); }
return conn.end();
});
}),
parseArgs: (command) => {
// Quotes with which arguments can be wrapped
const quotes = ['\'', '"'];
// State tracking
let insideQuotes = false;
let currentQuote = null;
// Parsed arguments are stored here
const args = [];
// Break the command into an array of characters
const commandChars = command.trim().split('');
let thisArg = '';
commandChars.forEach((char) => {
if (char === ' ' && !insideQuotes){
// This is a whitespace character used to separate arguments
if (thisArg) { args.push(thisArg); }
thisArg = '';
return;
}
// If this character is a quotation mark
if (quotes.indexOf(char) > -1) {
// If the cursor is currently inside a quoted string and has found a matching quote to the
// quote which started the string
if (insideQuotes && currentQuote === char) {
args.push(thisArg);
thisArg = '';
insideQuotes = false;
currentQuote = null;
return;
}
// If a quote character is found within a quoted string but it does not match the current enclosing quote,
// it should be considered part of the argument
if (insideQuotes) {
thisArg += char;
return;
}
// Cursor is not inside a quoted string, so we now consider it within one
insideQuotes = true;
currentQuote = char;
return;
}
// Include the character in the current argument
thisArg += char;
});
// Append current argument to array if it is populated
if (thisArg) {args.push(thisArg); }
return args;
},
/**
*
* @param client {Client}
* @param guild {Guild}
* @returns {Promise<void>}
*/
updateScheduleBoard: async (client, guild) => {
// Find all schedule boards
let sql = `SELECT sb.id, gd.id AS guildId, sb.channelId, sb.messageId
FROM schedule_boards sb
JOIN guild_data gd ON sb.guildDataId = gd.id
WHERE gd.guildId=?`;
const boards = await module.exports.dbQueryAll(sql, [guild.id]);
for (let board of boards) {
// Find board channel, clean database if channel has been deleted
const boardChannel = await guild.channels.fetch(board.channelId);
if (!boardChannel) {
await module.exports.dbExecute('DELETE FROM schedule_boards WHERE id=?', [board.id]);
continue;
}
// Find board message, clean database if message has been deleted
const boardMessage = await boardChannel.messages.fetch(board.messageId);
if (!boardMessage) {
await module.exports.dbExecute('DELETE FROM schedule_boards WHERE id=?', [board.id]);
continue;
}
sql = `SELECT se.id, se.timestamp, se.schedulingUserId, se.channelId, se.messageId, se.threadId, se.eventCode,
se.title, se.duration
FROM scheduled_events se
JOIN guild_data gd ON se.guildDataId = gd.id
WHERE gd.guildId=?
AND se.timestamp > ?
ORDER BY se.timestamp
LIMIT 10`;
const events = await module.exports.dbQueryAll(sql, [guild.id, new Date().getTime()]);
// If there are no scheduled events for this guild, continue to the next schedule board
if (events.length === 0) {
return boardMessage.edit({ content: 'There are no upcoming events.', embeds: [] });
}
sql = `SELECT COUNT(*) AS count
FROM scheduled_events se
JOIN guild_data gd ON se.guildDataId = gd.id
WHERE gd.guildId=?
AND se.timestamp > ?
ORDER BY se.timestamp
LIMIT 10`;
const countResult = await module.exports.dbQueryOne(sql, [guild.id, new Date().getTime()]);
// Embeds which will be PUT to the schedule board message
const embeds = [];
const embedColors = [
'3498DB', // Light Blue
'2ECC71', // Green
'E67E22', // Orange
'E74C3C', // Light Red (Rose)
'34495E', // Navy
'8B0000', // Dark Red (Maroon)
'8A2BE2', // Purple
'008080', // Teal
'DDA0DD', // Plum
'808000' // Olive
];
for (let event of events) {
let eventChannel = null;
let eventMessage = null;
try {
eventChannel = await guild.channels.fetch(event.channelId);
eventMessage = await eventChannel.messages.fetch(event.messageId);
} catch (err) {
if (err.status !== 404) {
throw err;
}
// If the channel or message is gone, remove this event from the table
await module.exports.dbExecute('DELETE FROM scheduled_events WHERE id=?', [event.id]);
continue;
}
let schedulingUser = null;
try {
schedulingUser = await guild.members.fetch(event.schedulingUserId);
} catch (err) {
if (err.status !== 404) {
throw err;
}
// If we have a 404 here, it means the user is no longer a member of the guild. In these instances,
// no information about the user will be included in the embed
}
let eventThread = null;
try {
eventThread = event.threadId ? await guild.channels.fetch(event.threadId) : null;
} catch (err) {
if (err.status !== 404) {
throw err;
}
// It's possible for a thread to have been deleted. In these cases, we remove the thread from the table
await module.exports.dbExecute('UPDATE scheduled_events SET threadId=NULL WHERE id=?', [event.id]);
}
// Determine RSVP count
const rsvpCount = await module.exports.dbQueryOne(
'SELECT COUNT(*) AS count FROM event_rsvp WHERE eventId=?',
[event.id]
);
const embed = new EmbedBuilder()
.setTitle(`${event.title || 'Upcoming Event'}`)
.setDescription(
`Starts <t:${Math.floor(event.timestamp / 1000)}:R> and should last` +
`${event.duration ? ` about ${event.duration} hours` : ' an undisclosed amount of time'}`
)
.setColor(`#${embedColors.pop()}`)
.setAuthor({ name: schedulingUser.displayName })
.setURL(eventMessage.url)
.setThumbnail(schedulingUser.displayAvatarURL())
.addFields(
{ name: 'Date/Time', value: `<t:${Math.floor(event.timestamp / 1000)}:F>`, inline: true },
{ name: ' ', value: ' ', inline: true },
{
name: 'Planning Channel',
value: eventThread ? `[#${eventChannel.name}](${eventThread.url})` : `#${eventChannel.name}`,
inline: true,
},
{ name: 'Event Code', value: event.eventCode, inline: true },
{ name: ' ', value: ' ', inline: true },
{ name: 'Current RSVPs', value: rsvpCount.count.toString(), inline: true },
);
embeds.push(embed);
}
// Update the schedule board
await boardMessage.edit({
content: (countResult.count > 10) ? '# Next 10 Upcoming Events' : '# Upcoming Events',
embeds
});
}
},
/**
* Update all schedule boards across all guilds
* @param client {Client}
*/
updateScheduleBoards: async (client) => {
// Find all schedule boards
let sql = `SELECT sb.id, gd.guildId AS guildId, sb.channelId, sb.messageId
FROM schedule_boards sb
JOIN guild_data gd ON sb.guildDataId = gd.id`;
const boards = await module.exports.dbQueryAll(sql);
for (let board of boards) {
// Fetch updated data for this guild
const guild = await client.guilds.fetch(board.guildId);
// Find board channel, clean database if channel has been deleted
let boardChannel = null;
try {
boardChannel = await guild.channels.fetch(board.channelId);
} catch (err) {
if (err.status === 404) {
await module.exports.dbExecute('DELETE FROM schedule_boards WHERE id=?', [board.id]);
continue;
}
}
// Ensure boardChannel is non-null
if (boardChannel === null) {
continue;
}
// Find board message, clean database if message has been deleted
let boardMessage = null;
try {
boardMessage = await boardChannel.messages.fetch(board.messageId);
} catch (err) {
if (err.status === 404) {
await module.exports.dbExecute('DELETE FROM schedule_boards WHERE id=?', [board.id]);
continue;
}
}
// Ensure boardMessage is non-null
if (boardMessage === null) {
continue;
}
sql = `SELECT se.id, se.timestamp, se.schedulingUserId, se.channelId, se.messageId, se.threadId,
se.eventCode, se.title, se.duration
FROM scheduled_events se
JOIN guild_data gd ON se.guildDataId = gd.id
WHERE gd.guildId=?
AND se.timestamp > ?
ORDER BY se.timestamp
LIMIT 10`;
const events = await module.exports.dbQueryAll(sql, [guild.id, new Date().getTime()]);
// If there are no scheduled events for this guild, continue to the next schedule board
if (events.length === 0) {
await boardMessage.edit({ content: 'There are no upcoming events.', embeds: [] });
continue;
}
sql = `SELECT COUNT(*) AS count
FROM scheduled_events se
JOIN guild_data gd ON se.guildDataId = gd.id
WHERE gd.guildId=?
AND se.timestamp > ?
ORDER BY se.timestamp
LIMIT 10`;
const countResult = await module.exports.dbQueryOne(sql, [guild.id, new Date().getTime()]);
// Embeds which will be PUT to the schedule board message
const embeds = [];
const embedColors = [
'3498DB', // Light Blue
'2ECC71', // Green
'E67E22', // Orange
'E74C3C', // Light Red (Rose)
'34495E', // Navy
'8B0000', // Dark Red (Maroon)
'8A2BE2', // Purple
'008080', // Teal
'DDA0DD', // Plum
'808000' // Olive
];
for (let event of events) {
let eventChannel = null;
let eventMessage = null;
try {
eventChannel = await guild.channels.fetch(event.channelId);
eventMessage = await eventChannel.messages.fetch(event.messageId);
} catch (err) {
if (err.status !== 404) {
throw err;
}
// If the channel or message is gone, remove this event from the table
await module.exports.dbExecute('DELETE FROM scheduled_events WHERE id=?', [event.id]);
continue;
}
let schedulingUser = null;
try {
schedulingUser = await guild.members.fetch(event.schedulingUserId);
} catch (err) {
if (err.status !== 404) {
throw err;
}
// If we have a 404 here, it means the user is no longer a member of the guild. In these instances,
// no information about the user will be included in the embed
}
let eventThread = null;
try {
eventThread = event.threadId ? await guild.channels.fetch(event.threadId) : null;
} catch (err) {
if (err.status !== 404) {
throw err;
}
// It's possible for a thread to have been deleted. In these cases, we remove the thread from the table
await module.exports.dbExecute('UPDATE scheduled_events SET threadId=NULL WHERE id=?', [event.id]);
}
// Determine RSVP count
const rsvpCount = await module.exports.dbQueryOne(
'SELECT COUNT(*) AS count FROM event_rsvp WHERE eventId=?',
[event.id]
);
const embed = new EmbedBuilder()
.setTitle(`${event.title || 'Upcoming Event'}`)
.setDescription(
`Starts <t:${Math.floor(event.timestamp / 1000)}:R> and should last` +
`${event.duration ? ` about ${event.duration} hours` : ' an undisclosed amount of time'}`
)
.setColor(`#${embedColors.pop()}`)
.setAuthor({ name: schedulingUser.displayName })
.setURL(eventMessage.url)
.setThumbnail(schedulingUser.displayAvatarURL())
.addFields(
{ name: 'Date/Time', value: `<t:${Math.floor(event.timestamp / 1000)}:F>`, inline: true },
{ name: ' ', value: ' ', inline: true },
{
name: 'Planning Channel',
value: eventThread ? `[#${eventChannel.name}](${eventThread.url})` : `#${eventChannel.name}`,
inline: true,
},
{ name: 'Event Code', value: event.eventCode, inline: true },
{ name: ' ', value: ' ', inline: true },
{ name: 'Current RSVPs', value: rsvpCount.count.toString(), inline: true },
);
embeds.push(embed);
}
// Update the schedule board
await boardMessage.edit({
content: (countResult.count > 10) ? '# Next 10 Upcoming Events' : '# Upcoming Events',
embeds
});
}
},
buildControlMessagePayload: (member) => ({
content: `This voice channel is currently owned by ${member}.\nThe following actions are available:` +
'\n-# Discord prohibits changing voice channel names more than twice per ten minutes.',
components: [
new ActionRowBuilder().addComponents(...[
new ButtonBuilder()
.setCustomId('eventRoom-rename')
.setLabel('Rename Channel')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('eventRoom-close')
.setLabel('Close Room')
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId('eventRoom-sendPing')
.setLabel('Send Event Ping')
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId('eventRoom-transfer')
.setLabel('Transfer Ownership')
.setStyle(ButtonStyle.Danger),
])
]
}),
};