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

重复声明const data引发SyntaxError,如何创建带用户选项的Slash Command

问题解决与代码修正

核心问题拆解

  1. 重复声明const变量:const声明的变量不允许重复定义,第23行再次使用const data触发语法错误。
  2. 命令配置逻辑错误:同一个SlashCommandBuilder实例多次调用setName/setDescription会覆盖之前的配置,导致只有最后一个命令(description)生效,help和moderation并未被正确创建。
  3. 方法调用错误:interaction.reply.apply是错误用法,直接调用interaction.reply即可。
  4. 冗余事件监听:多次注册interactionCreate事件可以合并,提升代码效率与可维护性。

修正后的完整代码

// 为每个命令创建独立的SlashCommandBuilder实例
const helpCommand = new SlashCommandBuilder()
    .setName("help")
    .setDescription("pour savoir toutes les commandes utilisables");

const moderationCommand = new SlashCommandBuilder()
    .setName("moderation")
    .setDescription("pour avoir toutes les commandes de moderation");

const descriptionCommand = new SlashCommandBuilder()
    .setName("description")
    .setDescription("pour connaître la description du bot");

const calinCommand = new SlashCommandBuilder()
    .setName("calin")
    .setDescription("donner un calin à un membre")
    .addUserOption(option => option
       .setName("utilisateur") 
       .setDescription("Utilisateur mentionné")
       .setRequired(true));

// 批量注册命令(需根据Discord.js版本调整注册逻辑,示例如下)
// REST.put(Routes.applicationCommands(clientId), { 
//   body: [
//     helpCommand.toJSON(), 
//     moderationCommand.toJSON(), 
//     descriptionCommand.toJSON(), 
//     calinCommand.toJSON()
//   ] 
// })

// 合并所有交互监听逻辑
client.on("interactionCreate", interaction => {
    if (!interaction.isCommand()) return;

    const { commandName } = interaction;

    switch(commandName) {
        case "help":
            interaction.reply("pour connaître mes commandes de moderation: /moderation");
            break;
        case "description":
            interaction.reply("Je suis Athéna, une déesse grec de l'artisanat et de la stratégie guerrière. Je m'occupe de la modération, jeux et de trackage d’information");
            break;
        case "calin":
            const user = interaction.options.getUser("utilisateur");
            // 因参数设为必填,无需判断user是否为undefined
            interaction.reply(`Merci du gros câlin <@${user.id}>`);
            break;
        case "moderation":
            interaction.reply("Liste des commandes de moderation: ..."); // 补充具体内容
            break;
    }
});

关键修正说明

  • 变量命名规范:每个命令使用独立的变量名(如helpCommand、calinCommand),避免const重复声明问题。
  • 独立命令实例:每个Slash命令对应单独的SlashCommandBuilder,确保所有命令都能正确注册生效。
  • 优化事件监听:用switch替代多段if判断,合并事件监听逻辑,代码更简洁易维护。
  • 修正方法调用:移除错误的apply调用,使用模板字符串优化消息拼接逻辑。
  • 参数命名规范:将命令参数改为小写(utilisateur),符合Discord命令参数的常规命名习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:05:58