简体   繁体   中英

How to count members belonging to a certain role in Discord.js bot?

I'm trying to implement a function which messages the count of users assigned to a certain role. A few months ago this worked flawlessly, but after a certain update it just stopped working correctly.

let count = message.guild.members.filter(m => m.roles.find(r => r.name === roleName)).size;
message.channel.send(user + " Count of users in " + roleName + ": "+count);

My code now looks like this:

let count = message.guild.members.cache.filter(m => m.roles.cache.find(r => r.name === roleName)).size; //These commands are in a module export, message is an object passed as an argument into it
message.channel.send(user + " Count of users in " + roleName + ": "+count);

Easy to say it doesn't work and it usually returns count of users that recently messaged or interacted with the bot. I tried using various .fetch() but they just return:

UnhandledPromiseRejectionWarning: Error [GUILD_MEMBERS_TIMEOUT]: Members didn't arrive in time

...or something similair. I tried guild.members.fetch() / guild.fetch() and such. Any help would be appreciated.

You need to enable the SERVER MEMBERS INTENT in your application. 在此处输入图像描述

You dont need to fetch all users or enable server members intent for such a feature.

You can send GET request to https://discord.com/api/v8/guilds/<guildID>/roles/member-counts endpoint.

This will return a response like this:

{
    "538088986342719490": 1,
    "593404972922830848": 2,
    ...
    // "roleID": memberCount,
}

In Discord.js v13 + The Syntax is:

const Guild = message.guild;
let Rolecount = Guild.members.cache.filter(m => m.roles.cache.find(r => r.name === 'RoleNameHere')).size;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM