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

如何解决discord.js文件中的discord is not defined错误?

解决discord.js中"discord is not defined"错误

问题原因

  • 变量大小写不匹配:你导入discord.js时用的是小写变量名discord,但创建客户端时写的是Discord.Client(),JS是大小写敏感的,Discord这个变量未定义,导致报错。
  • 重复创建客户端实例:代码里先后创建了两个client实例,既冗余又会导致逻辑冲突,且第二个实例未配置必要的intents,无法正常运行。
  • 过时事件监听:discord.js v14及以上版本已移除message事件,需改用messageCreate事件。

修复后的完整代码

const { Client, GatewayIntentBits } = require('discord.js');

// 仅创建一个配置好必要intents的客户端实例
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

client.on('ready', () => {
  console.log("bot on");
});

// 使用discord.js v14+支持的messageCreate事件
client.on('messageCreate', msg => {
  if(msg.content === "text"){
    msg.reply("good");
  }
});

client.login("你的私有令牌");

修复说明

  • 移除了重复的discord.js导入,保留解构导入的方式更简洁高效。
  • 只保留一个配置完整intents的客户端实例,避免资源浪费和逻辑冲突。
  • 将原message事件替换为messageCreate,适配新版本discord.js的API要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 18:38:11