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

如何在Discord.js v13中统计指定服务器的在线成员数量

错误根因

你遇到的报错是部分成员的presence字段为undefined导致的空指针异常。即使已经开启了对应intent和特权网关,也可能因为拉取成员时未要求返回状态数据、本地缓存缺失、用户长时间离线未同步状态等原因出现该情况。

解决方法

  1. 拉取成员时显式要求携带状态数据
    调用interaction.guild.members.fetch()时传入{ withPresences: true }参数,强制Discord API返回所有成员的在线状态信息,避免返回的成员对象缺失presence字段。
  2. 过滤逻辑增加空值兼容
    使用可选链操作符判空,presence不存在的成员统一视为离线,避免空指针报错。

完整可运行代码

// 拉取全量成员+同步在线状态
const allMembers = await interaction.guild.members.fetch({ withPresences: true });
// 过滤非机器人、在线成员
const onlineNonBotMembers = allMembers.filter(member => {
  return !member.user.bot && member.presence?.status !== "offline";
});
// 在线成员数量
const onlineCount = onlineNonBotMembers.size;

版本适配说明

如果你使用的是discord.js v14版本,原有intents写法已经弃用,需要调整为如下写法:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildPresences
    ],
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:48:00