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

Discord.js 12.0.0中msg.content返回空值问题求助

问题描述

我正在使用discord.js v12.0.0开发一个统计查询机器人,为了快速完成项目,不想处理斜杠命令和意图配置,但编写命令后发现无法正常工作。通过console.log打印msg.content排查时,发现msg.content及msg本身均显示为空值。确认并未运行自机器人(已知自机器人可能引发此类问题)。

相关截图

控制台输出为空
代码中的console.log(msg)
msg对象为空

机器人代码

import Discord from 'discord.js';
const client = new Discord.Client();
import fetch from 'node-fetch';

client.on('ready', () => {
  console.log(`online`);
});

let lb;

async function fet() {
  await fetch("https://login.deadshot.io/leaderboards").then((res) => {
      return res.json();
  }).then((res) => {
    lb = res;
  })
}

client.on('message', async msg => {
  console.log(msg)
  let channel = msg.channel.id;
  if (msg.author.id == client.user.id) return;
  if (channel != 1015992080897679370) return;
  await fet();
  let r;
  for (var x in lb.all.kills) {
    if (msg.content.toLowerCase() == lb.all.kills[x].name.toLowerCase()) {
      r = lb.all.kills[x].name;
    }
  }
  if (!r) return msg.channel.send('Error: user not found')
})

client.login(token)

解决方案

核心原因

Discord的网关意图系统要求机器人必须声明所需的权限才能接收对应事件的数据。即使是discord.js v12,当前Discord API也要求机器人开启消息相关的意图,否则无法获取到完整的Message对象及msg.content。

修复步骤

  1. 开启开发者门户的特权意图
    进入Discord开发者门户,找到你的机器人应用,切换到Bot页面,在Privileged Gateway Intents区域,开启Message Content Intent(若该选项不存在,需开启GUILD_MESSAGES相关权限)。

  2. 修改客户端初始化代码,添加意图配置
    在创建Discord.Client实例时,指定所需的网关意图:

    import Discord from 'discord.js';
    // 配置必要的网关意图,确保能接收服务器消息
    const client = new Discord.Client({
      intents: [
        Discord.Intents.FLAGS.GUILDS,
        Discord.Intents.FLAGS.GUILD_MESSAGES
      ]
    });
    import fetch from 'node-fetch';
    
    // 后续代码保持不变...
    
  3. 额外检查

    • 确认机器人邀请链接包含bot权限,确保基础访问权限正常
    • 确保机器人在目标服务器中有查看频道和发送消息的权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:42:24