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

Discord.js报错TokenInvalid:提供的令牌无效问题求助

Discord机器人 TokenInvalid 错误排查与解决

问题概述

启动Discord机器人时持续出现 Error [TokenInvalid]: An invalid token was provided. 错误,更换令牌后问题仍未解决,完全遵循教程步骤操作依旧报错。

报错堆栈信息

r.js:136
const invalidToken = new DiscordjsError(ErrorCodes.TokenInvalid);
^

Error [TokenInvalid]: An invalid token was provided.
at WebSocketManager.connect (C:\Users\Trevor\Desktop\NeuroDiscord\node_modules\discord.js\src\client\websocket\WebSocketManager.js:136:26)
at Client.login (C:\Users\Trevor\Desktop\NeuroDiscord\node_modules\discord.js\src\client\Client.js:228:21)
at Object. (C:\Users\Trevor\Desktop\NeuroDiscord\index.js:18:8)
at Module._compile (node:internal/modules/cjs/loader:1369:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1427:10)
at Module.load (node:internal/modules/cjs/loader:1206:32)
at Module._load (node:internal/modules/cjs/loader:1022:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
at node:internal/main/run_main_module:28:49 {
code: 'TokenInvalid'
}

使用的代码

require('dotenv/config')
const { Client, Events, GatewayIntentBits } = require("discord.js")
const { OpenAI } = require("openai")
require("dotenv/config")

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ]
})

client.once(Events.ClientReady, (ClientUser) =>{
    console.log(`logged in as ${clientUser.user.tag}`)
})

client.login(process.env.BOT_TOKEN)

环境信息

  • Node.js v20.12.2

排查与解决建议

  • 检查.env文件配置
    确认.env文件放在项目根目录(与index.js同级),令牌格式为BOT_TOKEN=你的机器人令牌,不要加引号或多余空格。可以临时在代码中添加console.log(process.env.BOT_TOKEN),运行后核对输出是否与Discord开发者后台的令牌完全一致,避免复制时出现字符缺失或冗余。
  • 重新生成有效令牌
    登录Discord开发者门户进入机器人页面,点击"Reset Token"生成新令牌(旧令牌会立即失效),复制后替换到.env文件中,注意不要误用应用的客户端ID或密钥。
  • 修复dotenv加载问题
    代码中重复加载了require('dotenv/config'),可改为只加载一次;若dotenv未正确读取文件,尝试手动指定路径:require('dotenv').config({ path: './.env' })。
  • 确认必要权限
    虽然报错指向令牌,但需确保在Discord开发者门户的Bot页面开启了"Message Content Intent"选项(代码中已使用该意图)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:52:49