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

Discord.js中messageCreate触发但无法获取消息内容,求排查原因

Discord机器人无法获取消息内容的原因及解决方法

问题描述

使用最新版discord.js的messageCreate事件监听消息,机器人所在服务器收到的消息无法被正确识别:日志中content为空字符串,embeds和attachments均为空数组,相关代码及日志如下:

相关代码

client.on('messageCreate', async message => {

    console.log(`Received message from ${message.author.tag} in ${message.guild ? message.guild.name : 'DM'}:`);
    console.log(`Content: ${message.content}`);
    console.log(`Embeds: ${JSON.stringify(message.embeds)}`);
    console.log(`Attachments: ${JSON.stringify(message.attachments)}`);

    // Ignore messages from bots
    if (message.author.bot) return;

    if (message.content === '!bitcoin') {
        try {
            const price = await getBitcoinPrice();
            message.channel.send(`The current price of Bitcoin is $${price}`);
        } catch (error) {
            if (error instanceof FetchError) {
                message.channel.send(error.message);
            } else {
                message.channel.send('An unexpected error occurred.');
            }
        }
    }
});

日志输出

Logged in as [bot-name]
Received message from [user] in [server-name]:
Content: 
Embeds: []
Attachments: []

核心原因及解决办法

  • 缺少消息内容权限(Message Content Intent)
    这是v14+版本discord.js最常见的问题:

    1. 登录Discord开发者后台,进入你的应用→Bot页面,在「Privileged Gateway Intents」下开启Message Content Intent;
    2. 实例化Client时必须显式声明该intent,否则无法获取消息内容:
      const { Client, GatewayIntentBits } = require('discord.js');
      const client = new Client({
        intents: [
          GatewayIntentBits.Guilds,
          GatewayIntentBits.GuildMessages,
          GatewayIntentBits.MessageContent, // 必填
          GatewayIntentBits.DirectMessages
        ]
      });
      
    3. 确保机器人在目标服务器中拥有「查看频道」和「读取消息历史」权限,否则即使intent开启也无法获取消息。
  • 消息类型为系统消息
    部分系统消息(如成员加入通知、频道创建提示等)本身没有content内容,确认测试时发送的是普通用户文本消息,而非系统通知类消息。

  • discord.js版本不兼容
    确认使用的是v14及以上稳定版,旧版本的intent声明方式已被废弃,会导致权限不生效。可通过npm list discord.js查看当前版本,若版本过低执行npm install discord.js@latest更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:06:07