Answer the question
In order to leave comments, you need to log in
How to make the telegram bot automatically restart after giving an error?
Greetings, I have a telegram bot in python, it is rooted on a Linux server, but there is such a problem that sometimes the bot crashes and I just physically cannot restart it all the time. I have a written script, but I took it from one person, he wrote that this script will restart the bot after restarting the telegram servers. Is it even possible to write a script that will check every 2 seconds whether the bot is working, and if not, restart it. Below I will attach the script code that I have now. I will be grateful for help.
[Unit]
Description=Telegram bot 'Airdrop'
After=syslog.target
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/usr/local/bin/bot
ExecStart=/usr/bin/python3 /usr/local/bin/bot/airdrop.py
RestartSec=10
Restart=always
[Install]
WantedBy=multi-user.target
Answer the question
In order to leave comments, you need to log in
Why check the functionality of the script every 2 seconds, and if it crashes, restart it? I haven't seen such vomit in a long time. Immediately it is necessary to make the exception (error) handler standard.
In Python, try-except is responsible for this. You add an infinite loop, and in case of not true (breakdown), it will return to the actions that will have to be executed if true.
while True:
try:
bot.polling()
except:
continue
bot.polling()
, you need to add any other method that launches long polling, if the script uses an alternative library to PyTelegramBotAPI
If a Linux machine:
I recently installed the supervisor package with the supervisord daemon for this purpose on the Raspberry Pi
. It allows you to automatically run the necessary scripts at system startup, restart them when it crashes (you can specify the number of restarts after which restarts will be stopped (for hopeless scripts)), log output to stdout.
But you will need to read a little about how to use this tool.
https://supervisord.readthedocs.io/en/latest/insta...
It's not a script, it's a unit file for systemd. It will restart and it will follow itself.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question