Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I gracefully handle Ctrl + C and shutdown Discord Py bot?

I'm using the Discord.py library to make a python discord bot, and on shutdown or when it gets SIGINIT I want it to run a shutdown handler (update database, close database connections, etc) I have the main python script and also discord cogs that I want to cleanly shutdown. A simple google just says to use a Try/Finally, and just to have it run client.close() but it needs to be awaited. So it looks something like this:

try:
    bot.run(config["token"])
finally:
    shutdownHandeler()
    bot.close() 

but it wants me to await the bot.close coroutine except I cant do that if its not inside an async function. I'm pretty new to asyncio and discord py so if anyone could point me in the right direction that would be awesome! Thanks in advance for any help.

like image 875
Jeremy Hsieh Avatar asked Nov 14 '25 11:11

Jeremy Hsieh


1 Answers

The issue with run() is that you can't just use try - finally to implement cleanup, because during the handling for run(), discord.py already closed the event loop along with the bot itself. However, during the first phase of run()'s cleanup, the bot.close() method gets called. So it would be best to run your cleanup operations in that close method:

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)
like image 131
Taku Avatar answered Nov 17 '25 08:11

Taku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!