Search code examples
pythonpython-3.xdiscorddiscord.py

How can I fix this error in my avatar command that I'm getting?


I need to fix this error, I'm not very good with APIs. I am keen to understand how to fix it, since I'm trying to learn Python.

The code:

@client.command()
async def avatarimg1(ctx, username):
    user = await roblox.get_user_by_username(username)
    embed = Embed(title=f"Avatar of {user.name}")
    response = requests.get(f'https://thumbnails.roblox.com/v1/users/avatar?userIds={user.id}&size=420x420&format=Png&isCircular=false')
    json_data = json.loads(response.text)
    imagesj = json_data["imageUrl"]
    
    embed.set_thumbnail(imagesj)
    await ctx.send(embed=embed)

Error:

> Ignoring exception in command avatarimg1: Traceback (most recent call
> last):   File
> "/home/runner/dasdasdasd/venv/lib/python3.8/site-packages/discord/ext/commands/core.py",
> line 85, in wrapped
>     ret = await coro(*args, **kwargs)   File "main.py", line 40, in avatarimg1
>     imagesj = json_data["imageUrl"] KeyError: 'imageUrl'
> 
> The above exception was the direct cause of the following exception:
> 
> Traceback (most recent call last):   File
> "/home/runner/dasdasdasd/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py",
> line 939, in invoke
>     await ctx.command.invoke(ctx)   File "/home/runner/dasdasdasd/venv/lib/python3.8/site-packages/discord/ext/commands/core.py",
> line 863, in invoke
>     await injected(*ctx.args, **ctx.kwargs)   File "/home/runner/dasdasdasd/venv/lib/python3.8/site-packages/discord/ext/commands/core.py",
> line 94, in wrapped
>     raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an
> exception: KeyError: 'imageUrl'

What can I try next?


Solution

  • The first layer of the response has only one key data which is a list so, you need to get the first element and access imageUrl key on that.

    imagesj = json_data['data'][0]['imageUrl']