From d4a45495179bd103fb983565e404e151c4fa555b Mon Sep 17 00:00:00 2001 From: Arseniy Obolenskiy Date: Sat, 13 Apr 2024 20:36:15 +0800 Subject: [PATCH] Suppress traceback on network disruption in Telegram app object Log error if network has disrupted, but do not print traceback --- src/backend/telegram/instance.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/backend/telegram/instance.py b/src/backend/telegram/instance.py index 1b7cd413..12726878 100644 --- a/src/backend/telegram/instance.py +++ b/src/backend/telegram/instance.py @@ -3,6 +3,7 @@ from telegram import Update, constants from telegram.ext import Application, CallbackContext, MessageHandler, filters +from telegram.error import NetworkError from src import const from src.api.bot_instance import BotInstance @@ -51,6 +52,15 @@ async def _handle_mentions(self, update: Update, context: CallbackContext) -> No await bc.executor.commands[cmd_line[0]].run(cmd_line, TelegramExecutionContext(update, context)) await bc.plugin_manager.broadcast_command("on_message", TelegramExecutionContext(update, context)) + @staticmethod + async def _error_handler(update: Update, context: CallbackContext) -> None: + # You can also log the error or do other error handling here + error = context.error + if isinstance(error, NetworkError): + log.error(f"Network error occurred: {error}") + return + raise error + @Mail.send_exception_info_to_admin_emails def _run(self, args) -> None: log.info("Starting Telegram instance...") @@ -75,6 +85,7 @@ def _run(self, args) -> None: bc.be.set_running(const.BotBackend.TELEGRAM, True, f"{bc.telegram.bot_username} ({self.__class__.__name__})") bc.executor.binders[const.BotBackend.TELEGRAM] = TelegramCommandBinding(app) bc.telegram.app = app + app.add_error_handler(self._error_handler) app.run_polling(timeout=600, stop_signals=()) counter = 0 reminder_proc = ReminderProcessing()