Reputation: 3
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!
Upvotes: 0
Views: 3494
Reputation: 1
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")
Upvotes: -1
Reputation: 11
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
Upvotes: 1
Reputation: 4225
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))
Upvotes: 4