summary refs log tree commit diff
path: root/events/messageCommands.js
blob: 25f1260084ce4b022bb905d3a4d6ff56c2011bf4 (plain)
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
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`
			});
		}
	}
}