How to get all members from my discord py server

Viewed 1509

I want to get all the members of my server, but when I Googled it, I just found that this code snippet would do this:

for guild in client.guilds:                      
 for member in guild.members:                     
  print(member)

Well, this code should display all members, the problem is that it only displays my bot user. But when I put it this way:

@tasks.loop(seconds=10)
async def counter():                                                                           
for guild in client.guilds:                      
 for member in guild.members:                     
  print(guild.members)

it displays information inside this object [ ] and I won't show it exactly because inside this object it has information about my account and discord server, so how can I change this code so that it shows me the number of members or the names of the members?

3 Answers

Printing guild.member returns a discord.Member object which has a lot of information inside it. Here are the ways you would like to opt:

Getting count of members:

for guild in client.guilds:
    print(len(guild.members))

Getting member names:

for guild in client.guilds:
    for member in guild.members:
        print(member.name)

Also I would suggest reducing loop time to avoid getting ratelimited.

how the member count is inside the object [ ] as I pointed out in the question, I accessed the property of this object, and then I managed to get all the members, this was the code:

for guild in client.guilds:
 print(guild.member_count)

Your method is correct which is:

for guild in client.guilds:
    print(guild.member_count)

But as you can see here in the docs

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires Intents.members to be specified.

Therefore, you must enable member intents in code and enable privileged intents in the developer portal

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

#or 
intents = discord.Intents.all()

client = commands.Bot(command_prefix='!', intents=intents)

Member intents are used for the following: link

This corresponds to the following events:

  • on_member_join()

  • on_member_remove()

  • on_member_update() (nickname, roles)

  • on_user_update()

This also corresponds to the following attributes and classes in terms of cache:

  • Client.get_all_members()

  • Guild.chunk()

  • Guild.fetch_members()

  • Guild.get_member()

  • Guild.members

  • Member.roles

  • Member.nick

  • Member.premium_since

  • User.name

  • User.avatar (User.avatar_url and User.avatar_url_as())

  • User.discriminator

Related