user13840650
user13840650

Reputation:

Find the total of members online/offline Discord.js

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

Answers (2)

Chinmay Kabi
Chinmay Kabi

Reputation: 518

Previous answers may not be working because since Oct 2020 the intents are turned off by default.

Finally this is what I found to be working, asking for intent.

Intents

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.

Privileged Intent

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

Enable Intents

  • 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"
]);
  • Step 3- Now to get a map of all online members, just do
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

Jakye
Jakye

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

Related Questions