Answer the question
In order to leave comments, you need to log in
Python Telegram bot: How to kill thread on any exception in main body?
Let's say I have a telegram bot on Telebot, which spins endlessly on a server with pm2 (auto-restart on exception).
I have a message thread (threading library) that sends messages to all users every day for example.
But there is such a situation that I get an exception in another part of the bot (outside the thread). How can I kill the thread with any exception and auto restart the bot through pm2? Wrapping everything in try is obviously not an option, and I don’t know where the exception will occur.
UPD: I can’t wrap the start of the bot in try, because the bot is divided into files with classes and methods that are called from hooks
Answer the question
In order to leave comments, you need to log in
Just make the thread a daemon via the parameter in threading.Thread.
If not None, daemon parameter explicitly sets whether the thread is daemonic. If None (the default), the daemonic property is inherited from the current thread.
daemon
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called , otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
The entire Python program exits when no alive non-daemon threads are left.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question