All checks were successful
CI / lint-and-test (push) Successful in 14s
- Introduced a new i18n module for managing translations and language normalization, supporting both Russian and English. - Updated various handlers and services to utilize the new translation functions for user-facing messages, improving user experience based on language preferences. - Enhanced error handling and response messages to be language-aware, ensuring appropriate feedback is provided to users in their preferred language. - Added tests for the i18n module to validate language detection and translation functionality. - Updated the example environment file to include a default language configuration.
38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
"""get_lang and t(): language from Telegram user, translate by key with fallback to en."""
|
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
import duty_teller.config as config
|
|
from duty_teller.i18n.messages import MESSAGES
|
|
|
|
if TYPE_CHECKING:
|
|
from telegram import User
|
|
|
|
|
|
def get_lang(user: "User | None") -> str:
|
|
"""
|
|
Normalize Telegram user language to 'ru' or 'en'.
|
|
If user has language_code starting with 'ru' (e.g. ru, ru-RU) return 'ru', else 'en'.
|
|
When user is None or has no language_code, return config.DEFAULT_LANGUAGE.
|
|
"""
|
|
if user is None or not getattr(user, "language_code", None):
|
|
return config.DEFAULT_LANGUAGE
|
|
code = (user.language_code or "").strip().lower()
|
|
return "ru" if code.startswith("ru") else "en"
|
|
|
|
|
|
def t(lang: str, key: str, **kwargs: str) -> str:
|
|
"""
|
|
Return translated string for lang and key; substitute kwargs into placeholders like {phone}.
|
|
Fallback to 'en' if key missing for lang.
|
|
"""
|
|
lang = "ru" if lang == "ru" else "en"
|
|
messages = MESSAGES.get(lang) or MESSAGES["en"]
|
|
template = messages.get(key)
|
|
if template is None:
|
|
template = MESSAGES["en"].get(key, key)
|
|
try:
|
|
return template.format(**kwargs)
|
|
except KeyError:
|
|
return template
|