user3896248
user3896248

Reputation: 669

Discord.py: Restarting a bot after the event loop closes

I have a discord.py bot that I'm currently hosting locally while it matures. I'd like to make it resilient against momentary blips in my internet connection, but I'm having a hard time. When the connection fails, the blocking Client.run() that represents the normal bot operation finishes and closes the event loop. I can't just re-call Client.run() a few minutes later, because The Event Loop is Closed.

I've tried re-declaring the Client object, but this doesn't seem to use a new event loop. I'm going through the discord.py and python event loop documentation, but can't figure out how to get a new event loop and use that instead.

I've tried things along the lines of asyncio.set_event_loop(asyncio.new_event_loop()) but it doesn't seem to make any difference - I still can't re-call Client.run() because the event loop is closed.

Upvotes: 3

Views: 4782

Answers (1)

user4815162342
user4815162342

Reputation: 155545

There is nothing wrong with the existing event loop in case of an internet connection blip. Simply don't call Client.run which closes the event loop. Since Client.run is anyway a simple wrapper around run_until_complete that closes the event loop, you can write your own that doesn't do so. For example:

def run_client(client, *args, **kwargs):
    loop = asyncio.get_event_loop()
    while True:
        try:
            loop.run_until_complete(client.start(*args, **kwargs))
        except Exception as e:
            print("Error", e)  # or use proper logging
        print("Waiting until restart")
        time.sleep(600)

Upvotes: 4

Related Questions