You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python Telegram Bot断网恢复后自动重启(需手动启动控制程序)

解决Telegram Bot网络中断后自动重启的问题

问题背景

我开发的Telegram Bot在终端运行正常,但网络中断时会触发以下ReadTimeout错误并停止运行:

raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=25)

需要实现:

  • 网络恢复后Bot自动重启
  • 仅手动启动控制程序A后,才由A负责运行Bot并在异常时重启;Bot不会随系统开机自动启动

解决方案

1. 控制程序A(bot_controller.py)

这个程序负责启动Bot进程、监控运行状态,一旦Bot退出就自动重启,同时加入重试间隔避免频繁尝试:

import subprocess
import time

def run_bot():
    while True:
        print("启动Telegram Bot...")
        # 启动Bot进程,假设Bot代码文件名为telegram_bot.py
        proc = subprocess.Popen(["python", "telegram_bot.py"])
        # 等待进程结束
        proc.wait()
        print("Bot已退出,10秒后尝试重启...")
        time.sleep(10)

if __name__ == "__main__":
    run_bot()

2. 修改后的Bot代码(telegram_bot.py)

调整原Bot代码,将轮询逻辑放入异常捕获块,遇到网络相关错误时主动退出进程,交给控制程序重启:

import telebot
import time
from requests.exceptions import ReadTimeout, ConnectionError

bot = telebot.TeleBot('*************')

@bot.message_handler(content_types=['text'])
def get_text_messages(my_mes):
    try:
        if my_mes.text == "/help":
            bot.send_message(my_mes.from_user.id, "hi")
        elif 0 < int(my_mes.text) < 5:
            num = int(my_mes.text) + 1
            bot.send_message(my_mes.from_user.id, str(num))
    except Exception as e:
        bot.send_message(my_mes.from_user.id, "write /help.")

def start_polling():
    while True:
        try:
            # 可根据需求调整超时时间
            bot.polling(none_stop=True, interval=0, timeout=30)
        except (ReadTimeout, ConnectionError):
            print("网络连接异常,Bot将退出等待重启...")
            break
        except Exception as e:
            print(f"未知错误: {e}")
            time.sleep(5)

if __name__ == "__main__":
    start_polling()

说明

  • 控制程序A通过subprocess.Popen启动Bot进程,用proc.wait()监控状态,Bot退出后等待10秒再重启
  • Bot代码专门捕获ReadTimeout、ConnectionError这类网络异常,触发后主动退出,让控制程序接手重启逻辑
  • 使用时只需手动运行python bot_controller.py,Bot就会启动;网络恢复后会自动重启,关闭控制程序则Bot同步停止

内容的提问来源于stack exchange,提问作者Xazratxon Sultonxonov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:31:39