-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.js
503 lines (415 loc) · 19.3 KB
/
utils.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
//@ts-check
const { MessageEmbed, Collection } = require("discord.js");
const ms = require("ms");
const embedColors = require('../../config/colors.json');
const reactions = ['⏪', '◀️', '⏸️', '▶️', '⏩', '🔢'];
const consoleColors = {
"SUCCESS": "\u001b[32m",
"WARNING": "\u001b[33m",
"ERROR": "\u001b[31m"
};
/**
* Function to check if the user has passed in the proper arguments when using a command
* @param {import('discord.js').Message} message - The message to check the arguments for
* @param {string[]} msgArgs - The arguments given by the user
* @param {import('../typings.d').Arguments} expectedArgs - The expected arguments for the command
* @returns {import('../typings.d').Flags} Returns the arguments mapped by their ID's if all the arguments were as expected, else, returns `undefined/false`
*/
function processArguments(message, msgArgs, expectedArgs) {
let counter = 0;
let amount, num, role, member, channel, attach, time;
let flags = { };
for (const argument of expectedArgs) {
//@ts-ignore
amount = (argument.amount && argument.amount > 1) ? argument.amount : 1;
for (let i = 0; i < amount; i++) {
if (!msgArgs[counter] && argument.type !== "ATTACHMENT") {
//@ts-ignore
if (argument.optional) return flags;
//@ts-ignore
return { invalid: true, prompt: argument.prompt };
}
switch (argument.type) {
case "SOMETHING":
if (argument.words && !argument.words.includes(msgArgs[counter].toLowerCase())) return { invalid: true, prompt: argument.prompt };
else if (argument.regexp && !argument.regexp.test(msgArgs[counter])) return { invalid: true, prompt: argument.prompt };
if (amount == 1) flags[argument.id] = msgArgs[counter];
else if (flags[argument.id]) flags[argument.id].push(msgArgs[counter]);
else flags[argument.id] = [msgArgs[counter]];
break;
case "NUMBER":
num = Number(msgArgs[counter]);
if (isNaN(num)) return { invalid: true, prompt: argument.prompt };
if (argument.min && argument.min > num) return { invalid: true, prompt: argument.prompt };
if (argument.max && argument.max < num) return { invalid: true, prompt: argument.prompt };
//@ts-ignore
if (argument.toInteger) num = parseInt(num);
if (amount == 1) flags[argument.id] = num;
else if (flags[argument.id]) flags[argument.id].push(num);
else flags[argument.id] = [num];
break;
case "CHANNEL":
if (msgArgs[counter].startsWith("<#") && msgArgs[counter].endsWith(">")) channel = message.guild.channels.cache.get(msgArgs[counter].slice(2, -1));
else channel = message.guild.channels.cache.get(msgArgs[counter]);
if (!channel) return { invalid: true, prompt: argument.prompt };
if (argument.channelTypes && !argument.channelTypes.includes(channel.type)) return { invalid: true, prompt: argument.prompt };
if (amount == 1) flags[argument.id] = channel;
else if (flags[argument.id]) flags[argument.id].push(channel);
else flags[argument.id] = [channel];
break;
case "ROLE":
if (msgArgs[counter].startsWith("<@&") && msgArgs[counter].endsWith(">")) role = message.guild.roles.cache.get(msgArgs[counter].slice(3, -1));
else role = message.guild.roles.cache.get(msgArgs[counter]);
if (!role) return { invalid: true, prompt: argument.prompt };
if (argument.notBot && role.managed) return { invalid: true, prompt: argument.prompt };
if (amount == 1) flags[argument.id] = role;
else if (flags[argument.id]) flags[argument.id].push(role);
else flags[argument.id] = [role];
break;
case "AUTHOR_OR_MEMBER":
if (msgArgs[counter] && (msgArgs[counter].startsWith("<@") || msgArgs[counter].startsWith("<@!") && msgArgs[counter].endsWith(">"))) member = message.guild.member(msgArgs[counter].replace("<@", "").replace("!", "").replace(">", ""));
else member = message.guild.member(msgArgs[counter]);
if (!member) flags[argument.id] = message.member;
else flags[argument.id] = member;
if (argument.toUser) flags[argument.id] = flags[argument.id].user;
break;
case "MEMBER":
if ((msgArgs[counter].startsWith("<@") || msgArgs[counter].startsWith("<@!") && msgArgs[counter].endsWith(">"))) member = message.guild.member(msgArgs[counter].replace("<@", "").replace("!", "").replace(">", ""));
else member = message.guild.member(msgArgs[counter]);
if (!member) return { invalid: true, prompt: argument.prompt };
else {
if (argument.notBot && member.user.bot) return { invalid: true, prompt: argument.prompt };
if (argument.notSelf && member.id === message.author.id) return { invalid: true, prompt: argument.prompt };
if (argument.toUser) member = member.user;
if (amount == 1) flags[argument.id] = member;
else if (flags[argument.id]) flags[argument.id].push(member);
else flags[argument.id] = [member];
}
break;
case "ATTACHMENT":
if (message.attachments.size === 0) return { invalid: true, prompt: argument.prompt };
attach = message.attachments.filter(a => {
let accepted = false;
argument.attachmentTypes.forEach(type => {
if (a.proxyURL.endsWith(type)) accepted = true;
});
return accepted;
});
if (attach.size === 0 && argument.optional) return flags;
else if (attach.size === 0) return { invalid: true, prompt: argument.prompt };
flags[argument.id] = attach.first();
break;
case "TIME":
time = msgArgs.slice(counter).join("").match(/(\d*)(\D*)/g);
time.pop();
num = 0;
for (let i = 0; i < time.length; i++) {
try {
num += ms(time[i]);
} catch (e) {
return { invalid: true, prompt: argument.prompt };
}
}
if (argument.min && num < argument.min) return { invalid: true, prompt: argument.prompt };
if (argument.max && num > argument.max) return { invalid: true, prompt: argument.prompt };
flags[argument.id] = num;
break;
default:
//@ts-ignore
log("WARNING", "src/utils/utils.js", `processArguments: the argument type '${argument.type}' doesn't exist`);
}
counter++
}
}
return flags;
}
/**
* Function to glocally blacklist a user
* @param {import('../typings.d').myClient} client - The client object (because the schemas are stored to it)
* @param {string} userID - The ID of the user to whitelist
*/
async function blacklist(client, userID) {
if (client.blacklistCache.has(userID)) return;
//@ts-ignore
await client.DBConfig.findByIdAndUpdate('blacklist', { $push: { 'blacklisted': userID } }, { new: true, upsert: true, setDefaultsOnInsert: true });
client.blacklistCache.add(userID);
}
/**
* Function to globally whitelist a previously blacklisted user
* @param {import('../typings.d').myClient} client - The client object (because the schemas are stored to it)
* @param {string} userID - The ID of the user to whitelist
*/
async function whitelist(client, userID) {
if (!client.blacklistCache.has(userID)) return;
await client.DBConfig.findByIdAndUpdate('blacklist', { $pull: { 'blacklisted': userID } }, { new: true, upsert: true, setDefaultsOnInsert: true });
client.blacklistCache.delete(userID);
}
/**
* Function to automatically send paginated embeds and switch between the pages by listening to the user reactions
* @param {import('discord.js').Message} message - Used to send the paginated message to the channel, get the user, etc.
* @param {MessageEmbed[]} embeds - The array of embeds to switch between
* @param {object} [options] - Optional parameters
* @param {number} [options.time] - The max time for createReactionCollector after which all of the reactions disappear
* @example Examples can be seen in `src/utils/utils.md`
*/
async function paginate(message, embeds, options) {
try {
const pageMsg = await message.channel.send({ embed: embeds[0] });
for (const emote of reactions) {
await pageMsg.react(emote);
await delay(750);
}
let pageIndex = 0;
let time = 30000;
const filter = (reaction, user) => {
return reactions.includes(reaction.emoji.name) && user.id === message.author.id;
};
if (options) {
if (options.time) time = options.time;
};
const collector = pageMsg.createReactionCollector(filter, { time: time });
collector.on('collect', async (reaction, user) => {
try {
await reaction.users.remove(user)
if (reaction.emoji.name === '⏩') {
pageIndex = embeds.length - 1;
await pageMsg.edit({ embed:embeds[pageIndex] });
} else if (reaction.emoji.name === '▶️') {
if (pageIndex < embeds.length - 1) {
pageIndex++;
await pageMsg.edit({ embed: embeds[pageIndex] });
} else {
pageIndex = 0;
await pageMsg.edit({ embed: embeds[pageIndex] });
}
} else if (reaction.emoji.name === '⏸️') {
await pageMsg.delete();
} else if (reaction.emoji.name === '⏪') {
pageIndex = 0;
await pageMsg.edit({ embed: embeds[pageIndex] });
} else if (reaction.emoji.name === '◀️') {
if (pageIndex > 0) {
pageIndex--;
await pageMsg.edit({ embed: embeds[pageIndex] });
} else {
pageIndex = embeds.length - 1;
await pageMsg.edit({ embed: embeds[pageIndex] });
}
} else if (reaction.emoji.name === '🔢') {
let msg = await getReply(message, { time: 7500, regexp: /^\d+$/ });
if (!msg) return;
let num = parseInt(msg.content);
if (num > embeds.length) num = embeds.length - 1;
else num--;
pageIndex = num;
await pageMsg.edit({ embed: embeds[pageIndex] });
}
} catch (e) {
return;
}
});
collector.on('end', async () => {
try {
await pageMsg.reactions.removeAll()
} catch (e) {
//
}
});
} catch (e) {
return;
}
}
/**
* Function to await a reply from a specific user.
* @param {import('discord.js').Message} message - The message to listen to
* @param {object} [options] - Optional parameters
* @param {number} [options.time] - The max time for awaitMessages
* @param {import('discord.js').User} [options.user] - The user to listen to messages to
* @param {string[]} [options.words] - Optional accepted words, will aceept any word if not provided
* @param {RegExp} [options.regexp] - Optional RegExp to accept user input that matches the RegExp
* @return {Promise<import('discord.js').Message>} Returns the `message` sent by the user if there was one, returns `false` otherwise.
* @example const reply = await getReply(message, { time: 10000, words: ['yes', 'y', 'n', 'no'] })
*/
async function getReply(message, options) {
let time = 30000;
let user = message.author;
let words = [];
if (options) {
if (options.time) time = options.time;
if (options.user) user = options.user;
if (options.words) words = options.words;
}
const filter = msg => {
return msg.author.id === user.id
&& (words.length === 0 || words.includes(msg.content.toLowerCase()))
&& (!options || !options.regexp || options.regexp.test(msg.content))
}
const msgs = await message.channel.awaitMessages(filter, { max: 1, time: time });
if (msgs.size > 0) return msgs.first();
return;
}
/**
* Return an random integer between `min` and `max` (both inclusive)
* @param {number} min - The lower bound
* @param {number} max - The upper bound
* @return {number}
* @example const rand = randomRange(0, 10)
*/
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Function to set a timeout
* @param {number} ms - Time to wait in milliseconds
* @return {promise}
* @example await delay(5000)
*/
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Function to convert milliseconds into readable time
* @param {number} ms - The time in
* @return {string} Readable time as a string
*/
function msToTime(ms) {
let time = "";
let n = 0;
if (ms >= 31536000000) {
n = Math.floor(ms / 31536000000);
time = `${n}y `;
ms -= n * 31536000000;
}
if (ms >= 2592000000) {
n = Math.floor(ms / 2592000000);
time += `${n}mo `;
ms -= n * 2592000000;
}
if (ms >= 604800000) {
n = Math.floor(ms / 604800000);
time += `${n}w `;
ms -= n * 604800000;
}
if (ms >= 86400000) {
n = Math.floor(ms / 86400000);
time += `${n}d `;
ms -= n * 86400000;
}
if (ms >= 3600000) {
n = Math.floor(ms / 3600000);
time += `${n}h `;
ms -= n * 3600000;
}
if (ms >= 60000) {
n = Math.floor(ms / 60000);
time += `${n}m `;
ms -= n * 60000;
}
n = Math.ceil(ms / 1000);
time += n === 0 ? '' : `${n}s`;
return time.trimEnd();
}
/**
* Function to get all missing permissions of a GuildMember
* @param {import('discord.js').GuildMember} member - The guild member whose missing permissions you want to get
* @param {import('discord.js').PermissionString[]} perms - The permissions you want to check for
* @return {string} Readable string containing all missing permissions
*/
function missingPermissions(member, perms){
const missingPerms = member.permissions.missing(perms)
.map(str=> `\`${str.replace(/_/g, ' ').toLowerCase().replace(/\b(\w)/g, char => char.toUpperCase())}\``);
return missingPerms.length > 1 ?
`${missingPerms.slice(0, -1).join(", ")} and ${missingPerms.slice(-1)[0]}` :
missingPerms[0];
}
/**
* Function to shorten down console logs
* @param {('SUCCESS'|'WARNING'|'ERROR')} type - The type of log (SUCCESS, WARNING, ERROR)
* @param {string} path - The path where the console log is coming from
* @param {string} text - The message to be displayed
*/
function log(type, path, text) {
console.log(`\u001b[36;1m<bot-prefab>\u001b[0m\u001b[34m [${path}]\u001b[0m - ${consoleColors[type]}${text}\u001b[0m`);
}
/**
* Custom embed class
* @param {object} data
* @param {import('../typings.d').myClient} data.client
* @param {string} data.userID - The ID of the user you're constructing this embed for
*/
async function CustomEmbed(data) {
let userInfo = await getUserInfo(data.client, data.userID);
const embed = new MessageEmbed()
.setColor(embedColors[userInfo.embedColor]);
return embed;
}
/**
* @param {import('../typings.d').myClient} client
* @param {import('../typings.d').Command} command - The command you want to set a cooldown for
* @param {import('discord.js').Message} message - The guild ID the command is executed in
* @return {(number|undefined)}
*/
function getCooldown(client, command, message) {
let guildInfo = client.guildInfoCache.get(message.guild.id);
let cd = command.cooldown;
if (guildInfo.commandCooldowns && guildInfo.commandCooldowns[command.name]) {
let roles = Object.keys(guildInfo.commandCooldowns[command.name]);
let highestRole = message.member.roles.cache.filter(role => roles.includes(role.id)).sort((a, b) => b.position - a.position).first();
if (highestRole) cd = guildInfo.commandCooldowns[command.name][highestRole.id] / 1000;
}
return cd;
}
/**
*
* @param {import('../typings.d').myClient} client
* @param {import('../typings.d').Command} command
* @param {import('discord.js').Message} message
*/
function setCooldown(client, command, message) {
const cd = getCooldown(client, command, message);
if (!cd) return;
let cooldowns;
if (typeof command.globalCooldown === 'undefined' || command.globalCooldown) {
if (!client.globalCooldowns.has(command.name)) client.globalCooldowns.set(command.name, new Collection());
cooldowns = client.globalCooldowns;
} else {
if (!client.serverCooldowns.has(message.guild.id)) client.serverCooldowns.set(message.guild.id, new Collection());
cooldowns = client.serverCooldowns.get(message.guild.id);
if (!cooldowns.has(command.name)) cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = cd * 1000;
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
}
/**
* @param {import('../typings.d').myClient} client
* @param {string} guildID
*/
async function getGuildInfo(client, guildID) {
let guildInfo = client.guildInfoCache.get(guildID);
if (!guildInfo) {
guildInfo = await client.DBGuild.findByIdAndUpdate(guildID, { }, { new: true, upsert: true, setDefaultsOnInsert: true });
client.guildInfoCache.set(guildID, guildInfo);
}
return guildInfo;
}
/**
* @param {import('../typings.d').myClient} client
* @param {string} userID
*/
async function getUserInfo(client, userID) {
let userInfo = client.userInfoCache.get(userID);
if (!userInfo) {
userInfo = await client.DBUser.findByIdAndUpdate(userID, { }, { new: true, upsert: true, setDefaultsOnInsert: true });
client.userInfoCache.set(userID, userInfo);
}
return userInfo;
}
module.exports = {
processArguments, blacklist, whitelist, paginate, log,
getReply, randomRange, delay, msToTime, missingPermissions,
CustomEmbed, getCooldown, setCooldown, getGuildInfo,
getUserInfo
}