discord.js中无法将字符串变量传入option.setName()函数的问题
问题分析与解决
问题描述
使用discord.js编写代码时,第22行将字符串变量optName传入option.setName()时触发错误,但传入"test"这类字符串字面量却能正常运行。错误截图如下:
相关代码:
import { SlashCommandBuilder } from "discord.js"; import { optionsI } from "./interfaces"; function initOptions( slashCommandBuild: SlashCommandBuilder, options: optionsI, ) { for (const [keys, values] of Object.entries(options) as [ keys: keyof typeof options, values: Map<string, string>, ][]) { slashCommandBuild[keys]((option: any) => { const optName: string = values.keys().next().value; const optDesc: string | undefined = values.get( values.keys().next().value, ); if (optName === undefined || optName === null) { throw new Error( `Please make sure that the command has a name.`, ); } option.setName(optName); if (optDesc === null || optDesc === undefined) return option; option.setDescription(optDesc); return option; }); } } export { initOptions };
原因
从错误截图可知,Discord对斜杠命令的选项名称有严格规则:只能包含小写字母、数字、连字符(-)和下划线(_),禁止出现大写字母、空格或其他特殊字符。
你传入的optName变量值违反了该规则,而字面量"test"完全符合要求,因此后者能正常运行。
此外代码存在潜在逻辑问题:两次调用values.keys().next()会生成独立迭代器,若Map包含多个键,第二次获取的键可能和第一次不匹配,导致optDesc对应的值错误。
解决步骤
- 检查
optName的实际值,确保仅包含小写字母、数字、-和_,剔除所有非法字符。 - 修复迭代器重复生成的问题,将键存入变量复用:
const firstKey = values.keys().next().value; const optName: string = firstKey; const optDesc: string | undefined = values.get(firstKey);
内容的提问来源于stack exchange,提问作者Laycookie
相关产品推荐
相关产品推荐

