Search code examples
pythongoogle-cloud-platformdiscord.pyaiohttp

Tenor API with aiohttp not working python


i'm creating a discord bot with discord.py. Right now im trying to make it so it sends a gif with the Tenor API. I created my API key with the google cloud tool. This is the code

    async def get_gif(self, search):
        async with aiohttp.ClientSession() as session:  
            key = os.getenv("API_KEY")
            async with session.get("https://g.tenor.com/v1/search?q={}&key={}&limit=1".format(search, key)) as resp:   
                
                if resp.status == 200:     #checks if response is correct
                    resp = await resp.json()
                    resp = resp['results'][0]['media'][0]['gif']['url']
                    return resp
                else:
                    return resp.status
    
    @commands.command(name="gif", aliases=["gf"])
    async def gif(self, ctx, args):
        await ctx.send(await self.get_gif(args))

I'm constantly getting error 401 and i can't figure out why, I tried with requests and it still didn't work. why am i getting this error? Any help is appreciated.


Solution

  • there might be other problems in your code, I didn't check carefully but I think the main issue comes from the url you're using:

    "https://g.tenor.com/v1/search?q={}&key={}&limit=1"
    

    I was using the old documentation from tenor where they use the "v1" api in the url but it is now "v2". This is updated in the new doc. It should work with the following url:

    "https://tenor.googleapis.com/v2/search?q={}&key={}&limit=1"
    

    I am far from an expert so as always I would advise to read the doc carefully.

    Hope it helps.