Search code examples
pythonpython-3.xdiscorddiscord.py

I am using discord py and trying to return the users avatar and if they dont have one return a default


I was trying to run the code embed.set_thumbnail(url=interaction.user.avatar.url) in a command yet whenever a user without a pfp tried to use the command it resulting in an error of discord.app_commands.errors.CommandInvokeError: Command 'balance' raised an exception: AttributeError: 'NoneType' object has no attribute 'url'. Is there any way to fix this problem

I used the following code as a "fix" per say and now all commands work yet even if you have a pfp or not it shows up as the default

if interaction.user.avatar.url == True:
   embed.set_thumbnail(url=interaction.user.avatar.url)
 else:
   embed.set_thumbnail(url="https://ubg100.net/images/discord.jpg")
   await interaction.response.send_message(embed=embed)

and then i tried this code:

        if interaction.user.avatar.url == "NoneType":
            embed.set_thumbnail(url=interaction.user.avatar.url)
        else:
          embed.set_thumbnail(url="https://ubg100.net/images/discord.jpg")
        await interaction.response.send_message(embed=embed)

yet i get the error i had before if someone tries to use command without a pfp/avatar


Solution

  • If you want to display default pfp for a non pfp user the consider using display_avatar instead of avatar. As display_avatar would return default discord avatar if no pfp is there.

    Updated code:

    embed.set_thumbnail(url=interaction.user.display_avatar.url)
    

    Docs reference: