Skip to content

Commit

Permalink
fix: fix bugs, related to translations
Browse files Browse the repository at this point in the history
  • Loading branch information
ZolotarevAlexandr committed Oct 28, 2024
1 parent d2a9beb commit f5eb770
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 24 deletions.
16 changes: 6 additions & 10 deletions src/bot/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,6 @@
logger.info("Using Memory storage")

dp = CustomDispatcher(storage=storage)
i18n = I18n(path="locales", default_locale="en", domain="messages")
dialog_i18n_middleware = make_i18n_middleware()
i18n_middleware = SimpleI18nMiddleware(i18n)

dp.message.outer_middleware(i18n_middleware)
dp.callback_query.outer_middleware(i18n_middleware)

dp.message.middleware(dialog_i18n_middleware)
dp.callback_query.middleware(dialog_i18n_middleware)

log_all_events_middleware = LogAllEventsMiddleware()
dp.message.middleware(log_all_events_middleware)
dp.callback_query.middleware(log_all_events_middleware)
Expand All @@ -66,6 +56,12 @@ async def unknown_intent_handler(event: ErrorEvent, callback_query: types.Callba

setup_dialogs(dp)

i18n = I18n(path="locales", default_locale="en", domain="messages")
dialog_i18n_middleware = make_i18n_middleware(locales=["ru", "en"], default_locale="en")
i18n_middleware = SimpleI18nMiddleware(i18n)
i18n_middleware.setup(dp)
dialog_i18n_middleware.setup(dp)


async def receptionist_notifications_loop():
if not settings.bot_settings.users or not settings.bot_settings.notification_time:
Expand Down
3 changes: 1 addition & 2 deletions src/bot/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from aiogram import Bot, Dispatcher
from aiogram.dispatcher.event.bases import UNHANDLED
from aiogram.types import CallbackQuery, Message, Update, User
from aiogram.utils.i18n import gettext as _

from src.bot.logging_ import logger

Expand All @@ -13,7 +12,7 @@ class CustomDispatcher(Dispatcher):
async def _send_dunno_message(self, bot: Bot, chat_id: int):
await bot.send_message(
chat_id,
_("⚡️ I don't understand you. Please, use /start command."),
"⚡️ I don't understand you. Please, use /start command.",
)

async def _listen_update(self, update: Update, **kwargs) -> Any:
Expand Down
13 changes: 5 additions & 8 deletions src/bot/i18n.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, Protocol
from typing import Any, Dict, List, Protocol

from aiogram_dialog.api.protocols import DialogManager
from aiogram_dialog.widgets.common import WhenCondition
Expand All @@ -9,9 +9,6 @@
from src.bot.constants import DIALOG_I18N_FORMAT_KEY
from src.bot.middlewares import DialogI18nMiddleware

DEFAULT_LOCALE = "en"
LOCALES = ["en", "ru"]


class Values(Protocol):
def __getitem__(self, item: Any) -> Any:
Expand All @@ -35,7 +32,7 @@ def default_format_text(text: str, data: Values) -> str:
return text.format_map(data)


def make_i18n_middleware():
def make_i18n_middleware(locales: List[str], default_locale: str = "en"):
loader = FluentResourceLoader(
os.path.join(
os.getcwd(),
Expand All @@ -46,10 +43,10 @@ def make_i18n_middleware():
)
l10ns = {
locale: FluentLocalization(
[locale, DEFAULT_LOCALE],
[locale, default_locale],
["dialog.ftl"],
loader,
)
for locale in LOCALES
for locale in locales
}
return DialogI18nMiddleware(l10ns, DEFAULT_LOCALE)
return DialogI18nMiddleware(l10ns, default_locale)
23 changes: 20 additions & 3 deletions src/bot/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import inspect
import logging
import os
from collections.abc import Awaitable, Callable
from typing import Any, Dict, Union
from collections.abc import Awaitable, Callable, Set
from typing import Any, Dict, Optional, Union

from aiogram import BaseMiddleware
from aiogram import BaseMiddleware, Router
from aiogram.dispatcher.event.handler import HandlerObject
from aiogram.types import CallbackQuery, Message, TelegramObject
from fluent.runtime import FluentLocalization
Expand Down Expand Up @@ -111,3 +111,20 @@ async def __call__(
data[DIALOG_I18N_FORMAT_KEY] = l10n.format_value

return await handler(event, data)

def setup(
self: BaseMiddleware,
router: Router,
exclude: Optional[Set[str]] = None,
) -> BaseMiddleware:
"""
Register middleware for all events in the Router
"""
if exclude is None:
exclude = set()
exclude_events = {"update", *exclude}
for event_name, observer in router.observers.items():
if event_name in exclude_events:
continue
observer.outer_middleware(self)
return self
2 changes: 1 addition & 1 deletion src/bot/routers/booking/create_booking_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
async def start_booking(_message: Message, dialog_manager: DialogManager):
await dialog_manager.start(
CreateBookingStates.choose_date,
mode=StartMode.RESET_STACK,
mode=StartMode.NEW_STACK,
)


Expand Down

0 comments on commit f5eb770

Please sign in to comment.