Auto-restart Telegram bot on AWS EC2 after crash or system restart

I built a Telegram bot with python-telegram-bot library and deployed it on my AWS EC2 instance. The bot keeps stopping unexpectedly every few hours and I also manually stop my EC2 instance sometimes to save money.

I’m trying to set up automatic restart using cron jobs in /etc/crontab but they don’t seem to work properly. Here’s what I want to achieve:

  1. Start the bot automatically when EC2 boots up
  2. Monitor and restart the bot if it stops working

Here’s my current crontab setup:

@reboot sudo pgrep -f telegram_bot.py || sudo nohup /usr/bin/python3 /home/ubuntu/telegram_bot.py & > /home/ubuntu/boot_log.txt

*/3 * * * * sudo pgrep -f telegram_bot.py || sudo nohup /usr/bin/python3 /home/ubuntu/telegram_bot.py & > /home/ubuntu/restart_log.txt

Is there something wrong with my cron configuration? Or should I use a different approach like systemd services instead?

Skip cron completely - use supervisor instead. I’ve run telegram bots on EC2 for 2+ years and supervisor nails both auto-restart and boot startup. Install with sudo apt install supervisor, then drop a config file in /etc/supervisor/conf.d/telegram-bot.conf. Set your python path, working directory, and user. Supervisor watches your process constantly and restarts it in seconds when it crashes. You get clean logging without messy output redirection, plus it handles all the daemon stuff. Just run sudo supervisorctl reread and sudo supervisorctl update after config changes. Way more reliable than cron for this.

Just wrap your bot in a bash script with a while loop and run it as a service. Something like while true; do python3 telegram_bot.py; sleep 5; done - crude but works great. Saves you from dealing with systemd or supervisor if you don’t want that complexity.

Had the same cron issues with my bots and switched to systemd - way better. Your cron setup has problems, especially the output redirection. Use >> /path/to/log 2>&1 to catch both stdout and stderr. Running sudo inside cron creates permission headaches too. Create a systemd service file at /etc/systemd/system/telegram-bot.service instead. Set the user permissions and working directory properly. Then run systemctl enable telegram-bot.service so it starts on reboot. Systemd’s built for this stuff - better process management and you get logging through journalctl.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.