discord.js attempting to get guildMember.presence.status results in "Cannot read properties of undefined (reading 'status')"

Viewed 950

I've been messing around with discord.js and have been trying to make a command that will allow me to list out all the online users in a server (Guild). This snippet isn't entirely mine, but from my understanding, I'm taking out the guild object from the interaction, and going further in to take out the guild member manager. From there the fetch method is called to get a collection of all the members which then gets filtered by the status.

async execute(interaction) {
    let { guild: { members } } = interaction;
    let allMembers = await members.fetch();
    let onlineUsers = allMembers.filter((member) => member.presence.status !== 'offline');
    let usernames = onlineUsers.map((member) => member.displayName);
    // array of usernames of users who are not offline
    console.log(usernames);

The error that I get is:

TypeError: Cannot read properties of undefined (reading 'status')

It seems that this error occurs when there are other users/other bots which are offline at the time when I run node index.js which I think is worth mentioning.

I believe to have declared my intents correctly:

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

This is what the Discord developer portal looks like.

Any help would be appreciated!

1 Answers

Yeah I had the same issue a few weeks ago... this solved my problem:

let guildMembers = await <guild>.members.fetch({ withPresences: true })

var onlineMembers = await guildMembers.filter(member => member.presence?.status != "offline").size

If you want to exclude bots from counting, change the second line to this:

var onlineMembers = await guildMembers.filter(member => !member.user.bot && member.presence?.status != "offline").size

So you may have noticed, that it works now only by adding ?. after presence, but why?

Mozilla explains it like this:

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

This means, if presence is undefined or null, the ?. returns undefined or null instead of stopping the program and throwing an error. This member's status won't be added to the collection and the bot continues counting.

If you want to learn more, here's the source


Note

Keep in mind that onlineMembers will never be 100% accurate. There are always members whose status cannot be read!

Related