-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommandHandler.js
93 lines (78 loc) · 3.02 KB
/
commandHandler.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
const { Collection, REST, Routes } = require("discord.js");
const { CLIENT_ID, token } = require("../config.js");
const fs = require("node:fs");
const path = require("node:path");
const Konsol = require("../functions/beautifulConsole.js");
const konsol = new Konsol();
const log = konsol.log;
const error = konsol.error;
const commands = new Collection();
const commandsJSON = [];
const foldersPath = path.join(__dirname, "..", "src", "commands");
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ("data" in command && "run" in command) {
commands.set(command.data.name, command);
commandsJSON.push(command.data.toJSON());
} else {
log(
`[WARNING] The command at ${filePath} is missing a required "data" or "run" property.`
);
}
}
}
const rest = new REST().setToken(token);
const deployCommands = async () => {
try {
log(`Started refreshing ${commandsJSON.length} application (/) commands.`);
const data = await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commandsJSON,
});
log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (err) {
error(err);
}
};
const watchCommands = () => {
let timeout;
const delay = 3 * 1000;
fs.watch(foldersPath, { recursive: true }, (eventType, filename) => {
if (filename && filename.endsWith('.js')) {
log(`Command file changed: ${filename}`);
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
commands.clear();
commandsJSON.length = 0;
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
delete require.cache[require.resolve(filePath)];
const command = require(filePath);
if ('data' in command && 'run' in command) {
commands.set(command.data.name, command);
commandsJSON.push(command.data.toJSON());
} else {
log(`[WARNING] The command at ${filePath} is missing a required "data" or "run" property.`);
}
}
}
log("Deploying commands after 3 seconds of inactivity...");
deployCommands();
}, delay);
}
});
};
deployCommands();
watchCommands();
module.exports = { commands, commandsJSON };