繁体   English   中英

使用 Discord Py 计算具有特定角色的所有成员

[英]Count all members with a specific role with Discord Py

我几乎是编程新手。 我想在我的机器人中添加一个 function 来计算具有 x 角色的成员数量,它始终是相同的角色。 我一直在尝试使用role.members ,但出现错误

NameError:未定义名称“角色”

谢谢!

Role.members上使用len但要获得角色Guild.get_role(role_id)

下面是代码:

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

可能有点晚了,但您可能想检查使用意图以使用解决方案。

参考: Discord Bot 只能看到自己,而不能看到公会中的其他用户

复制我这是有史以来最简单的方法

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.

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