我如何将 GIPHY Python API 与我的 discord 机器人一起使用?

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

根据我的理解,我可以使用 GIPHY 文档 (https://gyazo.com/1b6c0094162a54fe49029f665badf8df) 中的这个示例来打开一个 url,但我不太了解它。除此之外,当我 运行 这段代码时,我得到错误:

discord.ext.commands.errors.CommandInvokeError:命令引发异常: AttributeError:模块 'urllib' 没有属性 'urlopen'

我的问题是,一旦用户在文本频道中键入#giphy,我如何从某些标签中随机导入 GIF

这是我当前的代码:(代码已更新)

@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)

谢谢

API 给出的响应格式为 json。您需要对其进行解析以找到您希望嵌入的 url。加载后,它将成为 python.

中的字典

下面的代码是如何执行此操作的示例。它将调用 giphy API 和 return 前 10 个结果,并将随机 select 一个结果作为消息。

请注意,使用 aiohttp 是因为它是异步的,这意味着它不会阻塞您的代码。我还修改了命令,以便您可以搜索任何内容。要匹配您之前的请求 url,您可以使用 !giphy ryan gosling。如果用户未指定搜索值,则将使用 giphy 随机端点。

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')

此外,discord 似乎原生支持 giphy。在我进行测试时,它已经进行了自己的 giphy 调用。我已经使用一些不同的字符 (!, ~, ') 和 space 对此进行了测试,它似乎总是有效。请参阅以下示例。