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

Discord.js中Python CommandTree等效实现及斜杠命令同步问题

Python Discord Bot 转 discord.js 等效实现与斜杠命令同步指南

一、Python 代码对应的 JavaScript 实现

在 discord.js v14+ 版本中,没有单独的 CommandTree 类,斜杠命令的管理逻辑直接集成在客户端实例中。以下是你提供的 Python 代码的等效 JS 实现:

Python 原代码

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

对应的 discord.js 代码

const { Client, GatewayIntentBits, Collection } = require('discord.js');

// 对应 Python 的 discord.Intents.default(),按需启用必要意图
const intents = [
  GatewayIntentBits.Guilds, // 必须启用,否则无法处理服务器内的斜杠命令
  GatewayIntentBits.GuildMessages,
  // 可添加其他默认意图
];

// 初始化客户端,对应 Python 的 discord.Client
const client = new Client({ intents: intents });

// 用 Collection 存储命令,等效 Python 中 CommandTree 的命令管理作用
client.commands = new Collection();

二、正确同步斜杠命令

你代码里的 client.tree.sync() 是旧版本写法,v14+ 有两种可靠的同步方式:

方式一:在 ready 事件中全局同步(适合开发阶段)

修改你的 ready 事件代码,替换原同步逻辑:

client.on('ready', async () => {
    await client.user.setActivity({ type: 'WATCHING', name: loadConfigs.activity_name });

    if (!fs.existsSync(`${process.env.DATA_PATH}tracked_accounts.db`)) {
        initDB();
    }

    // 同步全局斜杠命令,将 client.commands 中的命令数据提交到 Discord
    const syncedCommands = await client.application.commands.set(client.commands.map(cmd => cmd.data));
    
    log.info(`${client.user.tag} is online`);
    log.info(`Synced ${syncedCommands.length} slash commands`);
});

方式二:通过 REST API 单独同步(适合生产环境)

这种方式无需启动 Bot,单独运行脚本即可完成同步,避免重复提交:

const { REST, Routes } = require('discord.js');
const { clientId, token } = require('./config.json');
const fs = require('fs');

const commands = [];
// 加载所有命令文件
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
}

const rest = new REST({ version: '10' }).setToken(token);

// 全局同步(生效时间约1小时)
rest.put(Routes.applicationCommands(clientId), { body: commands })
    .then((data) => console.log(`Successfully registered ${data.length} application commands.`))
    .catch(console.error);

// 服务器专属同步(立即生效,适合开发测试)
// rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
//     .then((data) => console.log(`Successfully registered ${data.length} guild commands.`))
//     .catch(console.error);

三、补充说明

  • 命令编写规范:每个斜杠命令需用 SlashCommandBuilder 构建示例:
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        await interaction.reply('Pong!');
    },
};

启动 Bot 时需将这类命令文件加载到 client.commands 集合中。

  • 错误处理:对应 Python 的 tree.on_error,可在 interactionCreate 事件中全局捕获错误,或给每个命令的 execute 方法添加 try-catch 逻辑。

内容的提问来源于stack exchange,提问作者MrPand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:22:38