Search code examples
pythonpython-3.xpycharmdiscorddiscord.py

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


I have recently been following this tutorial to get myself started with Discord's API. Unfortunately, when I got the part about printing all the users in the guild I hit a wall.

When I try to print all users' names it only prints the name of the bot and nothing else. For reference, there are six total users in the guild. The bot has Administrator privileges.

import os
import discord

TOKEN = os.environ.get('TOKEN')
client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        print(guild, [member.name for member in guild.members])

client.run(TOKEN)

Solution

  • As of discord.py v1.5.0, you are required to use Intents for your bot, you can read more about them by clicking here In other words, you need to do the following changes in your code -

    import discord
    from dotenv import load_dotenv
    
    load_dotenv()
    TOKEN = os.getenv('DISCORD_TOKEN')
    GUILD = os.getenv('DISCORD_GUILD')
    
    intents = discord.Intents.all()
    client = discord.Client(intents=intents)
    
    @client.event
    async def on_ready():
        for guild in client.guilds:
            if guild.name == GUILD:
                break
    
        print(
            f'{client.user} is connected to the following guild: \n' 
            f'{guild.name} (id: {guild.id})'
        )
    
        # just trying to debug here
        for guild in client.guilds:
            for member in guild.members:
                print(member.name, ' ')
    
        members = '\n - '.join([member.name for member in guild.members])
        print(f'Guild Members:\n - {members}')
        
    client.run(TOKEN)