如何在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
相关产品推荐
相关产品推荐

