PackOf20
PackOf20

Reputation: 334

Guild Members filter not Accurate

So I've been trying to make a counter which obviously counts the members of the server without the bots, with the bots, and only the bots and for some reason, it's not accurate what so ever. When I get into the general channel and run the command to display the counter, I get these as the output numbers:

Code:

const memberCount = message.guild.members.cache.filter(member => !member.user.bot).size;
const totalCount = message.guild.memberCount;
const botCount = message.guild.members.cache.filter(member => member.user.bot).size;

Output on a server with 20 Members:

1st Output is: 1
2nd Output is: 19 (It excludes itself for some reason? but i can fix that with just +1)
3rd Output is: 1

Clearly there is an issue with the code but I can't pinpoint what it is.

Upvotes: 0

Views: 365

Answers (1)

Skulaurun Mrusal
Skulaurun Mrusal

Reputation: 2847

Try fetching the members instead of reading them from the .cache.

const members = await message.guild.members.fetch();
const memberCount = members.filter(member => !member.user.bot).size;
const botCount = members.filter(member => member.user.bot).size;
const totalCount = members.size;

If you are on discord.js v13, make sure you have GUILD_MEMBERS intent enabled.

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MEMBERS"] });

Note that if you want to cache the members automatically on bot's startup, you need to enable GUILD_PRESENCES intent. Otherwise when GUILD_CREATE event is emitted on the websocket for the bot to cache guilds, members and users. The data won't include any GuildMembers except the bot itself. (That is why it shows you the number 1.)

Tested using discord.js ^13.0.1.

Upvotes: 2

Related Questions