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 :)