You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:06:28