[英]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.
我想在我的机器人中添加一个 function 来计算具有 x 角色的成员数量,它始终是相同的角色。 I've been trying to use
role.members
, but I get the error我一直在尝试使用
role.members
,但出现错误
NameError: name 'role' is not defined
NameError:未定义名称“角色”
Thank you!谢谢!
Use len
on Role.members
but to get a role you do Guild.get_role(role_id)
在
Role.members
上使用len
但要获得角色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参考: Discord Bot 只能看到自己,而不能看到公会中的其他用户
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.