pythonbotsdiscorddiscord.pygiphy

How would I use the GIPHY Python API with my discord bot?


From my understanding I can use this example from the GIPHY docs (https://gyazo.com/1b6c0094162a54fe49029f665badf8df) to open a url but I don't understand it too much. To add onto that, when I run this code I get the error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'urllib' has no attribute 'urlopen'

My question is how can I randomly import a GIF from certain tags once the user types #giphy in a text channel

Here is my current code: (Code got updated)

@bot.command(pass_context = True)
@commands.cooldown(1, 3, commands.BucketType.user)
async def gif(ctx, *, search):
channel = ctx.message.channel
session = aiohttp.ClientSession()

msg = await bot.send_message(channel, "**searching for " + search + "..**")
randomMessage = await bot.send_message(channel, "**showing a random image due to no images found from your search or you just didn't search anything**")

if search == "":
    randomImage = True
    print("random")
    randomMessage
    response = await session.get("https://api.giphy.com/v1/gif/random?api_keyY=4hnrG09EqYcNnv63Sj2gJvmy9ilDPx5&limit=10")
else:
    msg
    print("searching")
    correct_search = search.replace(" ", "+")
    reponse = await session.get("http://api.giphy.com/v1/gifs/search?q=" + correct_search + "&api_key=Y4hnrG09EqYcNnv63Sj2gJvmy9ilDPx5&limit=10")
data = json.loads(await reponse.text())
await session.close()

embed = discord.Embed(
    description = '**showing result for ' + search + '**',
    colour = discord.Colour.blue()
)

gif_choice = random.randint(0,9)
embed.set_image(url=data["data"][gif_choice]["images"]["original"]["url"])
if randomImage:
    await bot.delete_message(randomMessage)
else:
    await bot.delete_message(msg)

await bot.send_message(channel, embed=embed)

Thank you


Solution

  • The response that the API gives is formatted as json. You need to parse through it to find the url you wish to embed. After it has loaded, it will be a dictionary in python.

    The below code is an example of how to do this. It will make a call to the giphy API and return the first 10 results and will randomly select a result as a message.

    Note that aiohttp is used as it is asynchronous, meaning it will not block your code. I have also modified the command so that you can search for anything. To match your previous request url, you can use !giphy ryan gosling. If the user does not specify a value for search, then the giphy random endpoint will be used instead.

    from discord.ext import commands
    import discord
    import json
    import aiohttp
    import random
    
    client = commands.Bot(command_prefix='!')
    
    
    @client.command(pass_context=True)
    async def giphy(ctx, *, search):
        embed = discord.Embed(colour=discord.Colour.blue())
        session = aiohttp.ClientSession()
    
        if search == '':
            response = await session.get('https://api.giphy.com/v1/gifs/random?api_key=API_KEY_GOES_HERE')
            data = json.loads(await response.text())
            embed.set_image(url=data['data']['images']['original']['url'])
        else:
            search.replace(' ', '+')
            response = await session.get('http://api.giphy.com/v1/gifs/search?q=' + search + '&api_key=API_KEY_GOES_HERE&limit=10')
            data = json.loads(await response.text())
            gif_choice = random.randint(0, 9)
            embed.set_image(url=data['data'][gif_choice]['images']['original']['url'])
    
        await session.close()
    
        await client.send_message(embed=embed)
    
    client.run('token')
    

    Also, it seems that discord natively supports giphy. While I was testing, it already made it's own giphy calls. I've tested this using some different characters (!, ~, ') and space and it seems to always work. See below examples.

    native giphy discord example: using bot prefix !

    native giphy discord example: using ~

    native giphy discord example using space