forked from harshendram/Advanced-Discord-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy-commands.js
More file actions
166 lines (140 loc) · 4.13 KB
/
deploy-commands.js
File metadata and controls
166 lines (140 loc) · 4.13 KB
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
const { REST, Routes } = require("discord.js");
const { readdirSync, existsSync } = require("fs");
const path = require("path");
require("dotenv").config();
// 🚀 Initialize commands array
const commands = [];
// 📁 Load all command files
const commandsPath = path.join(__dirname, "commands");
const pluginsPath = path.join(__dirname, "plugins");
console.log("🔄 Loading commands...");
// Function to recursively load commands from folders
function loadCommandsFromDirectory(dirPath) {
const items = readdirSync(dirPath, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(dirPath, item.name);
if (item.isDirectory()) {
loadCommandsFromDirectory(fullPath);
} else if (item.isFile() && item.name.endsWith(".js")) {
try {
const command = require(fullPath);
if ("data" in command && "execute" in command) {
commands.push(command.data.toJSON());
const relativePath = path.relative(commandsPath, fullPath);
const category =
path.dirname(relativePath) === "."
? "root"
: path.dirname(relativePath);
console.log(`✅ Loaded: ${command.data.name} (${category})`);
} else {
console.log(
`⚠️ Skipped: ${fullPath} (missing "data" or "execute" property)`,
);
}
} catch (error) {
console.error(`❌ Error loading command ${fullPath}:`, error.message);
}
}
}
}
function loadPluginCommands(pluginsDir) {
if (!pluginsDir) return;
if (!existsSync(pluginsDir)) {
return;
}
const pluginDirs = readdirSync(pluginsDir, { withFileTypes: true });
for (const pluginDir of pluginDirs) {
if (!pluginDir.isDirectory()) continue;
const pluginCommandsPath = path.join(
pluginsDir,
pluginDir.name,
"commands",
);
if (!existsSync(pluginCommandsPath)) {
continue;
}
loadCommandsFromDirectory(pluginCommandsPath);
}
}
// Load all commands
loadCommandsFromDirectory(commandsPath);
loadPluginCommands(pluginsPath);
// 🌐 Initialize REST client
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
// ⏱️ Timeout wrapper — forces rejection if Discord hangs instead of responding
const withTimeout = (promise, ms = 15000) =>
Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(
() =>
reject(
Object.assign(new Error("timeout"), {
status: 429,
retryAfter: 60,
}),
),
ms,
),
),
]);
// 🔁 Retry wrapper — waits on rate limit and retries automatically
const deployWithRetry = async (route, body, retries = 5) => {
for (let i = 0; i < retries; i++) {
try {
return await withTimeout(rest.put(route, { body }));
} catch (error) {
if (error.status === 429) {
const wait = (error.retryAfter ?? 60) * 1000;
console.log(
`⏳ Rate limited. Waiting ${wait / 1000}s before retry ${i + 1}/${retries}...`,
);
await new Promise((r) => setTimeout(r, wait));
} else {
throw error;
}
}
}
throw new Error("Max retries exceeded");
};
// 🚀 Deploy commands
(async () => {
try {
console.log(
`\n🚀 Started refreshing ${commands.length} application (/) commands.`,
);
// Optional: log REST responses for debugging
rest.on("response", (req, res) => {
console.log(`[REST] ${req.method} ${req.path} → ${res.status}`);
});
// Single PUT replaces all existing commands — no need to clear first
const data = await deployWithRetry(
process.env.GUILD_ID
? Routes.applicationGuildCommands(
process.env.CLIENT_ID,
process.env.GUILD_ID,
)
: Routes.applicationCommands(process.env.CLIENT_ID),
commands,
);
console.log(
`✅ Successfully reloaded ${data.length} application (/) commands.`,
);
console.log(
`📍 Deployment: ${
process.env.GUILD_ID
? "Guild-specific (Development)"
: "Global (Production)"
}`,
);
// 📋 List deployed commands
console.log("\n📋 Deployed commands:");
commands.forEach((cmd, index) => {
console.log(`${index + 1}. /${cmd.name} - ${cmd.description}`);
});
console.log("\n🎉 Command deployment completed successfully!");
} catch (error) {
console.error("❌ Error deploying commands:", error.message);
process.exit(1);
}
})();