简体   繁体   中英

Role member count only counts roles of the user who sent the command discord.js v12

I'm trying to send a list of all of the roles in a server with the member count beside it. It successfully sends the role names but only counts the roles of the user who sent the command. For example, if a user only has RoleA , instead of sending RoleA - 3 RoleB - 5 RoleC - 2 , it will send RoleA - 1 RoleB - 0 RoleC - 0 .

const roles = client.guilds.cache.map(guild => {    
    return guild.roles.cache.map(role=>role.name).flat().filter(item => item !== '');
});

roles.sort().forEach(roleName => {
    let memberCount = msg.guild.roles.cache.find(role => role.name === roleName).members.size;
    
    if(roleName !== '@everyone')
        roles_as_list += '🔘 ' +roleName+ ' - ' +memberCount+ '\n';
});

msg.channel.send(roles_as_list);

It's not a fix for your code, but here is a way how to do it much easier:

let roles_as_list = msg.guild.roles.cache.filter(r => r.name !== `@everyone`).sort().map(r => `🔘 ${r.name} - ${r.members.filter(m => !m.user.bot).size}`).join(`\n`);
msg.channel.send(roles_as_list)

And just like that, you'll have server roles map that excludes bots from the list

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