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

为什么我的discord.js中messageCreate事件无法正常工作?

Discord机器人Ping-Pong命令无响应问题修复

你的代码存在几个关键错误,导致命令无法正常触发,以下是具体修正方案:

错误点分析

  • 事件监听名称错误:discord.js v14及以上版本已废弃message事件,需使用messageCreate事件监听消息创建。
  • 意图参数不规范:'GuildMessages'不能直接用字符串形式,必须使用GatewayIntentBits.GuildMessages枚举值;另外读取消息内容需要额外添加GatewayIntentBits.MessageContent意图,否则无法获取message.content。
  • 变量名不匹配:回调函数参数定义为messageCreate,但内部却使用未定义的message变量,导致逻辑无法执行。

修正后的完整代码

require('dotenv').config();

const { Client, GatewayIntentBits } = require('discord.js');
// 修正意图参数,补充MessageContent意图
const client = new Client({ 
    intents: [
        GatewayIntentBits.Guilds, 
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ] 
});

client.on('ready', () => {
    console.log(`Thunder bot is ready! Tag is ${client.user.tag}`);
});

// 修正事件名称与变量名
client.on('messageCreate', (message) => {
    if (message.content === 'ping'){
        message.reply('Pong!')
    }
});

client.login(process.env.TOKEN);

额外注意事项

  • 需在Discord开发者平台的机器人页面,开启Message Content Intent权限(位于Privileged Gateway Intents选项下),否则即使代码添加了对应意图,机器人也无法读取消息内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:09:27