Jeremy Hsieh
Jeremy Hsieh

Reputation: 71

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.

Upvotes: 3

Views: 2408

Answers (2)

Taku
Taku

Reputation: 33734

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)

Upvotes: 3

Stephen Milic
Stephen Milic

Reputation: 81

Why not declare bot.close() and shutdownHandeler() in an async function then call it when it's necessary, in your finaly or in a stop command or anything else you would think of ?

Upvotes: 0

Related Questions