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

如何让Discord.js机器人根据交互选项做出对应回复?

问题翻译

我希望我的Discord机器人能根据用户选择的交互选项进行回复。比如我有个名为favourite-pet的命令,用户选dog选项时,机器人回复“我最喜欢的宠物也是狗狗”;选cat选项时,回复“我最喜欢的动物也是猫咪”。但我没法实现这个功能,当前代码如下:

if (interaction.commandName === 'favourite-pet') {
    if (interaction.options === 'dog') {
      interaction.reply(`My favourtie pet is also a dog `)
    }
if (interaction.options === 'cat') {
      interaction.reply(`my favourite animal is also a cat  `)
    }
  }
解决方案

你代码的核心问题是直接把interaction.options和字符串做比较——interaction.options是存储所有命令选项的对象,不是单个选项的具体值。需要用对应的方法提取选项值,再做判断:

  1. 先通过getString()(如果是字符串/枚举类型选项)获取用户选择的宠物值,注意替换成你创建Slash命令时给该选项定义的名称(比如pet-type)
  2. 再根据提取到的值分支回复,同时用else if避免多次触发interaction.reply(单个交互只能回复一次)

修正后的代码示例:

if (interaction.commandName === 'favourite-pet') {
  // 替换pet-type为你实际的选项参数名
  const selectedPet = interaction.options.getString('pet-type');
  
  if (selectedPet === 'dog') {
    interaction.reply('我最喜欢的宠物也是狗狗');
  } else if (selectedPet === 'cat') {
    interaction.reply('我最喜欢的动物也是猫咪');
  } else {
    // 可选:处理未预期的选项值
    interaction.reply('我还没见过这种宠物呢!');
  }
}

额外注意:如果你的选项是其他类型(比如整数、布尔值),要对应使用getInteger()、getBoolean()等方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:59:57