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

Discord.js开发多功能Bot遇ValidationError:期望字符串原始值

Discord.js机器人报错:ValidationError: Expected a string primitive 排查与解决

你遇到的ValidationError: Expected a string primitive错误,定位在slashCommands.push(command.toJSON());这一行,本质是命令对象转JSON后,存在某个要求为字符串的字段不是字符串类型(比如是null、undefined或数字等)。虽然你觉得打印结果正常,但可能是打印时没显示出深层字段的类型问题,按以下步骤排查:

1. 逐个检查命令文件的data结构

所有.S.js后缀的 slash 命令文件中,必须确保以下核心字段都是字符串类型:

  • 命令本身的name和description
  • 命令选项(如果有)的name、description
  • 选项的type如果是手动赋值,必须是Discord.js提供的枚举值(比如ApplicationCommandOptionType.String),不能是自定义的非字符串/枚举值

比如不能出现这类错误写法:

// 错误:description被赋值为undefined
data: new SlashCommandBuilder()
    .setName('test')
    .setDescription(undefined)
// 错误:选项name用了数字
data: new SlashCommandBuilder()
    .setName('test')
    .setDescription('测试命令')
    .addStringOption(option =>
        option.setName(123) // 这里必须是字符串
        .setDescription('输入内容')
    )

2. 添加调试代码定位问题命令

在遍历命令文件的循环中加入详细日志,精准找到哪个命令出问题:

for(const file of slash_commandFiles)
{
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    
    // 打印当前检查的文件名和命令数据
    console.log(`=== 检查命令文件:${file} ===`);
    console.log('命令名称:', command.data.name, '类型:', typeof command.data.name);
    console.log('命令描述:', command.data.description, '类型:', typeof command.data.description);
    
    // 如果有选项,逐个检查选项的字段类型
    if(command.data.options?.length) {
        command.data.options.forEach((opt, index) => {
            console.log(`--- 选项${index+1} ---`);
            console.log('选项名称:', opt.name, '类型:', typeof opt.name);
            console.log('选项描述:', opt.description, '类型:', typeof opt.description);
        });
    }
    
    client.slashCommands.set(command.data.name, command);
    slashCommands.push(command.toJSON());
}

运行后看日志,哪个字段的类型不是string,就是问题所在。

3. 修复字段类型问题

找到异常字段后,将其修正为合法的字符串即可。比如把undefined改成空字符串或有效描述,把数字类型的名称改成字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:48:51