我的discord.py僵尸程序失去互联网后无法重新连接到Discord

时间:2020-08-27 05:19:14

标签: python discord discord.py

我构建了一个discord.py机器人。我希望该机器人在连接之前先等待互联网。另外,当它失去互联网时,我希望它等待互联网并重新连接。这是我当前的相关代码:

import asyncio
import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

async def task():
    await client.wait_until_ready()
    while True:
        await asyncio.sleep(5)
        print('Running')

def handle_exit():
    print("Handling")
    try:
        client.loop.run_until_complete(client.logout())
    except:
        pass
    for t in asyncio.Task.all_tasks(loop=client.loop):
        if t.done():
            try:
                t.exception()
                continue
            except:
                continue
        t.cancel()
        try:
            client.loop.run_until_complete(asyncio.wait_for(t, 5, loop=client.loop))
            t.exception()
        except:
            pass

def wait_for_internet_connection():
    while True:
        try:
            response = urlopen("http://www.google.com/",timeout=1)
            return
        except:
            pass

#MAIN CODE
wait_for_internet_connection()
while True:
    client.loop.create_task(task())
    try:
        client.loop.run_until_complete(client.start(TOKEN))
    except:
        print("Lost Internet")
        handle_exit()
    print("Waiting for Internet")
    wait_for_internet_connection()
    print("Reconnected")
    time.sleep(3)
    client = discord.Client()

当我执行此代码时,它以响应消息的方式成功连接到Discord。当我关闭互联网时,它将断开连接并等待互联网(其他线程上没有错误消息)。当我重新打开互联网时,任务功能开始输出“正在运行”,并且我的主机卡在“ client.loop.run_until_complete(client.start(TOKEN))”中而没有中断,但无法从和谐状态访问。为什么?有没有一种方法可以从头开始重新启动bot?

此处输出:

[BOT NAME] has connected to Discord!
Running
Running
Running
Lost Internet
Handling
Waiting for Internet
Reconnected
Running
Running
(Running continues forever, never 'connects to discord' though)

0 个答案:

没有答案