Justyn
Justyn

Reputation: 85

Discord list all members python

I´m trying to make a bot to make a list of members that owns a role I ask (Command: $role Admin Answer: 3 people have role Admin) and when I will ask (Command: $role list Admin Answer: @Justyn, @JustBoy, @JustBoss).

I tried this code:

@bot.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def members(ctx,*args):
    server = ctx.message.guild
    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 ctx.send("Role doesn't exist")
        return
    for member in server.members:
        if role_id in member.roles:
            await ctx.send(f"{member.display_name} - {member.id}")

but when I ask $members Botz, the answer is only "Justyn Bot - 799779320906121236" (On the server I have 8 bots with role Botz but it only lists own bot (itself) ). So I am confused.

If anyone knows how to do it please tell me! Thank you.

Upvotes: 0

Views: 733

Answers (2)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

Listing members

Guild.members requires intents.members enabled, to enable them:

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(..., intents=intents)

Also make sure to enable them in the developer portal, (here's how)

EDIT

Listing members with a particular role

async def whatever(ctx, role: discord.Role): # The `role` arg will be converted to a `discord.Role` instance
    await ctx.send(f"There's {len(role.members)} users with the role {role.name}")

Reference:

Upvotes: 2

Nurqm
Nurqm

Reputation: 4743

You have to enable intents from Discord Developer Portal and also you have to define it in your code in order to use some events and methods like discord.Member.roles.

In Developer Portal, you have to do:

Select Application -> Bot -> Privileged Gateway Intents -> Enable Presence Intent & Server Members Intent

In your code:

import discord
from discord.ext import commands

intents = discord.Intents().all()
bot = commands.Bot(command_prefix="<prefix>", intents=intents)

For more information, you can check API References about intents.

Upvotes: 0

Related Questions