簡體   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