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

Discord.js机器人随机崩溃:Cannot read property 'cache' of undefined报错排查

问题分析与解决方案

核心原因

你遇到的报错本质是discord.js v14强制要求显式声明客户端需要的网关权限(Intents),你的代码里new Discord.Client()未传入任何Intents参数,导致客户端无法正确订阅消息相关的网关事件,也无法缓存频道数据。当有消息触发MESSAGE_CREATE事件时,discord.js无法找到对应的频道对象(channel为undefined),进而访问channel.messages.cache时报错。

修复步骤

1. 修正客户端初始化代码

创建Client实例时必须传入包含必要权限的intents配置,至少需要开启Guilds和GuildMessages权限;如果需要读取消息内容,还要加上MessageContent权限(需在Discord开发者后台额外开启)。

修正后的代码:

const { Client, GatewayIntentBits } = require("discord.js");
// 声明需要的网关权限
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent // 若需读取消息内容则添加
  ]
});

var prefix = "!";
require('events').EventEmitter.defaultMaxListeners = 99;

client.login("XXX");

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

2. 开启Discord开发者后台的特权网关权限

如果使用了MessageContent权限,需要登录Discord开发者平台,找到你的机器人应用:

  • 进入「Bot」页面
  • 下拉到「Privileged Gateway Intents」区域,开启「Message Content Intent」开关

3. 额外排查(可选)

  • 你的Node.js版本16.13.1符合discord.js v14的最低要求(v16.9.0+),无需调整
  • 检查Synology NAS的网络稳定性,偶尔的WebSocket断连可能导致缓存不同步,但核心问题仍是网关权限缺失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:20:33