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

如何在Discord.js对象式声明的命令中配置选项的choices可选值

解决方案

你当前使用的是JSON对象格式的斜杠命令定义方式,addChoice()是SlashCommandBuilder链式写法的专属方法,和你的写法不兼容,直接给choices字段赋值数组即可,数组每一项对应一个可选值。


choices字段格式规则

  • 每个可选值是包含name和value两个属性的对象
  • name:用户在Discord命令选择界面看到的显示文本
  • value:代码实际接收到的参数值,类型需要和选项的type匹配,你这里是STRING类型,值为字符串即可

修改后的完整代码

module.exports = {
    name: 'gifsearch',
    description: 'Returns a gif based on your search term.',
    options: [{
        name: 'type',
        type: 'STRING',
        description: 'Whether to search for gifs or stickers.',
        // 此处为补充的choices配置,示例提供动图/贴纸两个可选值,可按需增减
        choices: [
            {
                name: '动图(GIF)',
                value: 'gif'
            },
            {
                name: '贴纸(Sticker)',
                value: 'sticker'
            }
        ],
        required: true
    },
    {
        name: 'search_term',
        type: 'STRING',
        description: 'The search term to use when searching for gifs.',
        required: true,
    }],
    async execute(interaction) {
        const searchTerm = interaction.options.getString('search_term')
        // 获取用户选择的type值
        const searchType = interaction.options.getString('type')
        // 根据选择的类型调用对应Giphy接口
        const apiPath = searchType === 'gif' ? 'gifs/search' : 'stickers/search'

        fetch(`https://api.giphy.com/v1/${apiPath}?q=${searchTerm}&api_key=${process.env.giphyAPIkey}&limit=1&rating=g`)
        .then((res) => res.json())
        .then((json) => {
            if (json.data.length <= 0) return interaction.reply({ content: `未找到对应资源!` })
            interaction.reply({content: `${json.data[0].url}`})
        })
    },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:09:04