如何让Python应用出错时自动重启?PythonAnywhere Telegram Bot保活方法
解决PythonAnywhere免费服务器上Telegram Bot自动停止与重启问题
一、实现程序出错自动重启
1. 异常捕获+循环重启
把Bot核心逻辑包裹在无限循环中,捕获所有未预期异常,出错后延迟重启,同时可记录错误日志方便排查:
import time from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text('Hello!') def main(): while True: try: app = ApplicationBuilder().token("你的Bot令牌").build() app.add_handler(CommandHandler("start", start)) app.run_polling() except Exception as e: # 写入错误日志 with open("bot_crash_logs.txt", "a") as log_file: log_file.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - 错误信息: {str(e)}\n") print(f"Bot崩溃,错误: {e},5秒后重启...") time.sleep(5) if __name__ == "__main__": main()
这种方式能处理大多数运行时异常,确保Bot崩溃后自动恢复。
2. 定时任务监控重启
利用PythonAnywhere免费版的定时任务功能,编写检查脚本监控Bot进程,停止时自动拉起:
- 编写
check_bot_status.py:
import subprocess def bot_is_running(): # 检查进程中是否存在你的Bot脚本 process_output = subprocess.run(["ps", "-ef"], capture_output=True, text=True).stdout return "你的Bot脚本文件名.py" in process_output if not bot_is_running(): # 启动Bot脚本(替换为你的脚本路径) subprocess.Popen(["python3", "/home/你的用户名/你的Bot脚本文件名.py"])
在PythonAnywhere的「Tasks」页面添加定时任务,设置每小时执行一次该脚本,作为兜底的重启方案。
二、保持Bot长期活跃(避免免费资源回收)
免费版PythonAnywhere会终止长期无输出或空闲的进程,可通过以下方式规避:
1. 定期输出存活日志
在Bot中添加定时任务,每隔几分钟打印存活日志,维持进程活跃状态:
import time from telegram.ext import JobQueue async def log_alive_status(context: ContextTypes.DEFAULT_TYPE): print(f"Bot运行正常,当前时间: {time.strftime('%Y-%m-%d %H:%M:%S')}") # 在main函数的app初始化后添加 app.job_queue.run_repeating(log_alive_status, interval=300) # 每5分钟输出一次
2. 替换为Webhook模式(更稳定)
Polling模式长期轮询容易被判定为空闲进程,改用Webhook模式更适配PythonAnywhere的Web环境:
- 调整Bot脚本为Webhook模式:
from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text('Hello!') def main(): app = ApplicationBuilder().token("你的Bot令牌").build() app.add_handler(CommandHandler("start", start)) # 配置Webhook app.run_webhook( listen="0.0.0.0", port=8000, url_path="你的Bot令牌" ) app.bot.set_webhook(url="https://你的用户名.pythonanywhere.com/你的Bot令牌") if __name__ == "__main__": main()
然后在PythonAnywhere的「Web」页面创建手动配置的Web应用,设置对应Python版本,修改WSGI文件指向你的Bot脚本(需调整为WSGI兼容格式)。Webhook仅在有Telegram请求时触发进程,资源利用率更高且不易被终止。
3. 避免阻塞操作
确保所有消息/命令处理函数无长时间阻塞,耗时操作(如网络请求)需添加超时或改用异步处理,防止进程卡住被服务器终止。
内容的提问来源于stack exchange,提问作者Kuki
相关产品推荐
相关产品推荐

