Discord.js中如何为Slash Command选项动态添加Choices
动态为Discord Slash Command选项添加Choices
核心问题是你没正确传递符合要求的格式给setChoices或addChoices方法,以下是两种可行实现方式(以Discord.js v14为例):
方式一:使用展开运算符直接传入数组
利用ES6的展开运算符...,把categories数组的元素逐个传递给setChoices,代码更简洁:
const { SlashCommandBuilder } = require('discord.js'); let categories = [{name: "cat1", value: "cat1"},{name: "cat3", value: "cat3"},{name: "cat2", value: "cat2"}]; const helpCommand = new SlashCommandBuilder() .setName('help') .setDescription('获取对应分类的帮助信息') .addStringOption(option => option.setName('category') .setDescription('选择帮助分类') .setChoices(...categories) );
方式二:循环数组逐个添加
如果需要对每个分类做额外处理(比如过滤、修改名称),可以用forEach循环调用addChoices:
const { SlashCommandBuilder } = require('discord.js'); let categories = [{name: "cat1", value: "cat1"},{name: "cat3", value: "cat3"},{name: "cat2", value: "cat2"}]; const helpCommand = new SlashCommandBuilder() .setName('help') .setDescription('获取对应分类的帮助信息') .addStringOption(option => { const categoryOption = option.setName('category').setDescription('选择帮助分类'); categories.forEach(category => { categoryOption.addChoices(category); }); return categoryOption; });
注意事项
- 确保使用Discord.js v14及以上版本,低版本的Slash Command构建语法不同;
- 每个Choice的
name和value长度不能超过100字符,否则会被Discord API拒绝; - 如果categories是异步获取的(比如从数据库拉取),要保证数组填充完成后再构建命令。
内容的提问来源于stack exchange,提问作者rpdjf
相关产品推荐
相关产品推荐

