如何让Python开发的Telegram Bot在崩溃或服务器重启后自动启动?
解决Telegram Bot开机自启与崩溃自动重启问题
一、实现服务器重启后自动启动Bot
用Linux系统自带的systemd配置服务是最稳定的方案:
创建systemd服务文件
打开终端执行命令:sudo nano /etc/systemd/system/telegram-bot.service写入服务配置内容
根据实际路径修改后粘贴到文件中:[Unit] Description=Telegram Bot Service After=network.target [Service] User=你的系统用户名 WorkingDirectory=/path/to/your/bot/folder ExecStart=/usr/bin/python3 /path/to/your/bot/main.py Restart=always RestartSec=5 [Install] WantedBy=multi-user.target几个关键参数说明:
User:替换为运行Bot的系统用户名WorkingDirectory:Bot脚本所在的文件夹完整路径ExecStart:Python解释器路径(可通过which python3查看)+ Bot主脚本的完整路径
启用并启动服务
执行以下命令使配置生效:sudo systemctl daemon-reload sudo systemctl enable telegram-bot.service sudo systemctl start telegram-bot.service可通过
systemctl status telegram-bot.service查看服务当前运行状态。
二、Bot崩溃时自动重启
方法一:依赖systemd自带机制
上面的systemd配置已经包含崩溃重启逻辑,核心是Restart参数:
Restart=always:无论Bot正常退出还是崩溃,都会自动重启Restart=on-failure:仅当Bot因错误(退出码非0)崩溃时才重启RestartSec=5:崩溃后等待5秒再重启,避免短时间内频繁重启
修改配置后,执行sudo systemctl daemon-reload && sudo systemctl restart telegram-bot.service即可生效。
方法二:用Shell脚本实现
如果不想依赖systemd,可写一个循环脚本:
- 创建
bot-restart.sh脚本:#!/bin/bash while true; do python3 /path/to/your/bot/main.py echo "Bot crashed at $(date), restarting in 5 seconds..." sleep 5 done - 给脚本添加执行权限:
chmod +x bot-restart.sh - 后台运行脚本:
nohup ./bot-restart.sh &
注意:这种方式无法实现开机自启,需额外配置。
内容的提问来源于stack exchange,提问作者user17982950
相关产品推荐
相关产品推荐

