【问题标题】:Giphy API not responding in discord.pyGiphy API 在 discord.py 中没有响应
【发布时间】:2021-10-24 21:23:20
【问题描述】:

我制作了一个不和谐的机器人,当你输入某个命令时它会显示 gif,但问题是它在前半部分运行良好,但在不使用时需要很长时间才能显示 gif。 基本上它在不使用时不会立即显示 gif。 这是我写的代码:

@client.command()

async def gif(ctx, *, q = 'dance'):

api_key = 'Some Key here'
api_instanc = giphy_client.DefaultApi()

try:
    api_responce = api_instanc.gifs_search_get(api_key, q, limit = 7,rating = 'r')
    lst = list(api_responce.data)
    giff = random.choice(lst)
    emb = discord.Embed(title = f"Requested by {ctx.author} " + q )
    emb.set_image(url= f'https://media.giphy.com/media/{giff.id}/giphy.gif')

    await ctx.channel.send(embed = emb)
except ApiException as e:
    await ctx.channel.send("API EXCEPTION")

它没有显示任何错误,但长时间后不起作用。 任何用 aiohttp 重写的代码都将不胜感激,因为我正在学习这一点。

【问题讨论】:

标签: discord.py


【解决方案1】:

我认为您使用的模块不是异步的,这会导致阻塞read more

命令中的默认值为search = None,您可以将其与 if 语句一起使用来检查。

之后就是请求api获取图片了。

这里是使用aiohttp编辑的代码

# import aiohttp
# import random

@bot.command()
async def giphy(ctx, search: str = None):
    api_key = ""
    embed = discord.Embed(title=f"Requested by {ctx.author}")
    async with aiohttp.ClientSession() as session:
        # search
        if search:
            embed.description = search
            async with session.get(f'http://api.giphy.com/v1/gifs/search?q={search}&api_key={api_key}&limit=10') as response:
                data = await response.json()
                gif_choice = random.randint(0, 9)
                embed.set_image(url=data['data'][gif_choice]['images']['original']['url'])
        # radnom
        else:
            async with session.get(f'http://api.giphy.com/v1/gifs/random?api_key={api_key}&limit=10') as response:
                data = await response.json()
                embed.set_image(url=data['data']['images']['original']['url'])

    await ctx.send(embed=embed)

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2021-08-18
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2013-09-09
    相关资源
    最近更新 更多