TypeScript版Discord.js批量刷新斜杠命令报错:Invalid Form Body
解决Discord.js批量提交斜杠命令的「Invalid Form Body」错误
问题排查与修复方案
- 修正命令名称格式:Discord斜杠命令名称仅允许小写字母、数字和连字符,你的
userCount包含大写字母,违反规范。改成全小写的usercount或者带连字符的user-count即可。 - 确认请求头配置:提交请求时必须将
Content-Type设置为application/json,Discord API对该请求头的校验严格,缺失或错误会触发格式报错。 - 优先使用Discord.js官方方法:避免手动构造API请求,直接用框架提供的
ApplicationCommandManager批量注册命令,示例代码如下:
import { Client, GatewayIntentBits } from 'discord.js'; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.on('ready', async () => { if (!client.user || !client.application) return; const commands = [ { name: 'ping', description: 'Replies with Pong!' }, { name: 'usercount', description: 'Returns the number of users online.' } ]; try { await client.application.commands.set(commands); console.log('批量命令注册成功'); } catch (error) { console.error('注册命令失败:', error); } }); client.login('你的Bot令牌');
- 核对API端点正确性:全局命令端点为
https://discord.com/api/v10/applications/{你的BotID}/commands,服务器专属命令需追加/guilds/{服务器ID},端点错误也会导致格式校验不通过。
修正后的合法请求体
[{"name":"ping","description":"Replies with Pong!"},{"name":"usercount","description":"Returns the number of users online."}]
内容的提问来源于stack exchange,提问作者nicht verfügbar
相关产品推荐
相关产品推荐

