Python get all members list from a specific role

你离开我真会死。 提交于 2019-12-08 03:31:20

问题


How to get a members list from a specific role with !getuser command in discord channel.

@bot.command(pass_context=True)  
async def getuser(ctx):

bot replys with their ID

 1. @user1#123
 2. @user2#123

回答1:


The rewrite branch provides an attribute Role.members.

On the async branch, you'll have to loop through all the members of the server and check their roles.

@bot.command(pass_context=True)  
async def getuser(ctx, role: discord.Role):
    role = discord.utils.get(ctx.message.server.roles, name="mod")
    if role is None:
        await bot.say('There is no "mod" role on this server!')
        return
    empty = True
    for member in ctx.message.server.members:
        if role in member.roles:
            await bot.say("{0.name}: {0.id}".format(member))
            empty = False
    if empty:
        await bot.say("Nobody has the role {}".format(role.mention))



回答2:


Hopefully a faster and more readable solution than the one before

@bot.command(pass_context=True)  
async def getuser(ctx,*args):
  server = ctx.message.server
  role_name = (' '.join(args))
  role_id = server.roles[0]
  for role in server.roles:
    if role_name == role.name:
      role_id = role
      break
  else:
    await bot.say("Role doesn't exist")
    return    
  for member in server.members:
    if role_id in member.roles:
      await bot.say(f"{role_name} - {member.name}")


来源:https://stackoverflow.com/questions/52025872/python-get-all-members-list-from-a-specific-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!