使用最新Discord JS开发斜杠命令机器人遇401未授权错误
Discord JS 斜杠命令机器人遭遇401未授权错误
我正在用最新版Discord JS开发带斜杠命令的Discord机器人,但每次运行都会返回Discord API错误:401: Unauthorized - Can't put application commands with REST。
我试过仅使用应用命令模块(只需要CLIENT_ID,不需要同时提供CLIENT_ID和GUILD_ID,和applicationGuildCommand不同),但问题依然存在。
机器人代码
import { config } from 'dotenv'; import { ActionRowBuilder, Client, GatewayIntentBits, InteractionType, ModalBuilder, Routes, // SelectMenuBuislder, TextInputBuilder, TextInputStyle, } from 'discord.js'; import { REST } from '@discordjs/rest'; import pingCommand from './commands/ping.js' config(); const TOKEN = process.env.BOT_TOKEN const CLIENT_ID = process.env.CLIENT_ID; const GUILD_ID = process.env.GUILD_ID; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], }); const rest = new REST({ version: '10' }).setToken(TOKEN); client.on('ready', () => console.log(`${client.user.tag} has logged in!`)); client.on('interactionCreate', (interaction) => { if (interaction.isChatInputCommand()) { console.log('Chat Command'); if (interaction.commandName === 'ping') { interaction.reply("Pong") } } }); async function main() { const commands = [ pingCommand ]; try { console.log('Started refreshing application (/) commands.'); await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands, }); client.login(TOKEN); } catch (err) { console.log(err); } } main();
测试用ping命令代码
import { SlashCommandBuilder } from '@discordjs/builders'; const pingCommand = new SlashCommandBuilder() .setName('ping') .setDescription('ping') .addRoleOption((option) => option .setName('eh') .setDescription("huh") .setRequired(false) ); export default pingCommand.toJSON();
解决建议
- 检查
BOT_TOKEN准确性:确认.env文件中的机器人令牌无拼写错误、无多余空格,且对应机器人账号已勾选applications.commands权限范围(在Discord开发者平台的机器人页面设置)。 - 验证
CLIENT_ID正确性:确保.env中的客户端ID是Discord开发者平台对应应用的ID,而非服务器ID或其他无关ID。 - 重新生成令牌:若之前生成令牌时未勾选
applications.commands授权范围,需重新生成包含该权限的令牌。 - 调整命令注册时机:将命令注册逻辑放在客户端登录成功后执行,避免REST请求先于登录发送:
async function main() { try { await client.login(TOKEN); console.log('Started refreshing application (/) commands.'); const commands = [pingCommand]; await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands }); console.log('Successfully reloaded application (/) commands.'); } catch (err) { console.log(err); } }
内容的提问来源于stack exchange,提问作者Ashiq Tasdid
相关产品推荐
相关产品推荐

