简体   繁体   中英

Count all members with a specific role with Discord Py

I'm almost new to programming. I wanted to add a function to my bot to count the amount of members with x role, it'll always be the same role. I've been trying to use role.members , but I get the error

NameError: name 'role' is not defined

Thank you!

Use len on Role.members but to get a role you do Guild.get_role(role_id)

Below is the code:

@bot.command()
async def rolemembers(ctx):
    role = ctx.guild.get_role(ROLE_ID)
    await ctx.send(len(role.members))

probably a bit late but you might want to check using intents in order to use the solution.

Ref: Discord Bot can only see itself and no other users in guild

Copy me This is the simplest way ever

import discord
from discord.ext import commands,tasks
intents = discord.Intents.default()  
intents.members = True

#If without intents It will return 0 so it should be like this



bot = commands.Bot(command_prefix='?',intents=intents)

@bot.command()
#You can create any name 
async def users_in_role(ctx,role: discord.Role):  
  
  #this will give the length of the users in role in an embed
  embed = discord.Embed(description = 
  f"**Users in role:**\n{len(role.members)}")
  await ctx.send(embed=embed)

@bot.event
async def on_ready():
  print('bot online')

#in the discord type ``?users_in_role @role_name`` example ``?users_in_role @Owner``


#for the discord token you should go to discord.dev and make an application and in the bot page create a bot and then copy its token

bot.run("BOT_TOKEN_HERE")

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