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

使用SlashCommandBuilder添加子命令时遇DiscordAPIError求助

Discord.js v13 子命令 type 字段缺失导致 DiscordAPIError 解决方案

问题根源

这个错误是因为你构建的 slash 命令数据中,某个选项(或子命令)的type字段未被正确设置,Discord API 无法识别该选项的类型。常见触发场景:

  • 使用addOption()代替addSubcommand()/addSubcommandGroup()来添加子命令
  • 命令构建的链式调用遗漏了必要的类型定义方法
  • 命令注册时未将SlashCommandBuilder实例转换为正确的 JSON 格式

针对性排查与修复

1. 检查子命令的构建方式

以你提到的user命令的info子命令为例,错误写法通常是误用addOption:

// 错误写法:用addOption添加子命令,导致type缺失
new SlashCommandBuilder()
  .setName('user')
  .setDescription('用户相关命令')
  .addOption(opt => opt.setName('info').setDescription('查看用户信息'));

正确的子命令构建必须使用addSubcommand方法:

// 正确写法:用addSubcommand定义子命令
const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('user')
    .setDescription('用户相关命令')
    .addSubcommand(subcmd =>
      subcmd
        .setName('info')
        .setDescription('查看用户信息')
        // 子命令内的选项需用对应类型的方法添加,比如addUserOption、addStringOption等
        .addUserOption(opt =>
          opt.setName('target')
            .setDescription('目标用户')
            .setRequired(false)
        )
    ),
  async execute(interaction) {
    if (interaction.options.getSubcommand() === 'info') {
      // 子命令执行逻辑
      const target = interaction.options.getUser('target') || interaction.user;
      await interaction.reply(`查看用户:${target.tag}`);
    }
  }
};

2. 确认命令注册逻辑正确

部署命令时,必须将SlashCommandBuilder实例转换为 Discord 可识别的 JSON 格式:

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const { clientId, guildId, token } = require('./config.json');

const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(f => f.endsWith('.js'));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  // 必须调用toJSON()转换命令数据
  commands.push(command.data.toJSON());
}

const rest = new REST({ version: '9' }).setToken(token);

(async () => {
  try {
    await rest.put(
      Routes.applicationGuildCommands(clientId, guildId),
      { body: commands }
    );
    console.log('命令部署成功');
  } catch (err) {
    console.error(err);
  }
})();

3. 定位错误命令

根据错误栈中的11.options[0],找到第11个被加载的命令文件(按文件读取顺序),重点检查该命令的选项/子命令构建逻辑,确认是否存在:

  • 用addOption定义子命令的情况
  • 选项未使用对应类型方法(比如直接用addOption而不是addStringOption)

总结

核心修复点是确保子命令通过addSubcommand/addSubcommandGroup添加,选项通过对应类型方法定义,并在注册时正确调用toJSON()转换命令数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:13:24