简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM