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

升级Discord.js v14遇TypeError:无法读取null的status属性

升级Discord.js v14后出现TypeError错误

错误信息

TypeError: Cannot read properties of null (reading 'status')

报错代码片段

setInterval(function() {
    let today = new Date();
    time = fancyTime(today);
    for (let i = 0; i < list.length; i++) {
        if (!(list[i].presence.status == "offline")) {
            // 如果用户不在线,更新数组为绿色圆圈并标记他们尚未离线
            if (list[i].presence.status == "idle") {
                timeList[i] = ":orange_circle:  " + time;
            } else if (list[i].presence.status == "dnd") {
                timeList[i] = ":red_circle:  " + time;
            } else {
                timeList[i] = ":green_circle:  " + time;
            }
            firstOffline[i] = 1;
        } else if ((list[i].presence.status == "offline") && (firstOffline[i] == 1)) {
            // 如果用户离线且是第一次离线,更新数组为当前时间并标记首次离线
            timeList[i] = ":white_circle:  " + time;
            firstOffline[i] = 0;
        }
    }
    // 将值备份到文本文件
    fs.writeFile("timeListBackup.txt", timeList, (err) => {});
    fs.writeFile("firstOfflineBackup.txt", firstOffline, (err) => {});
}, 1000)

问题原因与解决方案

在Discord.js v14中,list[i].presence返回null是导致报错的核心原因,主要由两点变化引发:

  1. 网关意图权限收紧:v14要求必须主动声明GuildPresences和GuildMembers意图,才能获取用户在线状态数据,否则presence会为null。
  2. 缓存机制调整:v14对用户缓存的处理更严格,若目标用户不在机器人缓存池中,presence同样会返回null。

具体修复步骤

  • 启用必要网关意图:创建客户端实例时,添加对应意图配置:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildPresences,
        GatewayIntentBits.GuildMembers
    ]
});

同时需在Discord开发者门户的机器人设置中,开启Privileged Gateway Intents下的Presence Intent和Server Members Intent权限。

  • 添加空值防御检查:在读取presence.status前先判断presence是否存在,避免访问null的属性:
    修改循环内代码如下:
for (let i = 0; i < list.length; i++) {
    // 先处理presence为null的情况
    if (!list[i].presence) {
        if (firstOffline[i] === 1) {
            timeList[i] = ":white_circle:  " + time;
            firstOffline[i] = 0;
        }
        continue;
    }

    // 原状态判断逻辑
    if (list[i].presence.status !== "offline") {
        if (list[i].presence.status === "idle") {
            timeList[i] = ":orange_circle:  " + time;
        } else if (list[i].presence.status === "dnd") {
            timeList[i] = ":red_circle:  " + time;
        } else {
            timeList[i] = ":green_circle:  " + time;
        }
        firstOffline[i] = 1;
    } else if (firstOffline[i] === 1) {
        timeList[i] = ":white_circle:  " + time;
        firstOffline[i] = 0;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:05:25