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

如何基于discord.js实现Discord在线成员计数器?

Convert Total Member Counter to Online Member Counter in discord.js

Hey there! Switching from tracking total members to online members is totally doable with a few key tweaks. Let's walk through the implementation, including important details to keep your counter accurate and reliable:

Key Background

Discord categorizes "online" members as those with one of these statuses:

  • online (actively using Discord)
  • idle (away from keyboard)
  • dnd (do not disturb)

Members marked offline get excluded from this count. Critical note: Make sure your bot has these privileged intents enabled in the Discord Developer Portal (under Bot > Privileged Gateway Intents):

  • Server Members Intent
  • Presence Intent

Without these, your bot won't be able to access member presence data, and your online count will be wrong.

Modified Code

Here's your updated script with online member tracking, error handling, and better reliability:

module.exports = async (client) => { 
  // Replace with your actual guild ID
  const targetGuildId = '$$$$$';
  // Replace with your counter channel ID
  const targetChannelId = '$$$$$';

  // Helper function to handle the count update
  const updateOnlineMemberCount = async () => {
    try {
      // Fetch the guild to ensure we have the latest server data
      const guild = await client.guilds.fetch(targetGuildId);
      if (!guild) {
        console.error("Couldn't locate the specified guild!");
        return;
      }

      // Fetch all members in the guild (cache might be incomplete, so this ensures accuracy)
      await guild.members.fetch();

      // Filter out offline members; optional chain operator prevents errors for missing presence data
      const onlineMembers = guild.members.cache.filter(member => 
        member.presence?.status !== 'offline'
      );
      const onlineCount = onlineMembers.size;

      // Grab the counter channel and update its name
      const counterChannel = guild.channels.cache.get(targetChannelId);
      if (!counterChannel) {
        console.error("Couldn't find the specified counter channel!");
        return;
      }

      await counterChannel.setName(`Aventureiros Online: ${onlineCount.toLocaleString()}`);
      console.log(`Updated online member count to: ${onlineCount}`);
    } catch (error) {
      console.error("Error updating online member count:", error);
    }
  };

  // Run the update immediately when the bot starts (no waiting 15 minutes!)
  await updateOnlineMemberCount();
  // Repeat the update every 15 minutes (900000 milliseconds)
  setInterval(updateOnlineMemberCount, 900000); 
}

What Changed & Why?

  • guild.members.fetch(): This pulls the full list of members from Discord instead of relying on local cache, which might miss members who haven't interacted with the bot recently.
  • Presence filtering: The filter checks for non-offline statuses, and the ?. operator avoids crashes if a member's presence data isn't available.
  • Error handling: The try/catch block catches issues like invalid IDs, missing permissions, or API errors—so your bot won't crash unexpectedly.
  • Immediate initial update: The counter updates as soon as the bot starts, instead of making users wait 15 minutes for the first refresh.

Quick Final Checks

  • Ensure your bot has the Manage Channels permission in the server (it needs this to rename the counter channel).
  • Double-check that you've replaced the placeholder IDs ($$$$$) with your actual guild and channel IDs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 08:47:45