AIOGRAM 3:如何在断网后恢复机器人

问题描述 投票:0回答:1

我的 Aiogram3 机器人出现问题。互联网消失后,我的机器人停止工作。通常,当互联网出现时,机器人就无法工作。我编写了一个脚本来确保机器人启动。

def check_process(process_name):
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == process_name:
            return True
    return False

def main():
    process_name = "MarriageGames.exe"
    while True:
        try:
            if check_process(process_name):
                print(f"The process {process_name} is running.")
            else:
                print(f"The process {process_name} is not running.")
                subprocess.Popen([process_name])
            time.sleep(5)
        except:
            pass

if __name__ == "__main__":
    main()

有运行机器人的脚本:

if __name__ == '__main__':
    while True:
        try:
            from handlers import *
            logging.basicConfig(level=logging.INFO, stream=sys.stdout)
            asyncio.run(main())
        except:
            time.sleep(5)

我有一个假设,如果我将机器人启动设置为“While True”,那么即使互联网不稳定,机器人也能正常工作。

请告诉我您是否知道如何确保机器人能够在网络不稳定的情况下恢复工作?是否可以通过管理员的聊天 ID 向管理员发送“机器人再次运行”消息?

python telegram telegram-bot python-telegram-bot aiogram
1个回答
0
投票

您可以像这样使用

request

import requests
import time

def check_network():
    try:
        requests.get('https://www.google.com', timeout=5)  # Try to connect to Google
        return True  # If successful, return True
    except requests.ConnectionError:
        return False  # If connection error occurs, return False

def network_connection():
    network_status = check_network()  # Initial network status
    while True:
        time.sleep(5)  # Check every 5 seconds
        new_network_status = check_network() # Check network status again
        if new_network_status != network_status:  # If there's a change in status
            if new_network_status:
                #code for the bot is up again

            network_status = new_network_status  # Update network status

if __name__ == "__main__":
    network_connection()

我希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.