'cant get gif URL from tenor api in discord.py

I'm new to python, and dont know what to do.

async def get_gif(searchTerm) -> str:  
async with aiohttp.ClientSession() as session:
    l = 50
    response = await session.get("https://api.tenor.com/v1/search?q={}&key={}&limit={}&media_filter=basic".format(searchTerm, KEY, l))
    ri = random.randint(0, l-1)
    data = json.loads(await response.text())
    gif_choice:str = data['results'][ri]['gif']['url']
    session.close()
    return gif_choice

That is my function rn. Here is the stacktrace:

Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\Lasse\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "d:\dev\Samsara bot\Bot.py", line 133, in on_message g:str = await get_gif("koneko") File "d:\dev\Samsara bot\Bot.py", line 76, in get_gif gif_choice:str = data['results'][ri]['gif']['url'] KeyError: 'gif'



Solution 1:[1]

Here's how I do it. Each result has a media key that has a list that contains an object that contains objects for different sizes. You can access their urls from them. I used 'mediumgif' for mine. There are different formats and sizes you can access like 'tinygif', 'nanogif', or mp4.

data['results'])[ri]['media'][0]['mediumgif']['url']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 3nws