pythonpython-3.xdiscorddiscord.pynextcord

Discord.py getting avatar if user isn't in same guild


How can I get a user avatar if the user is not in the same guild as the bot, but in mutual guilds?

I'm trying to get the user avatar from a mutual server.


Solution

  • How to get the user

    You can use await bot.fetch_user(user_id) to retrieve any user. You don't want to use bot.get_user(user_id) for various reasons here.

    How to get the image url

    You can use the avatar URL by using user.avatar.url (user being the class fetched by bot.fetch_user() and avatar is an asset links below)

    Example code

    @tree.command()
    async def avatar_from_another_guild(ctx, id_:str):  # id_ is the user id to fetch
        print(id_)
        user = await bot.fetch_user(int(id_))  # retrieve user here
        try:
            await ctx.response.send_message(user.avatar)  # send final product
        except AttributeError as err:  # error catching if invalid id is inserted
            print(user)
            await ctx.response.send_message("User not found." + str(err))
    

    Example code product

    image of example code working as intended

    py-cord variation

    @bot.slash_command()  # this is the only difference, everything else is the same
    async def avatar_from_another_guild(ctx, id_):
        print(id_)
        user = await bot.fetch_user(int(id_))
        try:
            await ctx.respond(user.avatar)
        except AttributeError:
            print(user)
            await ctx.respond("User not found.")
    

    Note: product is the same for both

    Resources