如何将SlashCommandBuilder选项存至独立JS文件并解决调用报错
SlashCommandBuilder选项统一管理问题解决与优化方案
问题场景
原本在SlashCommandBuilder中直接编写选项代码可正常运行:
.addStringOption((option) => option .setName('city') .setDescription('In which city are you currently based from?') .addChoices( { name: 'City 1', value: 'City-1-Example' }, { name: 'City 2', value: 'City-2-Example' } ) .setRequired(true) )
为了统一管理选项,将选项抽离到options.js:
export const options = { city: [ { name: 'City 1', value: 'City-1-Example' }, { name: 'City 2', value: 'City-2-Example' } ], optionsForAnotherCommand: [/* ... */] }
但调用时出现错误:
errors: [[ 0, ValidationError: Expected the value to not be an array ...
错误原因
Discord.js的addChoices方法要求传入多个独立的键值对对象参数,而非单个数组。直接传递options.city会把整个数组作为单个参数传入,不符合方法的参数格式要求。
快速修复
使用ES6扩展运算符(...)将数组展开为多个独立参数即可解决:
.addStringOption((option) => option .setName('city') .setDescription('In which city are you currently based from?') .addChoices(...options.city) // 用...展开数组 .setRequired(true) )
更规范的选项管理方案
1. 按功能/命令拆分选项文件
避免单个options.js文件过大,按通用选项、特定命令选项拆分存储:
// options/cityChoices.js export const cityChoices = [ { name: 'City 1', value: 'City-1-Example' }, { name: 'City 2', value: 'City-2-Example' } ]; // options/userTypeChoices.js export const userTypeChoices = [/* ... */];
2. 封装完整选项构建函数
将选项的名称、描述、必填性、选项值等完整配置封装成函数,直接在命令中调用,减少重复代码:
// options/optionBuilders.js import { SlashCommandStringOption } from 'discord.js'; import { cityChoices } from './cityChoices.js'; export const buildCityOption = () => new SlashCommandStringOption() .setName('city') .setDescription('In which city are you currently based from?') .addChoices(...cityChoices) .setRequired(true);
调用时只需一行代码:
.addStringOption(buildCityOption())
3. 配置文件驱动
如果选项需要频繁修改或从外部数据源同步,可以将选项存储在JSON/YAML配置文件中,通过工具函数动态加载:
// config/cityChoices.json [ {"name": "City 1", "value": "City-1-Example"}, {"name": "City 2", "value": "City-2-Example"} ]
加载并使用:
import cityChoices from '../config/cityChoices.json' assert { type: 'json' }; // 在命令中 .addStringOption((option) => option .setName('city') .setDescription('In which city are you currently based from?') .addChoices(...cityChoices) .setRequired(true) )
内容的提问来源于stack exchange,提问作者Cif
相关产品推荐
相关产品推荐

