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

discord.js v13斜杠命令处理器启动报Invalid Form Body错误如何解决

问题修复方案

错误原因

报错0.name: This field is required是因为你注册斜杠命令时传入的参数不符合Discord API要求,你的代码存在以下几个核心问题:

  • 重复注册ready事件:在命令遍历循环内重复绑定ready事件监听,会导致事件被触发多次
  • 命令数组逻辑错误:每次遍历单个命令都会重置commandsArray为空,最终数组只会保留最后一个命令的信息,且你传入的是命令名称字符串,而非Discord要求的斜杠命令结构对象
  • 无效的集合赋值:client.commands.set(cmd)缺少键参数,会插入无效的键值对
  • 命令定义结构不匹配:现有命令的help.description字段存的是别名数组,不符合斜杠命令要求的必填字符串描述字段规则

修改步骤

1. 调整命令处理器(index.js)逻辑

const pComandos = fs.readdirSync('Comandos');

client.commands = new Discord.Collection();
client.description = new Discord.Collection();
// 将命令数组提到循环外部,避免被重复重置
const commandsArray = [];

for (const folder of pComandos) {
    const file = fs.readdirSync('Comandos/' + folder);
    for (const comando of file) {
        let cmd = require(`./Comandos/${folder}/${comando}`);
        console.log(chalk.green(`[ C ] O comando ` + chalk.bold(comando) + ` foi carregado!`))
        // 注册主命令到集合
        client.commands.set(cmd.help.name, cmd)
        // 处理命令别名
        if (cmd.help.aliases) {
            cmd.desc = true
            cmd.help.aliases.forEach(alias => client.commands.set(alias, cmd))
        }
        // 构造符合Discord要求的斜杠命令对象,推入注册数组
        commandsArray.push({
            name: cmd.help.name,
            description: cmd.help.description
        });
        if (cmd.init) cmd.init(client)
    }
}

// 将ready事件移到循环外部,仅注册一次
client.on("ready", async() => {
    const server = client.guilds.cache.get("892210305558532116")
    // 传入构造完成的斜杠命令对象数组
    await server.commands.set(commandsArray)
    console.log("斜杠命令注册完成")
})

2. 调整命令文件结构(以ping.js为例)

将别名和命令描述拆分为独立字段,符合斜杠命令的参数要求:

const discord = require("discord.js");

exports.run = async (client, message, args) => {
  var latency = Date.now() - message.createdTimestamp
  message.reply(`<:emoji_3:892431734203891722> | My ping is: ${client.ws.ping}.
🗺 | Timezone: ${process.env.TZ}`);
};
exports.help = {
  name: "ping",
  description: "查看机器人当前延迟", // 斜杠命令必填字段,要求为字符串,长度不超过100字符
  aliases: ["p"] // 原别名移动到独立字段
};

3. 兼容斜杠命令触发(可选)

如果需要保留原有处理器逻辑,同时支持斜杠命令触发,新增interactionCreate事件监听即可:

client.on("interactionCreate", async interaction => {
    // 过滤非斜杠命令交互
    if (!interaction.isCommand()) return
    const cmd = client.commands.get(interaction.commandName)
    if (!cmd) return
    // 适配原有run方法的参数结构,无需修改原有命令逻辑
    interaction.createdTimestamp = interaction.createdTimestamp
    interaction.reply = interaction.reply.bind(interaction)
    cmd.run(client, interaction, [])
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:45:03