Toasty
Toasty

Reputation: 1880

How to count all online members using v13?

So I'm currently trying to get all online members in a specific guild and count them. I already tried these methods:

let onlineMembers = (await interaction.guild.members.fetch()).filter(
      (member) => !member.user.bot && member.user.presence.status !== "offline"
    );

and

let onlineMembers = interaction.guild.members.cache.filter(member => member.presence.status !== "offline").size

I also tried fetching all members first and filter the result like this:

const allMembers = await interaction.guild.members.fetch();
const onlineMembers = allMembers.filter(member => !member.user.bot && member.presence.status !== "offline");

But I'm always getting this exception:

TypeError: Cannot read property 'status' of undefined

So I went looking for a solution and I noticed that I manually have to activate all intents I want my bot to use. I "activated" the needed intents in my index.js like this:

const client = new Client({
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.GUILD_MEMBERS,
        Intents.FLAGS.GUILD_PRESENCES
    ],
});

But this didn't fix my problem either.

In the Discord Developer Portal I also enabled both privileged gateway intents:

Privileged Gateway Intents activated

And who could have guessed...it still doesn't work. It's weird, because for some members it's working but I need it to work for every member.

Does somebody know how to fix this?

Upvotes: 1

Views: 1044

Answers (1)

Christoph Blüm
Christoph Blüm

Reputation: 975

Fetching this information changed in V13

This code will generate an Object with the properties online, idle and dnd:

let GUILD_MEMBERS = await client.guilds.cache.get(config.ids.serverID).members.fetch({ withPresences: true })

var onlineMembers = {
 online: await GUILD_MEMBERS.filter((online) => online.presence?.status === "online").size,
 idle: await GUILD_MEMBERS.filter((online) => online.presence?.status === "idle").size,
 dnd: await GUILD_MEMBERS.filter((online) => online.presence?.status === "dnd").size
}

Let me know, if this works for you

Upvotes: 1

Related Questions