S
S
Solak12021-12-22 14:08:26
Python
Solak1, 2021-12-22 14:08:26

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

4 answer(s)
I
InternetMaster, 2021-12-22
@InternetMaster

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

Instead bot.polling(), you need to add any other method that launches long polling, if the script uses an alternative library to PyTelegramBotAPI

L
Leonid, 2021-12-22
@bravebug

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...

P
paran0id, 2021-12-22
@paran0id

It's not a script, it's a unit file for systemd. It will restart and it will follow itself.

J
Jan, 2022-01-10
@Buchachalo

Judging by the answers above the author, everything works conditionally. The bot does not crash and responds to /start. The problem is in the logic inside the bot.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question