如何使用discord.js将命令部署到机器人所在的所有Guild?
如何将Discord机器人命令部署到所有已加入的服务器
要把命令部署到机器人加入的所有服务器,你需要先获取机器人所在的全部服务器列表,再循环对每个服务器执行部署操作。以下是具体修改方案:
核心修改点
- 引入Discord.js客户端模块,通过登录机器人账号获取它所在的所有服务器
- 移除代码中固定的
guildId配置,改用动态获取的服务器ID列表 - 遍历每个服务器,逐个部署命令
修改后的完整代码
const { REST } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v9'); const { Client, GatewayIntentBits } = require('discord.js'); const { clientId, token } = require('./config.json'); const fs = require('fs'); // 补上原代码遗漏的fs模块引入 const commands = []; const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); console.log("Loading commands..."); for (const file of commandFiles) { const command = require(`./commands/${file}`); console.log("Loaded command : " + command.data.name + "..."); commands.push(command.data.toJSON()); } console.log("Commands loaded..."); const rest = new REST({ version: '9' }).setToken(token); // 初始化Discord客户端,获取服务器列表 const client = new Client({ intents: [GatewayIntentBits.Guilds] // 必须启用Guilds意图才能获取服务器信息 }); client.once('ready', async () => { console.log('Successfully registered application commands to :'); // 遍历机器人所在的所有服务器 for (const guild of client.guilds.cache.values()) { try { await rest.put( Routes.applicationGuildCommands(clientId, guild.id), { body: commands } ); console.log(`- ${guild.name} (ID: ${guild.id})`); } catch (error) { console.error(`Failed to deploy to ${guild.name}:`, error); } } console.log('Done registering application commands!'); client.destroy(); // 完成部署后关闭客户端连接 }); // 登录机器人 client.login(token);
注意事项
- 确保
config.json中只保留clientId和token,不再需要guildId - 机器人必须启用
Guilds意图,否则无法获取服务器列表 - 如果机器人加入了大量服务器,部署过程可能触发Discord API速率限制,可在循环中加入
await new Promise(resolve => setTimeout(resolve, 1000));来延迟请求 - 机器人需要在目标服务器拥有
Manage Guild权限才能部署命令
内容的提问来源于stack exchange,提问作者user18339230
相关产品推荐
相关产品推荐

