首页 > 解决方案 > Cat Facts API discord.py

问题描述

我正在尝试找出如何使用 API 生成猫事实。到目前为止,我有这个代码:

    @commands.command()
    async def catfact(self, ctx):
      async with aiohttp.ClientSession().get("https://catfact.ninja/fact") as response:
          fact = (await response.json())["fact"]
          length = (await response.json())["length"]
          embed = discord.Embed(title=f'Random Cat Fact Number: **{length}**', description=f'Cat Fact: {fact}', colour=0x400080)
          embed.set_footer(text="")
          await ctx.send(embed=embed)

它应该在嵌入中发送猫事实。到目前为止,它有效,但我仍然收到一个错误:

Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f6338088d60>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f6338bcb640>, 76247.003680814)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f6338088d00>

这个错误是什么意思,我该如何解决?

标签: pythondiscorddiscord.pydiscord.py-rewrite

解决方案


您遇到的这个错误似乎是由于您在打开会话后没有关闭会话造成的,正如这个aiohttp GitHub 问题所引用的那样。

最快的解决方法可能是在将 cat 事实发送给用户后简单地关闭会话。但是你的with声明并没有返回一个可以使用的会话,它只是给出了一个响应。因此,您可以将其拆分为两个with语句,如下所示:

前:

async with aiohttp.ClientSession().get("https://catfact.ninja/fact") as response:
    ...

后:

async with aiohttp.ClientSession() as session:
    async with session.get("https://catfact.ninja/fact") as response:
        ...

但是,既然这些with语句被拆分,会话在其with语句中的代码完成后会自动关闭;之前,它没有关闭,因为您的with声明没有公开会话本身,只是响应。通过在语句中公开会话本身(在这些更改之前,您没有这样做)with,Python 将在完成运行其中的代码后自动关闭它。

完整代码:

@commands.command()
async def catfact(self, ctx):
  async with aiohttp.ClientSession() as session:
    async with session.get("https://catfact.ninja/fact") as response:
      fact = (await response.json())["fact"]
      length = (await response.json())["length"]
      embed = discord.Embed(title=f'Random Cat Fact Number: **{length}**', description=f'Cat Fact: {fact}', colour=0x400080)
      embed.set_footer(text="")
      await ctx.send(embed=embed)
      # await session.close() # <--- here, but is not necessary

如果您仍然在其他地方遇到错误,您可以添加 await session.close() (上面代码中的最后一行)以手动关闭会话,但这不是必需的。


推荐阅读