Skip to content

Commit

Permalink
Simple error handler (#42)
Browse files Browse the repository at this point in the history
Simple error handler (#42)
  • Loading branch information
bralbral committed Apr 29, 2024
1 parent ae23d1c commit 80f73e2
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 11 deletions.
1 change: 1 addition & 0 deletions deploy/example.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions src/bot/handlers/__init__.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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"]
11 changes: 9 additions & 2 deletions src/bot/handlers/admins/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -56,14 +60,17 @@ 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,
)

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"]
40 changes: 40 additions & 0 deletions src/bot/handlers/errors.py
Original file line number Diff line number Diff line change
@@ -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"]
2 changes: 0 additions & 2 deletions src/bot/handlers/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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,
)


Expand Down
7 changes: 1 addition & 6 deletions src/bot/handlers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -41,7 +40,6 @@ async def handle_user_message(
):
await message.reply(
text=errors.unsupported_type,
parse_mode=SULGUK_PARSE_MODE,
)

return
Expand All @@ -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:
Expand All @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions src/bot/utils/setup_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/config/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion src/constants.py
Original file line number Diff line number Diff line change
@@ -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")

Expand Down

0 comments on commit 80f73e2

Please sign in to comment.