Discord机器人出现DiscordAPIError[50035]报错,求排查解决
错误信息
DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required
at SequentialHandler.runRequest (C:\Users\Admin\Desktop\bot\node_modules@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:287:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\Admin\Desktop\bot\node_modules@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
at async REST.request (C:\Users\Admin\Desktop\bot\node_modules@discordjs\rest\dist\lib\REST.cjs:52:22)
at async Client.client.handleCommands (C:\Users\Admin\Desktop\bot\src\functions\handlers\handleCommands.js:28:9) {
rawError: {
code: 50035,
errors: { '0': [Object] },
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v9/applications/1009341661572243516/guilds/688019305299706004/commands',
requestBody: { files: undefined, json: [ [Object], [Object] ] }
}
问题代码
命令处理文件(handleCommands.js)
const { Routes } = require('discord-api-types/v9'); const fs = require('fs'); module.exports = (client) => { client.handleCommands = async () => { const commandFolders = fs.readdirSync('./src/commands'); for (const folder of commandFolders) { const commandFiles = fs .readdirSync(`./src/commands/${folder}`) .filter((file) => file.endsWith('.js')); const { commands, commandArray } = client; for (const file of commandFiles) { const command = require(`../../commands/${folder}/${file}`); client.commands.set(command.data.name, command); commandArray.push(command, command.data.toJSON()); } } const clientId = '1009341661572243516'; const guildId = '688019305299706004'; const rest = new REST({ version: '9' }).setToken(process.env.token); try { console.log('Started refreshing application (/) commands.'); await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: client.commandArray, }); console.log('Successfully reloaded application(/) commands.'); } catch (error) { console.error(error); } }; };
示例命令文件(ping.js)
module.exports = { data: new SlashCommandBuilder() .setName("ping") .setDescription("Returns a ping"), async execute(interaction, client) { const message = await interaction.deferReply({ fetchReply: true, }); const newMessage = `API Latency: ${client.ws.ping}\n Client Ping: ${ message.createdTimestamp - interaction.createdTimestamp }`; await interaction.reply({ content: newMessage, }); }, };
错误原因
问题出在handleCommands.js的这段代码:
commandArray.push(command, command.data.toJSON());
这里一次向commandArray中推入了两个元素:
- 第一个是完整的
command对象(包含data配置和execute执行方法),这个对象不符合Discord API要求的命令结构,缺少API必填的顶层name字段。 - 第二个是正确的
command.data.toJSON()结果,即Slash命令的标准JSON格式。
当调用rest.put提交命令时,API解析数组第一个元素时发现结构无效,于是抛出0.name[BASE_TYPE_REQUIRED]错误。
解决方法
修改handleCommands.js中的推入逻辑,只将命令的标准JSON格式数据加入commandArray:
// 替换原push语句 commandArray.push(command.data.toJSON());
修改后commandArray中只会包含Discord API可识别的命令结构,即可正常完成命令刷新。
内容的提问来源于stack exchange,提问作者Harshita

