【问题标题】:Count all members with a specific role with Discord Py使用 Discord Py 计算具有特定角色的所有成员
【发布时间】:2021-02-17 22:11:21
【问题描述】:

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

NameError:名称“角色”未定义

谢谢!

【问题讨论】:

  • 这只是意味着“角色”不存在,所以你必须定义一个具有该名称的变量。

标签: python discord.py


【解决方案1】:

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))

【讨论】:

  • 您好,感谢您的帮助,当我运行命令时我得到 0,我尝试只打印列表,但它是空的。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    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")
    

    【讨论】:

    • 有点复制粘贴的答案,你所做的只是“扩展”一点经过验证的答案
    • 两年前我自己编写了这段代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2021-11-17
    • 2021-06-29
    • 1970-01-01
    • 2020-10-20
    • 2021-02-01
    相关资源
    最近更新 更多