python - 如何优雅地处理 Ctrl + C 并关闭 Discord Py 机器人?

标签 python discord.py python-asyncio

我正在使用 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/

相关文章:

python - 在 Python3 Pandas 中读取/导入 CSV 文件时出现编码问题

python - ProgrammingError : (psycopg2. errors.UndefinedColumn),同时使用 sqlalchemy

Python aiohttp + 异步 : How to execute code after loop. run_forever()

python - python asyncio call_soon_threadsafe 真的是线程安全的吗?

python - Python中如何快速得到线性规划的可行解?

python - discord.py bot 找到要删除的 channel 消息,但显示其客户端 ID 与我的相同

python - Discord.py 每个用户的冷却时间不同

discord.py - discord python : guild. 成员只返回机器人但没有成员

python-3.x - 在python中使用aiohttp获取多个URL

python - 为什么对数字调用 float() 比在 Python 中添加 0.0 慢?