Add internationalization support and enhance language handling
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.
This commit is contained in:
2026-02-18 13:56:49 +03:00
parent be57555d4f
commit 263c2fefbd
21 changed files with 594 additions and 92 deletions

View File

@@ -8,6 +8,7 @@ from telegram.ext import CommandHandler, ContextTypes
from duty_teller.db.session import session_scope
from duty_teller.db.repository import get_or_create_user, set_user_phone
from duty_teller.i18n import get_lang, t
from duty_teller.utils.user import build_full_name
@@ -36,21 +37,23 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await asyncio.get_running_loop().run_in_executor(None, do_get_or_create)
text = "Привет! Я бот календаря дежурств. Используй /help для списка команд."
lang = get_lang(user)
text = t(lang, "start.greeting")
await update.message.reply_text(text)
async def set_phone(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if not update.message or not update.effective_user:
return
lang = get_lang(update.effective_user)
if update.effective_chat and update.effective_chat.type != "private":
await update.message.reply_text("Команда /set_phone доступна только в личке.")
await update.message.reply_text(t(lang, "set_phone.private_only"))
return
args = context.args or []
phone = " ".join(args).strip() if args else None
telegram_user_id = update.effective_user.id
def do_set_phone() -> str:
def do_set_phone() -> str | None:
with session_scope(config.DATABASE_URL) as session:
full_name = build_full_name(
update.effective_user.first_name, update.effective_user.last_name
@@ -65,27 +68,33 @@ async def set_phone(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
)
user = set_user_phone(session, telegram_user_id, phone or None)
if user is None:
return "Ошибка сохранения."
return "error"
if phone:
return f"Телефон сохранён: {phone}"
return "Телефон очищен."
return "saved"
return "cleared"
result = await asyncio.get_running_loop().run_in_executor(None, do_set_phone)
await update.message.reply_text(result)
if result == "error":
await update.message.reply_text(t(lang, "set_phone.error"))
elif result == "saved":
await update.message.reply_text(t(lang, "set_phone.saved", phone=phone or ""))
else:
await update.message.reply_text(t(lang, "set_phone.cleared"))
async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if not update.message or not update.effective_user:
return
lang = get_lang(update.effective_user)
lines = [
"Доступные команды:",
"/start — Начать",
"/help — Показать эту справку",
"/set_phone — Указать или очистить телефон для отображения в дежурстве",
"/pin_dutyВ группе: закрепить сообщение о дежурстве (нужны права админа у бота)",
t(lang, "help.title"),
t(lang, "help.start"),
t(lang, "help.help"),
t(lang, "help.set_phone"),
t(lang, "help.pin_duty"),
]
if config.is_admin(update.effective_user.username or ""):
lines.append("/import_duty_schedule — Импорт расписания дежурств (JSON)")
lines.append(t(lang, "help.import_schedule"))
await update.message.reply_text("\n".join(lines))

View File

@@ -5,6 +5,9 @@ import logging
from telegram import Update
from telegram.ext import ContextTypes
import duty_teller.config as config
from duty_teller.i18n import get_lang, t
logger = logging.getLogger(__name__)
@@ -13,4 +16,6 @@ async def error_handler(
) -> None:
logger.exception("Exception while handling an update")
if isinstance(update, Update) and update.effective_message:
await update.effective_message.reply_text("Произошла ошибка. Попробуйте позже.")
user = getattr(update, "effective_user", None)
lang = get_lang(user) if user else config.DEFAULT_LANGUAGE
await update.effective_message.reply_text(t(lang, "errors.generic"))

View File

@@ -11,6 +11,7 @@ from telegram.error import BadRequest, Forbidden
from telegram.ext import ChatMemberHandler, CommandHandler, ContextTypes
from duty_teller.db.session import session_scope
from duty_teller.i18n import get_lang, t
from duty_teller.services.group_duty_pin_service import (
get_duty_message_text,
get_next_shift_end_utc,
@@ -26,9 +27,9 @@ JOB_NAME_PREFIX = "duty_pin_"
RETRY_WHEN_NO_DUTY_MINUTES = 15
def _get_duty_message_text_sync() -> str:
def _get_duty_message_text_sync(lang: str = "en") -> str:
with session_scope(config.DATABASE_URL) as session:
return get_duty_message_text(session, config.DUTY_DISPLAY_TZ)
return get_duty_message_text(session, config.DUTY_DISPLAY_TZ, lang)
def _get_next_shift_end_sync():
@@ -98,7 +99,9 @@ async def update_group_pin(context: ContextTypes.DEFAULT_TYPE) -> None:
if message_id is None:
logger.info("No pin record for chat_id=%s, skipping update", chat_id)
return
text = await loop.run_in_executor(None, _get_duty_message_text_sync)
text = await loop.run_in_executor(
None, lambda: _get_duty_message_text_sync(config.DEFAULT_LANGUAGE)
)
try:
await context.bot.edit_message_text(
chat_id=chat_id,
@@ -133,7 +136,10 @@ async def my_chat_member_handler(
ChatMemberStatus.BANNED,
):
loop = asyncio.get_running_loop()
text = await loop.run_in_executor(None, _get_duty_message_text_sync)
lang = get_lang(update.effective_user)
text = await loop.run_in_executor(
None, lambda: _get_duty_message_text_sync(lang)
)
try:
msg = await context.bot.send_message(chat_id=chat_id, text=text)
except (BadRequest, Forbidden) as e:
@@ -154,9 +160,7 @@ async def my_chat_member_handler(
try:
await context.bot.send_message(
chat_id=chat_id,
text="Сообщение о дежурстве отправлено, но закрепить его не удалось. "
"Сделайте бота администратором с правом «Закреплять сообщения» (Pin messages), "
"затем отправьте в чат команду /pin_duty — текущее сообщение будет закреплено.",
text=t(lang, "pin_duty.could_not_pin_make_admin"),
)
except (BadRequest, Forbidden):
pass
@@ -190,19 +194,18 @@ async def restore_group_pin_jobs(application) -> None:
async def pin_duty_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if not update.message or not update.effective_chat:
if not update.message or not update.effective_chat or not update.effective_user:
return
chat = update.effective_chat
lang = get_lang(update.effective_user)
if chat.type not in ("group", "supergroup"):
await update.message.reply_text("Команда /pin_duty работает только в группах.")
await update.message.reply_text(t(lang, "pin_duty.group_only"))
return
chat_id = chat.id
loop = asyncio.get_running_loop()
message_id = await loop.run_in_executor(None, _sync_get_message_id, chat_id)
if message_id is None:
await update.message.reply_text(
"В этом чате ещё нет сообщения о дежурстве. Добавьте бота в группу — оно создастся автоматически."
)
await update.message.reply_text(t(lang, "pin_duty.no_message"))
return
try:
await context.bot.pin_chat_message(
@@ -210,12 +213,10 @@ async def pin_duty_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
message_id=message_id,
disable_notification=True,
)
await update.message.reply_text("Сообщение о дежурстве закреплено.")
await update.message.reply_text(t(lang, "pin_duty.pinned"))
except (BadRequest, Forbidden) as e:
logger.warning("pin_duty failed chat_id=%s: %s", chat_id, e)
await update.message.reply_text(
"Не удалось закрепить. Убедитесь, что бот — администратор с правом «Закреплять сообщения»."
)
await update.message.reply_text(t(lang, "pin_duty.failed"))
group_duty_pin_handler = ChatMemberHandler(

View File

@@ -7,6 +7,7 @@ from telegram import Update
from telegram.ext import CommandHandler, ContextTypes, MessageHandler, filters
from duty_teller.db.session import session_scope
from duty_teller.i18n import get_lang, t
from duty_teller.importers.duty_schedule import (
DutyScheduleParseError,
parse_duty_schedule,
@@ -20,14 +21,12 @@ async def import_duty_schedule_cmd(
) -> None:
if not update.message or not update.effective_user:
return
lang = get_lang(update.effective_user)
if not config.is_admin(update.effective_user.username or ""):
await update.message.reply_text("Доступ только для администраторов.")
await update.message.reply_text(t(lang, "import.admin_only"))
return
context.user_data["awaiting_handover_time"] = True
await update.message.reply_text(
"Укажите время пересменки в формате ЧЧ:ММ и часовой пояс, "
"например 09:00 Europe/Moscow или 06:00 UTC."
)
await update.message.reply_text(t(lang, "import.handover_format"))
async def handle_handover_time_text(
@@ -39,18 +38,17 @@ async def handle_handover_time_text(
return
if not config.is_admin(update.effective_user.username or ""):
return
lang = get_lang(update.effective_user)
text = update.message.text.strip()
parsed = parse_handover_time(text)
if parsed is None:
await update.message.reply_text(
"Не удалось разобрать время. Укажите, например: 09:00 Europe/Moscow"
)
await update.message.reply_text(t(lang, "import.parse_time_error"))
return
hour_utc, minute_utc = parsed
context.user_data["handover_utc_time"] = (hour_utc, minute_utc)
context.user_data["awaiting_handover_time"] = False
context.user_data["awaiting_duty_schedule_file"] = True
await update.message.reply_text("Отправьте файл в формате duty-schedule (JSON).")
await update.message.reply_text(t(lang, "import.send_json"))
async def handle_duty_schedule_document(
@@ -60,11 +58,12 @@ async def handle_duty_schedule_document(
return
if not context.user_data.get("awaiting_duty_schedule_file"):
return
lang = get_lang(update.effective_user)
handover = context.user_data.get("handover_utc_time")
if not handover or not config.is_admin(update.effective_user.username or ""):
return
if not (update.message.document.file_name or "").lower().endswith(".json"):
await update.message.reply_text("Нужен файл с расширением .json")
await update.message.reply_text(t(lang, "import.need_json"))
return
hour_utc, minute_utc = handover
@@ -77,7 +76,7 @@ async def handle_duty_schedule_document(
except DutyScheduleParseError as e:
context.user_data.pop("awaiting_duty_schedule_file", None)
context.user_data.pop("handover_utc_time", None)
await update.message.reply_text(f"Ошибка разбора файла: {e}")
await update.message.reply_text(t(lang, "import.parse_error", error=str(e)))
return
def run_import_with_scope():
@@ -90,16 +89,29 @@ async def handle_duty_schedule_document(
None, run_import_with_scope
)
except Exception as e:
await update.message.reply_text(f"Ошибка импорта: {e}")
await update.message.reply_text(t(lang, "import.import_error", error=str(e)))
else:
total = num_duty + num_unavailable + num_vacation
parts = [f"{num_users} пользователей", f"{num_duty} дежурств"]
if num_unavailable:
parts.append(f"{num_unavailable} недоступностей")
if num_vacation:
parts.append(f"{num_vacation} отпусков")
unavailable_suffix = (
t(lang, "import.done_unavailable", count=str(num_unavailable))
if num_unavailable
else ""
)
vacation_suffix = (
t(lang, "import.done_vacation", count=str(num_vacation))
if num_vacation
else ""
)
await update.message.reply_text(
"Импорт выполнен: " + ", ".join(parts) + f" (всего {total} событий)."
t(
lang,
"import.done",
users=str(num_users),
duties=str(num_duty),
unavailable=unavailable_suffix,
vacation=vacation_suffix,
total=str(total),
)
)
finally:
context.user_data.pop("awaiting_duty_schedule_file", None)