From 80f73e2077845832a94bdba7951088ce10acfd7d Mon Sep 17 00:00:00 2001 From: bral <54455457+bralbral@users.noreply.github.com> Date: Mon, 29 Apr 2024 12:13:31 +0300 Subject: [PATCH] Simple error handler (#42) Simple error handler (#42) --- deploy/example.config.yaml | 1 + src/bot/handlers/__init__.py | 2 ++ src/bot/handlers/admins/router.py | 11 +++++++-- src/bot/handlers/errors.py | 40 +++++++++++++++++++++++++++++++ src/bot/handlers/misc.py | 2 -- src/bot/handlers/users.py | 7 +----- src/bot/utils/setup_bot.py | 2 ++ src/config/models.py | 3 +++ src/constants.py | 2 +- 9 files changed, 59 insertions(+), 11 deletions(-) create mode 100644 src/bot/handlers/errors.py diff --git a/deploy/example.config.yaml b/deploy/example.config.yaml index 20cedec..57e18a7 100644 --- a/deploy/example.config.yaml +++ b/deploy/example.config.yaml @@ -30,3 +30,4 @@ chat_id: -100XXXXXXXXXXXXX # too_long_message_caption: ❌ Too long message caption. # copy_message: ❌ Error during copying # extract_user_id: ❌ Error during extract_id +# chat_not_found: ❌ Chat not found. Make sure you have added the bot to the admin group diff --git a/src/bot/handlers/__init__.py b/src/bot/handlers/__init__.py index 53edb55..d103c77 100644 --- a/src/bot/handlers/__init__.py +++ b/src/bot/handlers/__init__.py @@ -1,6 +1,7 @@ from aiogram import Dispatcher from .admins import router as admin_router +from .errors import errors_router from .misc import router as misc_router from .users import router as users_router @@ -9,6 +10,7 @@ def register_handlers(dp: Dispatcher) -> None: dp.include_router(misc_router) dp.include_router(users_router) dp.include_router(admin_router) + dp.include_router(errors_router) __all__ = ["register_handlers"] diff --git a/src/bot/handlers/admins/router.py b/src/bot/handlers/admins/router.py index f3a04be..1a27bf5 100644 --- a/src/bot/handlers/admins/router.py +++ b/src/bot/handlers/admins/router.py @@ -5,6 +5,7 @@ from aiogram import Router from aiogram.exceptions import TelegramAPIError from aiogram.types import Message +from aiogram.types import MessageId from .utils import extract_id from src.bot.filters import FilterByChatID @@ -41,9 +42,12 @@ async def reply_to_user( except ValueError: pass + # check result of deliver + successful_deliver: Optional[MessageId] = None + try: try: - await bot.copy_message( + successful_deliver = await bot.copy_message( from_chat_id=message.chat.id, chat_id=user_id, message_id=message.message_id, @@ -56,7 +60,7 @@ async def reply_to_user( raise inner_ex # try to resend message - await bot.copy_message( + successful_deliver = await bot.copy_message( from_chat_id=message.chat.id, chat_id=user_id, message_id=message.message_id, @@ -64,6 +68,9 @@ async def reply_to_user( except TelegramAPIError as ex: await message.reply(text=f"{errors.copy_message} {str(ex)}") + finally: + if successful_deliver: + await message.reply(text=messages.notify_admin_about_success_answer) __all__ = ["router"] diff --git a/src/bot/handlers/errors.py b/src/bot/handlers/errors.py new file mode 100644 index 0000000..1960ed6 --- /dev/null +++ b/src/bot/handlers/errors.py @@ -0,0 +1,40 @@ +from typing import Optional + +import aiogram.exceptions +from aiogram import Bot +from aiogram import Router +from aiogram.types import User +from aiogram.types.error_event import ErrorEvent + +from src.config import Errors + +errors_router = Router(name="errors") + + +@errors_router.errors() # type: ignore +async def error_handler(exception: ErrorEvent, **kwargs) -> None: + + bot: Bot = kwargs["bot"] + from_user: Optional[User] = kwargs.get("event_from_user", None) + errors_messages: Errors = kwargs["errors"] + + if ( + isinstance(exception.exception, aiogram.exceptions.TelegramBadRequest) + and from_user + ): + if exception.exception.message.find("Bad Request: message is too long") > -1: + await bot.send_message( + chat_id=from_user.id, + text=errors_messages.too_long_message_text, + ) + + elif exception.exception.message.find("Bad Request: chat not found") > -1: + await bot.send_message( + chat_id=from_user.id, + text=errors_messages.chat_not_found, + ) + + return + + +__all__ = ["errors_router"] diff --git a/src/bot/handlers/misc.py b/src/bot/handlers/misc.py index bc36b41..79bd673 100644 --- a/src/bot/handlers/misc.py +++ b/src/bot/handlers/misc.py @@ -2,7 +2,6 @@ from aiogram import Router from aiogram.filters import Command from aiogram.types import Message -from sulguk import SULGUK_PARSE_MODE from src.config import Messages @@ -24,7 +23,6 @@ async def start_help_handler(message: Message, messages: Messages, **kwargs) -> await message.answer( messages.help_message, disable_web_page_preview=True, - parse_mode=SULGUK_PARSE_MODE, ) diff --git a/src/bot/handlers/users.py b/src/bot/handlers/users.py index 212baa6..3c642cc 100644 --- a/src/bot/handlers/users.py +++ b/src/bot/handlers/users.py @@ -3,7 +3,6 @@ from aiogram import Router from aiogram.enums import ContentType from aiogram.types import Message -from sulguk import SULGUK_PARSE_MODE from .utils import extract_userinfo_from_message from src.config import Errors @@ -41,7 +40,6 @@ async def handle_user_message( ): await message.reply( text=errors.unsupported_type, - parse_mode=SULGUK_PARSE_MODE, ) return @@ -56,9 +54,7 @@ async def handle_user_message( message_text = extract_userinfo_from_message(message) + message.html_text - await bot.send_message( - chat_id=chat_id, text=message_text, parse_mode=SULGUK_PARSE_MODE - ) + await bot.send_message(chat_id=chat_id, text=message_text) else: if message.caption and len(message.caption) > 1000: @@ -73,7 +69,6 @@ async def handle_user_message( from_chat_id=from_chat_id, message_id=message_id, caption=caption, - parse_mode=SULGUK_PARSE_MODE, ) await message.reply(text=messages.notify_user_about_success_deliver) diff --git a/src/bot/utils/setup_bot.py b/src/bot/utils/setup_bot.py index 402205f..9efc2fa 100644 --- a/src/bot/utils/setup_bot.py +++ b/src/bot/utils/setup_bot.py @@ -2,6 +2,7 @@ from aiogram.types import BotCommand from aiogram.types import BotCommandScopeDefault from sulguk import AiogramSulgukMiddleware +from sulguk import SULGUK_PARSE_MODE from src.config import BotConfig @@ -13,6 +14,7 @@ async def setup_bot(config: BotConfig) -> Bot: """ bot: Bot = Bot( token=config.token.get_secret_value(), + parse_mode=SULGUK_PARSE_MODE, ) # https://github.com/Tishka17/sulguk#example-for-aiogram-users diff --git a/src/config/models.py b/src/config/models.py index b8ca2a7..e99e11a 100644 --- a/src/config/models.py +++ b/src/config/models.py @@ -40,6 +40,9 @@ class Errors(BaseSettings): too_long_message_caption: str = Field(default="❌ Too long message caption.") copy_message: str = Field(default="❌ Error during copying") extract_user_id: str = Field(default="❌ Error during extract_id") + chat_not_found: str = Field( + default="❌ Chat not found. Make sure you have added the bot to the admin group" + ) class Config(BaseSettings): diff --git a/src/constants.py b/src/constants.py index a973a51..7463c3d 100644 --- a/src/constants.py +++ b/src/constants.py @@ -1,6 +1,6 @@ import os -VERSION: str = "2024-04-25.22" +VERSION: str = "2024-04-29.12" ROOT_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CONFIG_FILE_PATH: str = os.path.join(ROOT_DIR, "config.yaml")