Problem: My Telegram Bot exception stacktraces are displayed like a log, but seems not to be raised or maybe catched somewhere internally, so I cannot try-catch
them myself to get the idea why they happen and learn how to avoid that.
Goal of the question: Learn a proper way to capture Telegram bot connection related errors and prevent bot from dying becuase of them.
I am a beginner in writing Telegram bots and started learning from this official echo bot example.
The code in this question is based on the file in the link.
When bot gets exceptions, it either does not die, but log exception OR it does terminate, but does not execute my exception handling in Main()
(refer to its definition).
Neigther is helpful.
My problem is when running the bot locally, I get tons of exception logs — things like:
... loooong stack trace ...
File "C:UsersandruAppDataLocalProgramsPythonPython312Libsite-packageshttpx_transportsdefault.py", line 86, in map_httpcore_exceptions
raise mapped_exc(message) from exc
httpx.ConnectError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
... and so on...
Some times stack trace are almost duplicated.
Most common errors are httpx.ConnectError
and httpx.NetworkError
that I tried to catch like this:
def Main(): # This is supposed to capture error and print it with extra highlights
try:
main()
except (httpx.ConnectError, httpx.NetworkError) as err:
#
# Does not actuallty beeing called
#
print("nnn$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$nn")
print(err)
print("nnn$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$nn")
if __name__ == "__main__":
Main()
Main()
with a capital M is a wrapper around the actual main()
to capture when the bot dies.
But I never saw any dollar signs in my output. Even with the aid of ctrl+F
search in terminal.
Unfortunately, there are many lines in my code.
I tried to eliminate irrelevant for the sake of the example, but if the stripped version is not helpful, I may add it later in an edit.
This is the part that goes before Main()
import logging
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
ContextTypes,
filters
)
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("You joined my amazing bot")
def main():
# Some code was ommited as irrelevant to minimal description
application = Application.builder().token(TELEGRAM_TOKEN).build()
application.add_handler(CommandHandler("start", start_command))
application.run_polling()
Is there a better way to handle errors? Thank you very much!