Reputation: 63
I have a function which counts all active members on active server
I've tried to get into client.guilds.cache
then filter users by their presence.status
to check if the user is online. As far as I am aware what's happening .size
should return a number of active members on the server, but instead it returns 0, no matter what I try.
Here's the code I've tried
I call function in client.on
here and pass client as an argument
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers],
});
client.on("ready", () => {
activeMembersCounter(client)
});
Then in activeMembersCounter.ts
function activeMembersCounter(client: Client<boolean>): void {
const guild = client.guilds.cache.get(config.GUILD_ID);
const onlineMembers = guild.members.cache.filter((m) => m.presence?.status === "online"&& !member.user.bot).size;
console.log(onlineMembers) // logs 0
}
I've also tried async
version with fetch
async function activeMembersCounter(client: Client<boolean>): Promise<void> {
const guild = client.guilds.cache.get(config.GUILD_ID);
const onlineMembers = (await guild.members.fetch()).filter((member) => member.presence?.status === "online" && !member.user.bot);
console.log(onlineMembers.size);
}
I'm not 100% sure if my approach is correct here. I would love to get some advice :)
Upvotes: 2
Views: 1296
Reputation: 1
If you want to include DND && Idle members you need to use m.presence?.status != null
rather than using m.presence?.status != "offline"
Upvotes: 0
Reputation: 190
Two things you need to change.
Use the GatewayIntentBits.GuildPresences flag, m.presence returns null if you don't use it.
member is undefined in your online members variable. Use m.user.bot instead of member.user.bot.
Working code:
const { GatewayIntentBits, Client} = require('discord.js');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences],
});
function activeMembersCounter(c) {
const guild = c.guilds.cache.get("GUILD_ID");
console.log(guild);
const onlineMembers = guild.members.cache.filter((m) => m.presence?.status == "online" && !m.user.bot).size;
console.log(onlineMembers);
}
client.once('ready', () => {
activeMembersCounter(client);
})
Edit: If you're looking for active members, this could include DND members and Idle members. You might want to consider using m.presence?.status != "offline"
instead of m.presence?.status == "online"
to include these other statuses in your count.
Upvotes: 2