我正在使用 Discord.py 库来制作一个 python Discord 机器人,在关闭时或当它收到 SIGINIT 时,我希望它运行一个关闭处理程序(更新数据库、关闭数据库连接等)我有主要的 python脚本以及我想彻底关闭的不和谐齿轮。一个简单的谷歌只是说使用 Try/Finally,并且只是让它运行 client.close()
但需要等待。所以它看起来像这样:
try:
bot.run(config["token"])
finally:
shutdownHandeler()
bot.close()
但它希望我等待
bot.close 协程,除非它不在异步函数内,否则我无法这样做。我对 asyncio 和 discord py 还很陌生,所以如果有人能指出我正确的方向,那就太棒了!预先感谢您的帮助。
最佳答案
run()
的问题是你不能只使用 try
- finally
来实现清理,因为在处理run()
,discord.py 已经关闭了事件循环以及机器人本身。但是,在 run()
清理的第一阶段,会调用 bot.close()
方法。因此最好在该 close 方法中运行清理操作:
from discord.ext import commands
class Bot(commands.Bot):
async def async_cleanup(self): # example cleanup function
print("Cleaning up!")
async def close(self):
# do your cleanup here
await self.async_cleanup()
await super().close() # don't forget this!
bot = Bot(None)
bot.run(TOKEN)
关于python - 如何优雅地处理 Ctrl + C 并关闭 Discord Py 机器人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69682471/