/
index.js
384 lines (335 loc) · 19.3 KB
/
index.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
// Utilities
const storagePath = require('./config.json')['storage-path'];
const botPath = require('./config.json')['bot-path'];
const getsDiscord = require('./functions/utilities/getsDiscord');
const updateLine = require('./functions/utilities/updateLine');
const logger = require('./functions/utilities/logger');
let configs = require('./functions/utilities/getConfigs')();
const isDisabled = require('./functions/utilities/isDisabled')
const getCooldown = require(`${storagePath}/profiles/handlers/getCooldown`);
const cooldownMessage = require(`${storagePath}/messages/cooldown`);
const disabledMessage = require(`${storagePath}/messages/disabledCommands`);
const buttonPerms = require(`${storagePath}/messages/buttonPerms`);
const suOnly = require(`${storagePath}/messages/suOnly`);
let superusers = require('./functions/utilities/getSu')(storagePath);
logger.newFile();
updateLine(logger.log('Starting bot: Importing packages', ['Starting']));
// Import packages
const fs = require('fs');
const yaml = require('js-yaml');
const PasteClient = require("pastebin-api").default;
const paste = new PasteClient("mZVKJXmQ66XPQaGiYVd_XI3IQ7oopTNa");
updateLine(logger.log('Loading configurations', ['Starting']));
// Read preferences config file
let preferences;
try {
preferences = yaml.load(fs.readFileSync(`${storagePath}/config/master/preferences.yml`, 'utf8'));
} catch (error) {
console.error('Did you download the config files?')
throw error;
}
// Callbacks
let commandCallbacks = {
updateSu: (newSu) => {
superusers = newSu;
},
updateConfig: (newConfig) => {
configs = newConfig;
}
};
updateLine(logger.log('Loading environment variables', ['Starting']));
{
// Load environment variables
const result = require('dotenv').config();
if (result.error) {
console.error('dotenv: did you create a .env file?');
throw result.error;
}
}
// Functions
function readyPrint() {
updateLine('');
console.log(`${logger.log(`Startup completed\nReady! Logged in as ${client.user.tag}`, ['Starting/Completed'])}`);
}
// Import Discord API
const {
Client,
Collection,
Intents,
MessageEmbed
} = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES,
Intents.FLAGS.GUILDS]
});
let registerList = ['on', 'once']
let listeners = {
system: {},
on: {},
once: {},
};
updateLine(logger.log('Starting bot: Getting commands', ['Starting']));
// Read files in 'bot_modules' directory
client.commands = new Collection();
const commandCategories = fs.readdirSync(`${storagePath}/bot_modules`);
for (let commandCategory in commandCategories) {
commandCategory = commandCategories[commandCategory];
const commandFiles = fs.readdirSync(`${storagePath}/bot_modules/${commandCategory}`).filter(fileName => fileName.endsWith('.js'));
for (let commandFile of commandFiles) {
const file = require(`${storagePath}/bot_modules/${commandCategory}/${commandFile}`);
if (file.isCommand) {
client.commands.set(file.data.name, file);
}
if (file.listeners) {
for (const listener of file.listeners) {
if (listener.enabled) {
if (listeners[listener.data.type][listener.data.value] === undefined) {
listeners[listener.data.type][listener.data.value] = {
blocking: [],
nonblocking: [],
}
}
const pushTo = {
name: listener.name,
file: `${commandCategory}/${commandFile}`,
function: listener.function,
}
listeners[listener.data.type][listener.data.value][listener.blocking ? 'blocking' : 'nonblocking'].push(pushTo);
}
}
}
}
}
for (let type in registerList) {
type = registerList[type];
for (const key in listeners[type]) {
client[type](key, (data) => {
for (const i in listeners[type][key].nonblocking) {
setTimeout(() => {
try {
listeners[type][key].nonblocking[i].function(data);
} catch (err) {
err.stack = `Error loction: ${listeners[type][key].nonblocking[i].file} - ${listeners[type][key].nonblocking[i].name}\n${err.stack}`;
console.error(logger.log(err.stack, ['Error/Listener']));
}
}, 0);
}
for (const i in listeners[type][key].blocking) {
try {
listeners[type][key].blocking[i].function(data);
} catch (err) {
err.stack = `Error loction: ${listeners[type][key].nonblocking[i].file} - ${listeners[type][key].nonblocking[i].name}\n${err.stack}`;
console.error(logger.log(err.stack, ['Error/Listener']));
}
}
});
}
}
updateLine(logger.log('Connecting to Discord', ['Starting']));
// On ready
client.once('ready', client => {
if (preferences.onStart.sendMessages.enabled) {
updateLine(logger.log('Sending startup messages', ['Starting']));
const users = preferences.onStart.sendMessages.users;
const channels = preferences.onStart.sendMessages.channels;
const totalMessages = users.length + channels.length;
let sent = 0;
let success = 0;
let failed = 0;
const { messageUser, messageChannel } = require(`${storagePath}/messages/startup`);
// send startup messages to users
for (const i in users) {
setTimeout(() => {
getsDiscord.getUser(client, users[i], function (user) {
user.send(messageUser({ client, user, MessageEmbed })).then(() => {
sent++;
success++;
updateLine(logger.log(`Sending startup messages [Success: ${success} | Failed: ${failed} | Progress: ${sent}/${totalMessages}]`, ['Starting']));
if (sent === totalMessages) {
readyPrint();
}
}).then(() => { }).catch(_ => {
sent++;
failed++;
updateLine(logger.log(`Sending startup messages [Success: ${success} | Failed: ${failed} | Progress: ${sent}/${totalMessages}]`, ['Starting']));
if (sent === totalMessages) {
readyPrint();
}
});
});
}, 0);
}
// send startup messages to channels
for (i in channels) {
setTimeout(() => {
getsDiscord.getChannel(client, channels[i], function (channel) {
channel.send(messageChannel({ client, channel, MessageEmbed })).then(() => {
sent++;
success++;
updateLine(logger.log(`Sending startup messages [Success: ${success} | Failed: ${failed} | Progress: ${sent}/${totalMessages}]`, ['Starting']));
if (sent === totalMessages) {
readyPrint();
}
}).catch(_ => {
sent++;
failed++;
updateLine(logger.log(`Sending startup messages [Success: ${success} | Failed: ${failed} | Progress: ${sent}/${totalMessages}]`, ['Starting']));
if (sent === totalMessages) {
readyPrint();
}
});
});
}, 0);
}
} else {
readyPrint();
}
});
client.on('interactionCreate', async (inter) => {
if (!inter.user.bot) {
let su = false;
if (superusers.master.currentOn.includes(inter.user.id)) {
su = true;
} else if (inter.guild !== null && superusers[inter.guild.id] !== undefined && superusers[inter.guild.id].currentOn.includes(inter.user.id)) {
su = true;
}
let guildID;
if (inter.guild) {
guildID = inter.guild.id;
} else {
guildID = 'dm';
}
if (inter.isCommand()) {
const commandName = inter.commandName;
const command = client.commands.get(commandName);
try {
if (inter.options['_subcommand'] === null) {
console.log(logger.log(`User: ${inter.user.username}#${inter.user.discriminator} | User ID: ${inter.user.id} | Command: ${commandName} | Superuser: ${su}`, ['Interaction/Command']));
if (su) {
await command.execute(inter, { client, storagePath, logger, botPath, superusers, paste }, commandCallbacks);
} else if (configs[(
configs[guildID] === undefined || configs[guildID].commands === undefined || configs[guildID].commands[commandName] === undefined || configs[guildID].commands[commandName]['su-only'] === undefined
) ? 'master' : guildID].commands[commandName]['su-only']) {
inter.reply({ ephemeral: true, embeds: [suOnly()] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
const disabled = isDisabled({ configs, commandName, guildID, type: 'command' });
if (disabled.disabled) {
inter.reply({ ephemeral: true, embeds: [disabledMessage({ type: disabled.reason })] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
const cooldown = getCooldown(inter.user.id, { configs, storagePath, botPath, commandName, type: 'command', run: true, guildID });
if (cooldown.cooldown > 0) {
inter.reply({ ephemeral: true, embeds: [cooldownMessage(cooldown.cooldown, cooldown.serverCooldown, botPath, 'command')] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
await command.execute(inter, { client, storagePath, logger, botPath, superusers, paste }, commandCallbacks);
}
}
}
} else {
const subcommandName = inter.options['_subcommand'];
console.log(logger.log(`User: ${inter.user.username}#${inter.user.discriminator} | User ID: ${inter.user.id} | Command: ${commandName}/${subcommandName} | Superuser: ${su}`, ['Interaction/Command']));
if (su) {
await command.subcommands[subcommandName](inter, { client, storagePath, logger, botPath, superusers, paste }, commandCallbacks);
} else if (configs[(
configs[guildID] === undefined || configs[guildID].commands === undefined || configs[guildID].commands[commandName] === undefined || configs[guildID].commands[commandName].subcommands === undefined || configs[guildID].commands[commandName].subcommands[subcommandName] === undefined || configs[guildID].commands[commandName].subcommands[subcommandName]['su-only'] === undefined
) ? 'master' : guildID].commands[commandName].subcommands[subcommandName]['su-only']) {
inter.reply({ ephemeral: true, embeds: [suOnly()] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
const disabled = isDisabled({ configs, commandName, guildID, subcommandName: inter.options['_subcommand'], type: 'subcommand' });
if (disabled.disabled) {
inter.reply({ ephemeral: true, embeds: [disabledMessage({ type: disabled.reason })] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
const cooldown = getCooldown(inter.user.id, { configs, storagePath, botPath, commandName, subcommandName, type: 'subcommand', run: true, guildID });
if (cooldown.cooldown > 0) {
inter.reply({ ephemeral: true, embeds: [cooldownMessage(cooldown.cooldown, cooldown.serverCooldown, botPath, 'command')] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
await command.subcommands[subcommandName](inter, { client, storagePath, logger, botPath, superusers, paste }, commandCallbacks);
}
}
}
}
} catch (err) {
console.error(logger.log(err.stack, ['Error/Command', commandName]));
}
} else if (inter.isButton()) {
let args;
try {
console.log(logger.log(`User: ${inter.user.username}#${inter.user.discriminator} | User ID: ${inter.user.id} | CustomID: ${inter.customId} | Superuser: ${su}`, ['Interaction/Button']));
args = inter.customId.split('|');
if (su) {
client.commands.get(args[0]).buttons[args[1]](inter, { client, storagePath, logger, userId: args[2], botPath, superusers, paste, args: args.slice(3) });
} else if (configs[(
configs[guildID] === undefined || configs[guildID].commands === undefined || configs[guildID].commands[args[0]] === undefined || configs[guildID].commands[commandName][args[0]].buttons === undefined || configs[guildID].commands[commandName][args[0]].buttons[args[1]] === undefined || configs[guildID].commands[commandName][args[0]].buttons[args[1]]['su-only'] === undefined
) ? 'master' : guildID].commands[args[0]].buttons[args[1]]['su-only']) {
inter.reply({ ephemeral: true, embeds: [suOnly()] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
if (args[2] === '_' || args[2] === inter.user.id) {
let guildID;
if (inter.guild) {
guildID = inter.guild.id;
} else {
guildID = 'dm';
}
const disabled = isDisabled({ configs, commandName: args[0], guildID, buttonName: args[1], type: 'button' });
if (disabled.disabled) {
inter.reply({ ephemeral: true, embeds: [disabledMessage({ type: disabled.reason })] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
const cooldown = getCooldown(inter.user.id, { configs, logger, storagePath, botPath, commandName: args[0], buttonName: args[1], type: 'button', run: true, guildID });
if (cooldown.cooldown > 0) {
inter.reply({ ephemeral: true, embeds: [cooldownMessage(cooldown.cooldown, cooldown.serverCooldown, botPath, 'button')] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
if (args[2] === '_' || su || args[2] === inter.user.id) {
client.commands.get(args[0]).buttons[args[1]](inter, { client, storagePath, userId: args[2], logger, botPath, superusers, paste, args: args.slice(3) });
}
}
}
} else {
inter.reply({ ephemeral: true, embeds: [buttonPerms()] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
}
}
} catch (err) {
console.error(logger.log(err.stack, ['Error/Button', `${args[0]}/${args[1]}`]));
}
} else if (inter.isSelectMenu()) {
let values = inter.values[0].split('|');
let args = inter.customId.split('|');
try {
if (su) {
client.commands.get(args[0]).selectmenus[args[1]](inter, { client, storagePath, logger, userId: args[2], botPath, superusers, paste, args: values });
} else if (configs[(
configs[guildID] === undefined || configs[guildID].commands === undefined || configs[guildID].commands[args[0]] === undefined || configs[guildID].commands[commandName][args[0]].selectmenus === undefined || configs[guildID].commands[commandName][args[0]].selectmenus[args[1]] === undefined || configs[guildID].commands[commandName][args[0]].selectmenus[args[1]]['su-only'] === undefined
) ? 'master' : guildID].commands[args[0]].selectmenus[args[1]]['su-only']) {
inter.reply({ ephemeral: true, embeds: [suOnly()] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
console.log(logger.log(`User: ${inter.user.username}#${inter.user.discriminator} | User ID: ${inter.user.id} | Value: ${inter.customId}`, ['Interaction/SelectMenu']));
if (args[2] === '_' || args[2] === inter.user.id) {
if (inter.guild) {
guildID = inter.guild.id;
} else {
guildID = 'dm';
}
}
const disabled = isDisabled({ configs, commandName: args[0], guildID, selectmenuName: args[1], type: 'selectmenu' });
if (disabled.disabled) {
inter.reply({ ephemeral: true, embeds: [disabledMessage({ type: disabled.reason })] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
const cooldown = getCooldown(inter.user.id, { configs, logger, storagePath, botPath, commandName: args[0], selectmenuName: args[1], type: 'selectmenu', run: true, guildID });
if (cooldown.cooldown > 0) {
inter.reply({ ephemeral: true, embeds: [cooldownMessage(cooldown.cooldown, cooldown.serverCooldown, botPath, 'selectmenu')] }).then(() => { }).catch(err => { console.log(logger.log(err.stack, ['Error/DiscordAPI'])) });
} else {
if (args[2] === '_' || args[2] === inter.user.id) {
client.commands.get(args[0]).selectmenus[args[1]](inter, { client, storagePath, logger, userId: args[2], botPath, superusers, paste, args: values });
}
}
}
}
} catch (err) {
console.error(logger.log(err.stack, ['Error/SelectMenu', `${args[0]}/${args[1]}`]));
}
}
}
});
// Log on to Discord
client.login(process.env.BOT_TOKEN)