如何基于discord.js实现Discord在线成员计数器?
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
filterchecks for non-offline statuses, and the?.operator avoids crashes if a member's presence data isn't available. - Error handling: The
try/catchblock 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 Channelspermission 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

