Discord.js斜杠命令注册报错:Expected token to be set for this request
Discord.js注册斜杠命令报错:Expected token to be set for this request, but none was present
错误详情
Registering slash commands... something wrong happen with this command: Error: Expected token to be set for this request, but none was present
使用的代码
const { REST, Routes } = require('discord.js'); const commands = [ { name: 'mc' , description: 'show the actual number of members in the server', }, ]; const rest = new REST({ version: '10' }).setToken(process.env.TOKEN_ID); (async () => { try { console.log('Registering slash commands...'); await rest.put( Routes.applicationGuildCommand(process.env.CLIENT_ID, process.env.GUILD_ID), { body: commands } ) console.log('slash commands were registered without errors') } catch (error) { console.log(`something wrong happen with this command: ${error}`); } })();
补充说明:已通过.env文件配置了bot token、服务器ID和bot ID,正在学习Discord.js创建斜杠命令的相关内容。
解决方法
1. 确认dotenv已安装并加载
如果未安装dotenv,先执行安装命令:
npm install dotenv
然后在代码最顶部添加加载语句:
require('dotenv').config();
缺少这一步,Node.js无法读取.env文件中的环境变量。
2. 核对.env变量名与代码引用一致
检查.env文件内的token变量名是否为TOKEN_ID,变量名大小写敏感,若.env中写的是TOKEN,代码里需对应改为process.env.TOKEN,必须完全匹配。
3. 验证环境变量是否成功读取
在代码中加入打印语句,确认变量值是否正常加载:
console.log('Token:', process.env.TOKEN_ID); console.log('Client ID:', process.env.CLIENT_ID); console.log('Guild ID:', process.env.GUILD_ID);
如果输出undefined,说明.env文件路径错误(比如不在项目根目录)或格式错误(正确格式为TOKEN_ID=你的bot令牌,变量值不要加引号)。
4. 检查Bot Token有效性
确认从Discord开发者平台复制的Bot Token无多余空格或换行,且Bot已被邀请到目标服务器,邀请时需勾选applications.commands权限。
内容的提问来源于stack exchange,提问作者Kuma
相关产品推荐
相关产品推荐

