-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
465 lines (424 loc) · 16.5 KB
/
bot.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
"use strict";
import config from "./config.json" assert { type: "json" };
import { Client, GatewayIntentBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, Options, ActivityType, Partials } from 'discord.js';
import { message_embed, sleep, server_count, stamp_console } from "./shared.js";
import { readdirSync } from 'node:fs';
import { createPool } from 'mysql';
import { promisify } from 'util';
import { generate_sentences, expand_set } from './engine.js';
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages],
partials: [Partials.Channel],
makeCache: Options.cacheWithLimits({
...Options.DefaultMakeCacheSettings,
ReactionManager: 0,
GuildMemberManager: {
maxSize: 1,
keepOverLimit: member => member.id === client.user.id
},
GuildMessageManager: {
maxSize: 1,
keepOverLimit: message => message.author.id === client.user.id
},
UserManager: {
maxSize: 1,
keepOverLimit: user => user.id === client.user.id
},
MessageManager: {
maxSize: 1,
keepOverLimit: message => message.author.id === client.user.id
},
})
});
let dead = false;
let loaded = false;
let exitting = false;
let disconnected = false;
let db;
if (config.database.socket !== undefined) {
db = createPool({
user: config.database.username,
password: config.database.password,
database: config.database.database,
socketPath: config.database.socket
});
} else {
db = createPool({
port: config.database.port,
host: config.database.address,
user: config.database.username,
password: config.database.password,
database: config.database.database
});
}
const query = promisify(db.query).bind(db);
db.async_query = query;
const command_responses = {};
const button_responses = {};
const button_files = readdirSync('./buttons').filter(file => file.endsWith('.js'));
const commandFiles = readdirSync('./commands').filter(file => file.endsWith('.js'));
const author = { name: "Aurillium", iconURL: "https://avatars.githubusercontent.com/u/57483028", url: "https://github.com/Aurillium" };
for (const file of button_files) {
import("./buttons/" + file).then((module) => {
button_responses[file.slice(0, -3)] = module.response
});
}
let commandsEmbed = new EmbedBuilder()
.setColor("#FF8758")
.setTitle("Command List")
.setDescription("Here's a list of commands for Pronouns Bot:\n(Required arguments look like `<this>` and optional ones look like `[this]`)")
.setAuthor(author);
for (const file of commandFiles) {
import("./commands/" + file).then((command) => {
if (!config.testing_mode && command.testing) return;
command_responses[command.data.name] = command.response;
let command_string = "/" + command.data.name;
for (const option of command.data.options) {
let j = option.toJSON();
if (j.required) {
command_string += " <" + option.toJSON().name + ">";
} else {
command_string += " [" + option.toJSON().name + "]";
}
}
commandsEmbed = commandsEmbed.addFields({
name: command.data.name,
value: command.doc + "\n**Usage:** `" + command_string + "`\n** **"
});
});
}
command_responses["commands"] = async function(interaction) {
await interaction.reply({embeds: [commandsEmbed]});
}
async function change_status() {
let delay = 1000 * 60;
if (config.testing_mode) {
delay = 1000 * 4;
}
while (true) {
// Only change status when all shards are loaded
if (loaded) {
client.user.setStatus('online');
if (!exitting) {
client.user.setActivity('/help 🏳️🌈🏳️⚧️', { type: ActivityType.Listening });
} else break;
await sleep(delay);
if (!exitting) {
client.user.setActivity((await server_count(client)).toString() + " servers 🏳️🌈🏳️⚧️", { type: ActivityType.Watching });
} else break;
await sleep(delay);
if (!exitting) {
client.user.setActivity("shard #" + client.shard_id + " 🏳️🌈🏳️⚧️", { type: ActivityType.Watching });
} else break;
}
await sleep(delay);
}
}
client.on('ready', () => {
client.user.setActivity('Starting... 🏳️🌈🏳️⚧️', { type: ActivityType.Playing });
client.user.setStatus('idle')
change_status().catch(e => {
console.log("Status change failed:");
console.log(e);
});
});
client.on('interactionCreate', async interaction => {
if (dead) return;
try {
// Command timings
let initial = performance.now();
if (interaction.isCommand()) {
if (interaction.commandName in command_responses) {
await command_responses[interaction.commandName](interaction, db);
console.log(interaction.commandName + " took " + (performance.now() - initial).toString() + "ms");
} else {
await interaction.reply({embeds: [message_embed("That command isn't loaded in this version!", "#FF0000")]})
}
} else if (interaction.isButton()) {
const [handler_name, ...rest] = interaction.customId.split(":");
if (handler_name in button_responses) {
await button_responses[handler_name](interaction, rest.join(":"), db);
console.log(interaction.customId + " took " + (performance.now() - initial).toString() + "ms");
} else {
await interaction.reply({embeds: [message_embed(`That button isn't loaded in this version!\nCustom ID: "${interaction.customId}"`, "#FF0000")]})
}
}
} catch (error) {
console.warn("=== ERROR ===");
console.warn("Error: " + error.message);
if (interaction.isCommand()) {
console.warn("Interaction: Command");
console.warn(interaction);
// Fix after assignment
/*console.warn(" Arguments:");
for (const option of interaction.command.options) {
let out = "";
if (option.type === ApplicationCommandOptionType.Boolean) {
out = interaction.getBoolean
}
console.warn(" " + option.name + ": " + );
}*/
}
if (interaction.isButton()) {
console.warn("Interaction: Button");
console.warn(" Custom ID: " + interaction.customId);
}
console.warn("Trace: " + error.stack);
// Let's not report intentional crashes
if (error.message === "Intentional crash") {
error.stack = "__Intentional crash, don't report me pls!__\n\n" + error.stack;
}
let error_embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Oops!")
.setAuthor(author)
.setDescription("**An error has occcurred.**\nPlease share the following information (along with what you were doing at the time) in a new issue on [GitHub](https://github.com/Aurillium/PronounBot/issues/new), or on our [support server](https://discord.gg/ZnRzV469rJ), and we will look into it and resolve it.\n\n**Stack Trace:**\n" + error.stack)
try {
await interaction.reply({embeds: [error_embed]});
} catch (error) {
try {
await interaction.channel.send({embeds: [error_embed]});
} catch (error) {
console.warn("Failed to send error message to channel.");
console.warn("Error: " + error.message);
}
}
// If the crash was intentional, escalate it after handling
if (error.message === "Intentional crash") {
throw error;
}
}
});
client.on('messageCreate', async message => {
if (dead) return;
try {
// Command timings
let initial = performance.now();
if (message.mentions.parsedUsers === null) {
if (message.content == null) return;
} else {
if (!message.mentions.parsedUsers.map(user => user.id).includes(client.user.id)) return;
}
if (message.author.bot) return;
const deleter = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId("delete_try:" + message.author.id)
.setLabel("Delete")
.setEmoji("🗑️")
.setStyle(ButtonStyle.Danger),
);
let raw_names = [];
let raw_terms = [];
let raw_sets = [];
let args = {names: [], sets: [], terms: [], plural: null, hidden: null, all_pronouns: false, no_pronouns: false, random_pronouns: false};
let plural_warned = false;
//let hidden_warned = false;
for (const line of message.content.replaceAll(client.user.toString(), "").split("\n")) {
if (!line.includes(":")) continue;
let [key, value] = line.split(":", 2);
key = key.trim().toLowerCase();
value = value.trim().toLowerCase();
if (key === "name" || key === "names" || key === "n") {
for (const name of value.split(new RegExp("[/,]"))) {
if (name.length > 50) {
await message.reply({embeds: [message_embed("Names must be at most 50 characters in length.")]});
return;
}
raw_names.push(name.trim());
}
} else if (key === "term" || key === "terms" || key === "t") {
for (const term of value.split(new RegExp("[/, ]"))) {
if (term.length > 50) {
await message.reply({embeds: [message_embed("Terms must be at most 50 characters in length.")]});
return;
}
raw_terms.push(term.trim());
}
} else if (key === "pronouns" || key === "sets" || key === "set" || key === "p") {
if (value === "all" || value === "a") {
if (args.no_pronouns || args.random_pronouns) {
await message.reply({embeds: [message_embed("You can only specify all, no *or* random pronouns, not multiple.")], components: [deleter]});
return;
}
args.all_pronouns = true;
} else if (value === "none" || value === "no" || value === "n") {
if (args.all_pronouns || args.random_pronouns) {
await message.reply({embeds: [message_embed("You can only specify all, no *or* random pronouns, not multiple.")], components: [deleter]});
return;
}
args.no_pronouns = true;
} else if (value === "random" || value === "rand" || value === "r") {
if (args.all_pronouns || args.no_pronouns) {
await message.reply({embeds: [message_embed("You can only specify all, no *or* random pronouns, not multiple.")], components: [deleter]});
return;
}
args.random_pronouns = true;
} else {
for (const set of value.split(new RegExp("[, ]"))) {
raw_sets.push(set.trim());
}
}
} else if (key === "plural" || key === "pl") {
if (args.plural !== null && !plural_warned) {
await message.reply({embeds: [message_embed("Muliple 'plural' values detected. Please only use one.")], components: [deleter]});
return;
}
if (value === "y" || value === "yes" || value === "t" || value === "true") {
args.plural = true;
} else if (value === "n" || value === "no" || value === "f" || value === "false") {
args.plural = false;
} else {
await message.reply({embeds: [message_embed("Invalid 'plural' option detected. Only 'yes', 'no' , 'true', 'false', or their abbreviations are valid values.")], components: [deleter]});
return;
}
} else {
await message.reply({embeds: [message_embed("Invalid key: '" + key + "'. It will be ignored.")], components: [deleter]});
}
}
for (const name of raw_names) {
if (name !== "" && !args.names.includes(name)) args.names.push(name);
}
for (const term of raw_terms) {
if (term !== "" && !args.terms.includes(term)) args.terms.push(term);
}
if (!args.no_pronouns && !args.all_pronouns && !args.random_pronouns) {
for (const raw_set of raw_sets) {
if (raw_set !== "") {
let set = expand_set(raw_set);
if (set === null) {
await message.reply({embeds: [message_embed("Pronoun sets must have either four or five pronouns (check /help for more information): '" + raw_set + "'.")], components: [deleter]});
return;
}
// Loop over only the entries which are strings
for (const pronoun of set.slice(0, -1)) {
if (pronoun.length > 20) {
await message.reply({embeds: [message_embed("Pronouns must be at most 20 characters in length.")]});
return;
}
}
if (!args.sets.map(element => element.join("/")).includes(set.join("/"))) {
args.sets.push(set);
}
}
}
}
if (args.no_pronouns && args.sets.length !== 0) {
await message.reply({embeds: [message_embed("Cannot use no pronouns and specific sets at the same time.")], components: [deleter]});
return;
} else if (args.random_pronouns && args.sets.length !== 0) {
await message.reply({embeds: [message_embed("Cannot use a random pronoun set and specific sets at the same time.")], components: [deleter]});
return;
}
// ALL ERRORS SHOULD BE DEALT WITH BY HERE
const response_text = args.names.length === 0 ? "How do these look?" : "How do these look [name]?";
let result;
if (args.all_pronouns || args.random_pronouns) {
result = await db.async_query("SELECT Subjective, Objective, Possessive, Possessive2, Reflexive, Plural FROM Sets");
}
let sentences = "";
if (args.no_pronouns) {
sentences = await generate_sentences([], args.names, db, response_text);
} else if (args.all_pronouns) {
let sets = [];
for (const row of result) {
sets.push([row.Subjective, row.Objective, row.Possessive, row.Possessive2, row.Reflexive, row.Plural]);
}
sentences = await generate_sentences(sets.concat(args.sets), args.names, db, response_text);
} else if (args.random_pronouns) {
let sets = [];
for (const row of result) {
sets.push([row.Subjective, row.Objective, row.Possessive, row.Possessive2, row.Reflexive, row.Plural]);
}
sentences = await generate_sentences([sets[Math.floor(Math.random() * sets.length)]], args.names, db, "The set I chose was **[subjective]/[objective]/[possessive]/[possessive2]/[reflexive]**:");
} else {
sentences = await generate_sentences(args.sets, args.names, db, response_text);
}
// NOT HIDDEN FOR NOW
if (args.hidden && 0) {
const dm = await message.author.createDM();
await dm.send({content: "`" + JSON.stringify(args) + "`", components: [deleter]})
} else {
await message.reply({content: sentences, components: [deleter]});
}
// Log time taken to execute command
console.log("@command took " + (performance.now() - initial).toString() + "ms");
} catch (error) {
if (error.message === "Missing Permissions") {
return; // Nothing we can do
}
if (error.message === "Invalid Form Body") {
// > 4000 char messages shouldn't be possible anymore so this would be odd
// We did receive a system message though and it would be good to log that
}
console.warn("=== ERROR ===");
console.warn("Error: " + error.message);
console.warn("Command Content: " + message.content);
// Maybe later add the parsed parameters?
console.warn("Trace: " + error.stack);
// Inform user as well
try {
let error_embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Oops!")
.setAuthor(author)
.setDescription("**An error has occcurred.**\nPlease share the following information (along with what you were doing at the time) in a new issue on [GitHub](https://github.com/Aurillium/PronounBot/issues/new), or on our [support server](https://discord.gg/ZnRzV469rJ), and we will look into it and resolve it.\n\n**Stack Trace:**\n" + error.stack)
await message.reply({embeds: [error_embed]});
} catch (second_error) {
console.warn("While trying to send the error to the chat, a second error occurred.");
console.warn("Error: " + error.message);
console.warn("Trace: " + error.stack);
}
}
});
process.on("message", message => {
if (!message.type) return false;
if (dead) return;
// Messages without the type property aren't our concern
// Likewise don't include the shard_id message because it's
// - Easy to test
// - Won't have the console stamp
if (message.type !== "shard_id") {
console.log("Message received: ", message);
}
if (message.type == "shard_id") {
// When the shard logs in, the manager sends it its ID
// for its console stamp
stamp_console('SHARD ' + message.data.toString());
client.shard_id = message.data;
console.log(`Logged in as ${client.user.tag}!`);
} else if (message.type == "loaded") {
// When all shards are loaded we can communicate with the
// shard manager
loaded = true;
} else if (message.type == "exit") {
// On a controlled exit we should get a message telling us
// to hang until the manager exits
onExit().then(() => {
console.log("Shard exited.");
process.exit();
}).catch(error => {
console.log(error);
console.log("Shard exited with errors.");
process.exit();
});
}
});
async function onExit() {
exitting = true;
console.log("Exitting...");
client.user.setActivity('Restarting... 🏳️🌈🏳️⚧️', { type: ActivityType.Playing });
client.user.setStatus('idle');
//db.end();
console.log("Shard ready to exit.");
// Sleep to allow the shard manager to catch up and send the exit message
await sleep(500);
// Stop replying to interactions
dead = true;
// And finally we exit
}
process.on("SIGINT", () => {
// Do nothing; Ctrl+C is handled by the shard manager
});
// https://discord.com/api/oauth2/authorize?client_id=983907393823969312&permissions=2147483648&scope=bot%20applications.commands
client.login(config.token);