Sunday, October 31, 2021

[SOLVED] Discord Bot Client.User Error Converting to Discord.Utils in Python

Issue

python 3.7.3 discord.py 1.3.4 raspberry pi 4

I'm stuck at the beginning, after everything was working.

I started over from scratch. When I use the for loop followed by my print(f'{client.user} I have no issues and the bot username prints to the terminal. When I ditch the loop and use the guild = discord.utils.get(client.guilds, name=GUILD) code, I get the following error in the terminal.

Ignoring exception in on_ready Traceback (most recent call last): File "/home/pi/.local/lib/python3.7/site-packages/discord/client.py", line 312, in _run_event await coro(*args, **kwargs) File "/home/pi/TackleBot/bot2.py", line 27, in on_ready f'{client.user} is connected to the following guild:\n' AttributeError: 'NoneType' object has no attribute 'name'

If I add a print(client.user) command directly after the guild = discord.utils.get command, it will print the user name there, and still error out below. I've spent hours combing through documentation, and this is where I'm at now. Still confused. If I comment out the for loop, I get the error. If I comment out the discord utility command, it works fine. Never changing anything with the print(f'{client.user} block.

I'm learning as I go, any help or advice is immensely appreciated. Thank you!

    import os
    
    import discord

    from dotenv import load_dotenv

    load_dotenv()
    TOKEN = os.getenv('DISCORD_TOKEN')
    GUILD = os.getenv('DISCORD_GUILD')
    
    client = discord.Client()

    @client.event
    async def on_ready():
        guild = discord.utils.get(client.guilds, name=GUILD)
        if guild is not None:
            channel = discord.utils.get(guild.text_channels, name=GUILD)
    # when the lines 18-20 are used, line 26 throws an object type error 'none'
    # when lines 23-25 are used, there is no error
    #    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})'
        )
        
        members = '\n - '.join([member.name for member in guild.members])
        print(f'{guild.name}:\n - {members}')
    
    client.run(TOKEN)

Solution

If I understand correctly, you're trying to print the guild info in the on_ready function first, right?

You can do it like this:

client = discord.Client()
@client.event
async def on_ready():
     for guild in client.guilds:
         print(
          f'{client.user} is connected to the following guild:\n'
          f'{guild.name}(id: {guild.id})'
         )
     members = '\n - '.join([member.name for member in guild.members])
     print(f'Guild Members:\n - {members}')

Finally:

client.run(TOKEN)


Answered By - Costa