I’ve got a Telegram bot running on AWS EC2 using pyrogram. It keeps crashing after a while and I sometimes stop the instance to save money. I tried setting up cron jobs in /etc/crontab to handle reboots and crashes, but they don’t seem to work right. Here’s what I did:
- A job to start the bot after EC2 reboots
- Another job to check and restart the bot every 2 minutes if it crashed
My crontab looks like this:
@reboot sudo pgrep -f bot.py || sudo nohup /usr/bin/python3 /home/ubuntu/bot.py & > /home/ubuntu/reboot_log.txt
*/2 * * * * sudo pgrep -f bot.py || sudo nohup /usr/bin/python3 /home/ubuntu/bot.py & > /home/ubuntu/crash_log.txt
Are these cron jobs set up correctly? Is there a better way to keep my bot running? Any help would be great!
Your cron jobs are close, but they could be improved. I’d suggest using systemd instead for better process management. It’s built into most modern Linux distributions and offers more robust handling of service restarts and logging.
Here’s how you can set it up:
- Create a service file in /etc/systemd/system/telegrambot.service
- Define your bot as a service with restart options
- Enable and start the service
Your service file might look like:
[Unit]
Description=Telegram Bot Service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /home/ubuntu/bot.py
WorkingDirectory=/home/ubuntu
User=ubuntu
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Then enable with ‘sudo systemctl enable telegrambot’ and start with ‘sudo systemctl start telegrambot’. This should keep your bot running across reboots and crashes more reliably than cron jobs.
I’ve dealt with similar issues running bots on EC2. Your approach is on the right track, but there are a few tweaks that could make it more robust.
Instead of relying solely on cron jobs, I’d recommend using a process manager like Supervisor. It’s designed specifically for keeping processes running and restarting them if they crash. Here’s how I set it up:
- Install Supervisor:
sudo apt-get install supervisor
- Create a config file for your bot in
/etc/supervisor/conf.d/telegram_bot.conf
- Configure it to start on boot and auto-restart
The config might look something like:
[program:telegram_bot]
command=/usr/bin/python3 /home/ubuntu/bot.py
directory=/home/ubuntu
user=ubuntu
autostart=true
autorestart=true
stderr_logfile=/var/log/telegram_bot.err.log
stdout_logfile=/var/log/telegram_bot.out.log
This setup has been much more reliable for me than cron jobs. It handles crashes and reboots seamlessly, and you can easily check the status or logs if needed.
hey there, have u tried using Docker? it’s pretty neat for keeping stuff running. just make a Dockerfile for ur bot, then use docker-compose to set it up with restart: always. that way it’ll keep going after reboots and crashes. plus, u can easily move it between ec2 instances if needed. might be worth a shot!