python - 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>
这个错误是什么意思,我该如何解决?
解决方案
您遇到的这个错误似乎是由于您在打开会话后没有关闭会话造成的,正如这个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()
(上面代码中的最后一行)以手动关闭会话,但这不是必需的。
推荐阅读
- rvest - Rvest 返回零列表
- c# - 为什么可以将地址添加到 MailMessage.To 使用对象初始化?
- static-analysis - 单个文件上的 Spotbugs?
- swift - 调用localizedNetworkReachabilityStatusString 后的未知状态
- c - 如何将字符串和变量连接到C中的字符串
- java - Java - 在二维字符数组中搜索单词?
- javascript - 如何找到与提供的 slug 匹配的某个对象的索引
- android - 使用 cordova-plugin-firebase-messaging 显示来自 Ionic 的通知
- r - 使用 %in% 进行字符串搜索(包含特殊字符)在 str_detect 工作时不起作用
- vba - VBA:设置工作簿,并激活工作簿错误