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

Discord机器人遭遇401: Unauthorized错误求助

DiscordAPIError[0]: 401 Unauthorized 错误排查与解决

问题描述

在PowerShell终端执行node .\index.js时,反复遇到DiscordAPIError[0]: 401: Unauthorized错误。已多次更换token,且确认在正确根目录运行命令,问题仍未解决。

代码片段

import { config } from 'dotenv';
import { Client, GatewayIntentBits, Routes } from 'discord.js';
import { REST } from '@discordjs/rest';

config();

const TOKEN = process.env.BOT_TOKEN_CLOUD;
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!`);});

async function main() {
    const commands = [
        {
            name: 'testcommand',
            description: 'test command'
        },
    ];
    try {
        console.log('Started refreshing application (/) commands.');
        await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), {
            body: commands,
        });
        client.login(TOKEN);
    }   catch (err) {
        console.log(err);
    }
}

main();

错误信息

DiscordAPIError[0]: 401: Unauthorized
at SequentialHandler.runRequest (file:///C:/Users/Name/Documents/djs-v14/node_modules/@discordjs/rest/dist/lib/handlers/SequentialHandler.mjs:283:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (file:///C:/Users/Name/Documents/djs-v14/node_modules/@discordjs/rest/dist/lib/handlers/SequentialHandler.mjs:95:14)
at async REST.request (file:///C:/Users/Name/Documents/djs-v14/node_modules/@discordjs/rest/dist/lib/REST.mjs:48:22)
at async main (file:///C:/Users/Name/Documents/djs-v14/index.js:32:9) {
rawError: { message: '401: Unauthorized', code: 0 },
  code: 0,
  status: 401,
  method: 'PUT',
  url: 'https://discord.com/api/v10/applications/CLIENT_ID/guilds/948742790421053482/commands',
  requestBody: { files: undefined, json: [ [Object] ] }
}

解决方法

你的代码存在一个直接错误:初始化REST客户端时,你传入的是字符串'TOKEN'而非定义好的变量TOKEN,导致API请求使用无效的token字符串,触发401未授权错误。

修改这一行代码:

const rest = new REST({ version: '10' }).setToken('TOKEN');

改为:

const rest = new REST({ version: '10' }).setToken(TOKEN);

此外,建议额外检查以下几点:

  • 确认.env文件中BOT_TOKEN_CLOUD的token值无多余空格或换行符
  • 确保机器人已被邀请到目标服务器,且拥有applications.commands权限
  • 验证.env中的CLIENT_ID和GUILD_ID与Discord开发者后台信息完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:45:47