Reputation:
Hello I am making a server state command and I do not know how to find the total members online/offline so if someone could help me that would be awesome. :)
Upvotes: 3
Views: 11554
Reputation: 518
Finally this is what I found to be working, asking for intent.
Maintaining a stateful application can be difficult when it comes to the amount of data you're expected to process, especially at scale. Gateway Intents are a system to help you lower that computational burden.
Basic information about the guild without any extra effort. But there is some data that is not found in the payload until Privileged intents are enabled. One of the privileged intents as of this answer are GUILD_PRESENCES
. Read the docs here
Step 1: Go to discord developer portal -> your app -> bot then select the presence intent
Step 2:
const Discord = require('discord.js');
const intents = new Intents([
Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need
"GUILD_MEMBERS", // lets you request guild members
"GUILD_PRESENCES"
]);
let onlineMembers = (await guild.members.fetch()).filter((member) => !member.user.bot && member.user.presence.status == 'online'); // Remove the bot check as per use
There are 4 status you can check for now, unlike what was done in previous answers online
, offline
, idle
, dnd
.
Upvotes: 6
Reputation: 6645
client.on("message", message => {
if (message.author.bot) return false;
if (message.content.toLowerCase() == "stats") {
const Embed = new discord.MessageEmbed();
Embed.setTitle(`Server Stats`)
// Using Collection.filter() to separate the online members from the offline members.
Embed.addField("Online Members", message.guild.members.cache.filter(member => member.presence.status !== "offline").size);
Embed.addField("Offline Members", message.guild.members.cache.filter(member => member.presence.status == "offline").size);
message.channel.send(Embed);
};
});
Upvotes: 7