【问题标题】:How would I use the GIPHY Python API with my discord bot?我如何将 GIPHY Python API 与我的 discord 机器人一起使用?
【发布时间】:2019-04-12 13:39:06
【问题描述】:

据我了解,我可以使用 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)

谢谢

【问题讨论】:

  • 您可以尝试以问题的形式表达您的问题吗?
  • 哎呀我完全忘记问这个问题了哈哈
  • 您的导入是什么样的?您可能正在寻找urllib.request.urlopen
  • 我已经更新了我的代码并修复了我的导入,但我似乎仍然无法让它工作。它输出:(文件路径)第 96 行,在 giphy await bot.send_message(channel, embed=embed) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\discord\ client.py”,第 1152 行,在 send_message 中数据 = 来自 self.http.send_message(channel_id,内容,guild_id=guild_id,tts=tts,embed=embed

标签: python bots discord discord.py giphy


【解决方案1】:

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

以下代码是如何执行此操作的示例。它将调用 giphy API 并返回前 10 个结果,并随机选择一个结果作为消息。

请注意,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 调用。我已经使用一些不同的字符(!,〜,')和空格对此进行了测试,它似乎总是有效。请参阅以下示例。

【讨论】:

  • 非常感谢!我不知道 discord 支持这样的 giphy,老实说它很酷。由于我找不到任何绕过不和谐的方法,每当您在句子开头键入 giphy 时自动尝试将您的文本更改为 giphy url,所以我决定将命令更改为 #gif,现在它可以正常工作了!还有一件事要问,如果用户没有输入任何要搜索的内容,我如何随机搜索 gif?
  • 抱歉问了很多问题,我还在学习 python,这对我帮助很大,但是我测试命令越多,我注意到显示的 gif 总是相同的 gif .前任。如果我搜索“特里”,无论我搜索多少次特里,弹出的唯一 GIF 是他在喊“我的丙烯酸树脂!”。我注意到的另一件事是我无法在搜索中添加空格。前任。搜索 Terry Crews 时出现错误,如何将空格替换为 _?
  • 我已经编辑了我的答案以包括你的两个场景。如果未指定搜索,则使用随机端点。如果指定,则返回 10 个结果并随机选择一个。上面的命令已经满足了空间的需求。这是通过 async def giphy(ctx, *, search): 中包含的 * 字符完成的。没有它,您将无法使用空格,或者您必须将参数括在引号中,例如!giphy "Terry Crews"。此处的文档:discordpy.readthedocs.io/en/latest/…
  • 感谢不同的结果工作,只有一件事,我仍然无法搜索毛圈组。我已经更新了我的原始帖子以显示我目前拥有的内容。出现以下错误: raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raise an exception: KeyError: 'data'
  • @ceiltechbladhm 不错。我上次的编辑没有正确处理data,它需要在response 之后,所以它必须在这两种情况下。另外请记住,这是针对旧版本的discord.py,新版本不使用client.send_message
猜你喜欢
  • 2021-02-24
  • 2019-08-10
  • 2021-04-14
  • 2021-06-06
  • 2021-11-30
  • 2022-11-15
  • 2020-08-16
  • 2021-08-13
  • 2017-12-05
相关资源
最近更新 更多