summary refs log tree commit diff
path: root/events/messageCommands.js
diff options
context:
space:
mode:
Diffstat (limited to 'events/messageCommands.js')
-rw-r--r--events/messageCommands.js71
1 files changed, 71 insertions, 0 deletions
diff --git a/events/messageCommands.js b/events/messageCommands.js
new file mode 100644
index 0000000..25f1260
--- /dev/null
+++ b/events/messageCommands.js
@@ -0,0 +1,71 @@
+const path = require('node:path');
+const util = require('node:util');
+const fs = require('node:fs');
+
+const { Collection } = require('discord.js');
+
+globalThis.commands = new Collection();
+
+globalThis.commandsReload = () => {
+	globalThis.commands = new Collection();
+
+	console.error('commands:');
+
+	const commandsDir = fs.readdirSync(config.directories.commandsDir).filter((fileName) => fileName.endsWith('.js'));
+
+	for (let i = 0; i < commandsDir.length; i += 1) {
+		const commandModulePath = path.join(process.cwd(), config.directories.commandsDir, commandsDir[i]);
+		delete require.cache[require.resolve(commandModulePath)];
+
+		const commandModule = require(commandModulePath);
+
+		if (typeof commandModule.name !== 'string' || typeof commandModule.execute !== 'function') {
+			console.error(`${commandModulePath} is not a valid command module`);
+			continue;
+		}
+
+		commands.set(commandModule.name, commandModule);
+
+		console.log(`\t${commandsDir[i]} -> ${commandModule.name}`);
+	}
+}
+
+globalThis.commandsReload();
+
+module.exports = {
+	name: 'messageCreate',
+	async execute(message) {
+		if (message.author.bot) return;
+
+		let prefix = false;
+		for (let i = 0; i < config.prefixes.length; i += 1) {
+			const configuredPrefix = config.prefixes[i];
+
+			if (message.content.startsWith(configuredPrefix)) {
+				prefix = configuredPrefix;
+				break;
+			}
+		}
+
+		if (!prefix) {
+			return;
+		}
+
+		const args = message.content.slice(prefix.length).trim().split(/ +/gmi);
+		const command = globalThis.commands.get(args[0]);
+
+		if (!command) {
+			return;
+		}
+
+		try {
+			await command.execute(message, args.slice(1), globalThis.client);
+		} catch (e) {
+			console.error(e);
+			return await message.reply({
+				content: `an error occurred\n${e}\nplease contact the bot developer`
+			});
+		}
+	}
+}
+