M
M
mddoffguy2022-01-05 22:14:06
Python
mddoffguy, 2022-01-05 22:14:06

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

1 answer(s)
V
Vindicar, 2022-01-06
@mddoffguy

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.

This will help here's why:

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.

Allotment is mine.
Well, if you have non-demonic flows that are not controlled by you, then you will have to wrap the main bot in a try catch. And yes, the fact that "the bot is divided into files with classes and methods" changes absolutely nothing. If the bot is synchronous, it has an entry point where you start its work, and any uncaught exception in that thread will only be raised there. If the bot is asynchronous, then you need to respond to uncaught exceptions in coroutines - read the asyncio docs on how to do this.
Well, the optimal solution is to figure out where the exception pops up, understand its cause, and fix it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question