Analysis: docs/analysis/onboarding_funnel.md (56% of users never add a player; drop happens on the first screen; non-ru/en users convert at 25%). Design: docs/design/onboarding.md. - /start: one message. New user: promise + "send a Lichess username, e.g. DrNykterstein" with [❓ Где взять имя] / [🇬🇧 English] (language switch edits the message in place). Returning user: their players + /today /addgamer /help. - /addgamer asks for the name directly (the two-button menu from 2025-12-03 is gone). - Any non-command text in a private chat is a player-name attempt: no awaiting flag, PicklePersistence removed. onboarding.normalise_username accepts lichess.org URLs, @name, quotes, "add Name"; chess.com and non-name text get their own hints; nothing is sent to Lichess for them. - Every reply ends with the next step (success: hourly report is on, /today, send another name). One no_players empty state for /today, /week, /getgamers, /delgamer, /setperiod, /profile, /year. - /help: 18 lines in three groups; /year and /lang aliases; command menu set from code for en (default) and ru at startup (set_my_commands). - /addtoken trap: non-lip_ text gets a hint instead of "invalid token"; any other command inside the conversation ends it and runs; /cancel outside a conversation answers "nothing to cancel". - All echoed input html-escaped. Terminology unified: игрок / имя на Lichess / отчёт (player / Lichess username / report). - events: user_start screen=, addgamer_input kind= normalised=, addgamer_result format|chesscom, lang_set via=, addtoken_result not_a_token; text in_flow= gone. - i18n: 18 dead keys removed, 21 added; docs (README, USER_GUIDE, about, CURRENT_STATE, CHANGELOG Unreleased) updated; 107 bot tests (was 61). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
510 lines
26 KiB
Python
510 lines
26 KiB
Python
"""
|
||
Internationalization module for the Lichess Telegram Bot
|
||
Supports English and Russian languages.
|
||
|
||
Onboarding texts (start_*, add_prompt, player_*, *_hint, no_players,
|
||
help_message, lang_prompt) follow docs/design/onboarding.md: every logical
|
||
line <= 34 characters (an emoji counts as 2), one emoji at the start of the
|
||
first line, names in <code>, HTML parse mode. tests/bot/test_onboarding.py
|
||
checks the line lengths.
|
||
"""
|
||
|
||
from typing import Optional
|
||
|
||
# Translation dictionary (English and Russian)
|
||
TRANSLATIONS = {
|
||
'en': {
|
||
# Onboarding (docs/design/onboarding.md): every line <= 34 chars, one
|
||
# emoji at the start of the first line, HTML (<code> for names).
|
||
# /start for a user without players; the example is a real active account
|
||
'start_new': (
|
||
"♟️ Track Lichess players:\n"
|
||
"a report on their games every\n"
|
||
"hour, plus daily and weekly stats.\n\n"
|
||
"Send a Lichess username,\n"
|
||
"e.g. <code>DrNykterstein</code>\n"
|
||
"(the name from lichess.org/@/…)"
|
||
),
|
||
# /start for a user with players: {names} = first 3 in <code>, {more} = start_more or ''
|
||
'start_returning': (
|
||
"♟️ You follow: {names}{more}.\n\n"
|
||
"/today — today's games\n"
|
||
"/addgamer — add a player\n"
|
||
"/help — all commands"
|
||
),
|
||
'start_more': " and {n} more",
|
||
'btn_lang_ru': "🇷🇺 Русский",
|
||
'btn_lang_en': "🇬🇧 English",
|
||
'btn_where_name': "❓ Where is the username?",
|
||
'add_prompt': (
|
||
"Send a Lichess username,\n"
|
||
"e.g. <code>DrNykterstein</code>."
|
||
),
|
||
# caption of helpEN.jpeg
|
||
'where_name_caption': (
|
||
"The username is in the profile\n"
|
||
"URL: lichess.org/@/username\n"
|
||
"Send it here."
|
||
),
|
||
|
||
# Help command
|
||
'help_message': (
|
||
"♟️ Commands\n\n"
|
||
"<b>Players</b>\n"
|
||
"/addgamer — add a player\n"
|
||
"/getgamers — list and ratings\n"
|
||
"/delgamer — remove a player\n\n"
|
||
"<b>Stats</b>\n"
|
||
"/today — today\n"
|
||
"/yesterday — yesterday\n"
|
||
"/week — last 7 days\n"
|
||
"/year — last year (slow)\n\n"
|
||
"<b>Settings</b>\n"
|
||
"/setperiod — how often to report\n"
|
||
"/addtoken — puzzles via token\n"
|
||
"/lang — bot language\n"
|
||
"/support — contact the author"
|
||
),
|
||
|
||
# Add token
|
||
'addtoken_prompt': (
|
||
"🔑 Enter the Lichess API token to get puzzle data.\n"
|
||
"The token is created in profile settings — give it only puzzle:read permission.\n"
|
||
"After that, the player corresponding to this token will be added.\n\n"
|
||
"Changed your mind — /cancel. To just add a player you need no token: send the name."
|
||
),
|
||
# text in the /addtoken conversation that does not look like a token
|
||
'addtoken_not_token': (
|
||
"ℹ️ That does not look like a token\n"
|
||
"(Lichess tokens start with lip_).\n\n"
|
||
"/addtoken is only for puzzle stats\n"
|
||
"via your own token. To add a\n"
|
||
"player, press /cancel and send\n"
|
||
"the name."
|
||
),
|
||
'token_added': "✅ Token added for player {username}!",
|
||
'gamer_added_with_token': "✅ Player {username} added with token!",
|
||
# Replies to a name ({username} = HTML-escaped by the caller)
|
||
'player_added': (
|
||
"✅ Added <code>{username}</code>\n"
|
||
"<a href=\"https://lichess.org/@/{username}\">lichess.org/@/{username}</a>\n\n"
|
||
"🔔 Every hour you get a report\n"
|
||
"on their games (if they played).\n\n"
|
||
"/today — today's stats\n"
|
||
"Another player? Just send a name."
|
||
),
|
||
'invalid_token': "❌ Invalid token. Please try again.",
|
||
'token_username_error': "❌ Failed to get username from token. Please try again.",
|
||
'player_not_found': (
|
||
"❌ No player <code>{username}</code>\n"
|
||
"on Lichess.\n\n"
|
||
"Check the spelling and send the\n"
|
||
"name again. It is the name from\n"
|
||
"lichess.org/@/username"
|
||
),
|
||
'player_closed': (
|
||
"⛔ Account <code>{username}</code> is closed\n"
|
||
"on Lichess — no games to track.\n\n"
|
||
"Send another player's name."
|
||
),
|
||
'lichess_unavailable': (
|
||
"⚠️ Lichess is not responding.\n"
|
||
"Send the name again in a minute."
|
||
),
|
||
'player_already': (
|
||
"ℹ️ <code>{username}</code> is already\n"
|
||
"on your list.\n\n"
|
||
"/today — today's stats\n"
|
||
"Another player? Just send a name."
|
||
),
|
||
'name_format_hint': (
|
||
"ℹ️ A Lichess username is Latin\n"
|
||
"letters, digits, \"-\" and \"_\",\n"
|
||
"no spaces. E.g. <code>DrNykterstein</code>.\n\n"
|
||
"Send the name again."
|
||
),
|
||
'chesscom_hint': (
|
||
"ℹ️ That looks like Chess.com.\n"
|
||
"This bot works with Lichess only.\n\n"
|
||
"If the player is on Lichess too,\n"
|
||
"send their Lichess username."
|
||
),
|
||
'token_rejected_notice': "⚠️ Lichess rejected the saved token for {username} — puzzle stats have been turned off for this player, game tracking continues as normal. Use /addtoken to reconnect a fresh token if you want puzzle stats back.",
|
||
'gamer_account_closed': "⛔ Lichess account {username} is closed. Notifications for it are paused; if it is reopened, they will resume automatically.",
|
||
'gamer_account_not_found': "❌ Lichess account {username} no longer exists (deleted or renamed). Notifications for it are paused.",
|
||
'gamer_account_reopened': "✅ Lichess account {username} is active again, notifications resumed.",
|
||
|
||
# Empty state of /today, /getgamers, /delgamer, /setperiod, /profile, /year
|
||
'no_players': (
|
||
"📭 You are not following anyone\n"
|
||
"yet.\n\n"
|
||
"Send a Lichess username, e.g.\n"
|
||
"<code>DrNykterstein</code>, and I will start\n"
|
||
"sending reports."
|
||
),
|
||
|
||
# Get gamers
|
||
'loading_ratings': "🔄 Loading player ratings...",
|
||
'select_active_gamer': "👥 <b>Player statistics:</b>\n\n",
|
||
'gamers_closed_legend': "⛔ closed: {names}",
|
||
'gamers_not_found_legend': "❓ not found: {names}",
|
||
'active_gamer_set': "✅ Active player: {username}",
|
||
'gamer_not_found': "❌ Player not found",
|
||
|
||
# Delete gamer
|
||
'loading_gamers': "🔄 Loading player list...",
|
||
'select_gamer_to_delete': "🗑️ <b>Select player to delete:</b>\n\n",
|
||
'gamer_deleted': "✅ Player <b>{username}</b> removed from tracked list.",
|
||
'active_gamer_deleted': "✅ Player <b>{username}</b> removed from tracked list.\n\n⚠️ You deleted the active player. Use the /getgamers command to select a player for which the /today, /yesterday, /week commands will work.",
|
||
'last_gamer_deleted': "✅ Player <b>{username}</b> removed from tracked list.\n\n⚠️ You deleted the last player. Send a Lichess username to add a new one.",
|
||
'delete_failed': "❌ Failed to delete player",
|
||
|
||
# Stats commands
|
||
'unknown_period': "❌ Unknown period",
|
||
'no_data': "📭 No data",
|
||
'stats_title': "📊 Statistics {username} • {date_range}\n\n",
|
||
'puzzles_section': "🧩 Puzzles: {total} (✅ {solved} - ❌ {unsolved})\n\n",
|
||
'game_type_header': "{emoji} {game_type} — {games_count} games • {rating_change}\n",
|
||
'stat_label_rating': "⭐ Rating:",
|
||
'stat_label_wins': "✅ Wins:",
|
||
'stat_label_losses': "❌ Losses:",
|
||
'stat_label_draws': "🤝 Draws:",
|
||
'game_rows_heading': "{emoji} {game_type} games:\n",
|
||
|
||
# Set period
|
||
'select_period': "⏱️ Select period for player {username}:\n📱 Notifications will be sent to personal messages",
|
||
'notifications_disabled': "✅ Notifications disabled for {username}",
|
||
'period_set': "✅ Period {period} minutes set for {username}\n📱 Notifications will be sent to personal messages",
|
||
'disable_notifications': "❌ Disable notifications",
|
||
'period_minutes': "⏰ {period} minutes",
|
||
|
||
# Period notification
|
||
'period_1_minute': "for 1 minute",
|
||
'period_2_3_4_minutes': "for {period} minutes",
|
||
'period_minutes_text': "for {period} minutes",
|
||
'period_hours_text': "for {hours}h",
|
||
'period_days_text': "for {days}d",
|
||
'period_notification_title': "📊 Statistics {username} • {period_text}\n\n",
|
||
'period_puzzles_section': "🧩 Puzzles: {total} (✅ {solved} - ❌ {failed})\n\n",
|
||
'no_activity': "📭 No activity for this period",
|
||
|
||
# Last year or 1000 games
|
||
'last_year_1000_player_processing': "🔄 Requesting data for player <b>{username}</b>...",
|
||
|
||
# Stats commands (today/yesterday/week)
|
||
'stats_player_processing': "🔄 Requesting data for player <b>{username}</b>...",
|
||
|
||
# Support
|
||
'support_message': (
|
||
"💬 <b>Support & Feedback</b>\n\n"
|
||
"You can write to the service developer directly and report a problem, suggest new features, or ask a question.\n\n"
|
||
"I will be happy to review every message and respond to it.\n\n"
|
||
"The developer accepts messages in <b>English</b> and <b>Russian</b> languages.\n\n"
|
||
"📧 Contact: <a href=\"https://t.me/vrubelr\">@vrubelr</a>\n\n"
|
||
"📦 Bot version: <b>{version}</b>"
|
||
),
|
||
|
||
# Common
|
||
'period_minutes_suffix': "m",
|
||
'select_player_period': "⏱️ Select a player to set the notification period:",
|
||
'period_set_confirm': "✅ Period {period} set for {username}\n📱 Notifications will be sent to personal messages",
|
||
'period_label_minutes': "{n} minutes",
|
||
'period_label_hour': "1 hour",
|
||
'period_label_hours': "{n} hours",
|
||
'unknown_command': (
|
||
"ℹ️ No such command.\n"
|
||
"/help — list of commands."
|
||
),
|
||
'cancel_nothing': (
|
||
"ℹ️ Nothing to cancel.\n"
|
||
"/help — list of commands."
|
||
),
|
||
'non_text_hint': (
|
||
"ℹ️ I read text only.\n"
|
||
"Send the Lichess username as\n"
|
||
"text, e.g. <code>DrNykterstein</code>."
|
||
),
|
||
|
||
# Language selection
|
||
'lang_prompt': "🌐 Язык / Language",
|
||
'language_set_en': "✅ Language: English",
|
||
'language_set_ru': "✅ Язык: русский",
|
||
|
||
# Profile command
|
||
'select_player_profile': "👤 <b>Select player:</b>",
|
||
'profile_link_sent': "✅ Profile link sent",
|
||
},
|
||
'ru': {
|
||
# Onboarding (docs/design/onboarding.md): every line <= 34 chars, one
|
||
# emoji at the start of the first line, HTML (<code> for names).
|
||
'start_new': (
|
||
"♟️ Следите за игроками Lichess:\n"
|
||
"отчёт о партиях раз в час,\n"
|
||
"статистика за день и неделю.\n\n"
|
||
"Пришлите имя игрока на Lichess,\n"
|
||
"например <code>DrNykterstein</code>\n"
|
||
"(имя из адреса lichess.org/@/…)"
|
||
),
|
||
'start_returning': (
|
||
"♟️ Вы следите: {names}{more}.\n\n"
|
||
"/today — партии за сегодня\n"
|
||
"/addgamer — добавить игрока\n"
|
||
"/help — все команды"
|
||
),
|
||
'start_more': " и ещё {n}",
|
||
'btn_lang_ru': "🇷🇺 Русский",
|
||
'btn_lang_en': "🇬🇧 English",
|
||
'btn_where_name': "❓ Где взять имя",
|
||
'add_prompt': (
|
||
"Пришлите имя игрока на Lichess,\n"
|
||
"например <code>DrNykterstein</code>."
|
||
),
|
||
# подпись к helpRU.jpeg
|
||
'where_name_caption': (
|
||
"Имя игрока — в адресе его\n"
|
||
"профиля: lichess.org/@/имя\n"
|
||
"Пришлите его сюда."
|
||
),
|
||
|
||
# Help command
|
||
'help_message': (
|
||
"♟️ Команды\n\n"
|
||
"<b>Игроки</b>\n"
|
||
"/addgamer — добавить игрока\n"
|
||
"/getgamers — список и рейтинги\n"
|
||
"/delgamer — удалить игрока\n\n"
|
||
"<b>Статистика</b>\n"
|
||
"/today — за сегодня\n"
|
||
"/yesterday — за вчера\n"
|
||
"/week — за неделю\n"
|
||
"/year — за год (медленно)\n\n"
|
||
"<b>Настройки</b>\n"
|
||
"/setperiod — как часто отчёты\n"
|
||
"/addtoken — пазлы по токену\n"
|
||
"/lang — язык бота\n"
|
||
"/support — написать автору"
|
||
),
|
||
|
||
# Add token
|
||
'addtoken_prompt': (
|
||
"🔑 Введите токен API Lichess для получения данных по пазлам.\n"
|
||
"Токен создается в настройках профиля — дайте ему только разрешение puzzle:read.\n"
|
||
"После этого будет добавлен игрок, соответствующий этому токену.\n\n"
|
||
"Передумали — /cancel. Чтобы просто добавить игрока, токен не нужен: пришлите его имя."
|
||
),
|
||
'addtoken_not_token': (
|
||
"ℹ️ Это не похоже на токен\n"
|
||
"(токен Lichess начинается с lip_).\n\n"
|
||
"/addtoken нужен только для\n"
|
||
"статистики пазлов по своему\n"
|
||
"токену. Чтобы добавить игрока,\n"
|
||
"нажмите /cancel и пришлите имя."
|
||
),
|
||
'token_added': "✅ Токен добавлен для игрока {username}!",
|
||
'gamer_added_with_token': "✅ Игрок {username} добавлен с токеном!",
|
||
# Ответы на имя ({username} экранирует вызывающий код)
|
||
'player_added': (
|
||
"✅ Добавлен <code>{username}</code>\n"
|
||
"<a href=\"https://lichess.org/@/{username}\">lichess.org/@/{username}</a>\n\n"
|
||
"🔔 Раз в час пришлю отчёт о его\n"
|
||
"партиях (если он играл).\n\n"
|
||
"/today — статистика за сегодня\n"
|
||
"Ещё игрок — просто пришлите имя."
|
||
),
|
||
'invalid_token': "❌ Неверный токен. Попробуйте еще раз.",
|
||
'token_username_error': "❌ Не удалось получить username из токена. Попробуйте еще раз.",
|
||
'player_not_found': (
|
||
"❌ На Lichess нет игрока\n"
|
||
"<code>{username}</code>.\n\n"
|
||
"Проверьте буквы и пришлите имя\n"
|
||
"ещё раз. Имя — из адреса профиля\n"
|
||
"lichess.org/@/имя"
|
||
),
|
||
'player_closed': (
|
||
"⛔ Аккаунт <code>{username}</code> закрыт\n"
|
||
"на Lichess — партий не будет.\n\n"
|
||
"Пришлите имя другого игрока."
|
||
),
|
||
'lichess_unavailable': (
|
||
"⚠️ Lichess не отвечает.\n"
|
||
"Пришлите имя ещё раз через\n"
|
||
"минуту."
|
||
),
|
||
'player_already': (
|
||
"ℹ️ <code>{username}</code> уже в вашем\n"
|
||
"списке.\n\n"
|
||
"/today — статистика за сегодня\n"
|
||
"Ещё игрок — просто пришлите имя."
|
||
),
|
||
'name_format_hint': (
|
||
"ℹ️ Имя на Lichess — латинские\n"
|
||
"буквы, цифры, «-» и «_», без\n"
|
||
"пробелов. Например <code>DrNykterstein</code>.\n\n"
|
||
"Пришлите имя ещё раз."
|
||
),
|
||
'chesscom_hint': (
|
||
"ℹ️ Похоже, это Chess.com.\n"
|
||
"Бот работает только с Lichess.\n\n"
|
||
"Если игрок есть и на Lichess,\n"
|
||
"пришлите его имя оттуда."
|
||
),
|
||
'token_rejected_notice': "⚠️ Lichess отклонил сохранённый токен для {username} — статистика по пазлам для этого игрока отключена, отслеживание партий продолжается как обычно. Используйте /addtoken, чтобы подключить новый токен и вернуть статистику по пазлам.",
|
||
'gamer_account_closed': "⛔ Аккаунт {username} на Lichess закрыт. Уведомления по нему приостановлены; если его откроют, они возобновятся автоматически.",
|
||
'gamer_account_not_found': "❌ Аккаунта {username} на Lichess больше нет (удалён или переименован). Уведомления по нему приостановлены.",
|
||
'gamer_account_reopened': "✅ Аккаунт {username} на Lichess снова активен, уведомления возобновлены.",
|
||
|
||
# Пустое состояние /today, /getgamers, /delgamer, /setperiod, /profile, /year
|
||
'no_players': (
|
||
"📭 Вы пока никого не\n"
|
||
"отслеживаете.\n\n"
|
||
"Пришлите имя игрока на Lichess,\n"
|
||
"например <code>DrNykterstein</code>, — и я\n"
|
||
"начну присылать отчёты."
|
||
),
|
||
|
||
# Get gamers
|
||
'loading_ratings': "🔄 Загрузка рейтингов игроков...",
|
||
'select_active_gamer': "👥 <b>Статистика игроков:</b>\n\n",
|
||
'gamers_closed_legend': "⛔ закрыт: {names}",
|
||
'gamers_not_found_legend': "❓ не найден: {names}",
|
||
'active_gamer_set': "✅ Активный игрок: {username}",
|
||
'gamer_not_found': "❌ Игрок не найден",
|
||
|
||
# Delete gamer
|
||
'loading_gamers': "🔄 Загрузка списка игроков...",
|
||
'select_gamer_to_delete': "🗑️ <b>Выберите игрока для удаления:</b>\n\n",
|
||
'gamer_deleted': "✅ Игрок <b>{username}</b> удален из списка отслеживаемых.",
|
||
'active_gamer_deleted': "✅ Игрок <b>{username}</b> удален из списка отслеживаемых.\n\n⚠️ Вы удалили активного игрока. Используйте команду /getgamers для выбора игрока, для которого будут работать команды /today, /yesterday, /week.",
|
||
'last_gamer_deleted': "✅ Игрок <b>{username}</b> удален из списка отслеживаемых.\n\n⚠️ Вы удалили последнего игрока. Пришлите имя игрока на Lichess, чтобы добавить нового.",
|
||
'delete_failed': "❌ Не удалось удалить игрока",
|
||
|
||
# Stats commands
|
||
'unknown_period': "❌ Неизвестный период",
|
||
'no_data': "📭 Нет данных",
|
||
'stats_title': "📊 Статистика {username} • {date_range}\n\n",
|
||
'puzzles_section': "🧩 Пазлы: {total} (✅ {solved} - ❌ {unsolved})\n\n",
|
||
'game_type_header': "{emoji} {game_type} — {games_count} игр • {rating_change}\n",
|
||
'stat_label_rating': "⭐ Рейтинг:",
|
||
'stat_label_wins': "✅ Побед:",
|
||
'stat_label_losses': "❌ Поражений:",
|
||
'stat_label_draws': "🤝 Ничьих:",
|
||
'game_rows_heading': "{emoji} Партии {game_type}:\n",
|
||
|
||
# Set period
|
||
'select_period': "⏱️ Выберите период для игрока {username}:\n📱 Уведомления будут отправляться в личные сообщения",
|
||
'notifications_disabled': "✅ Уведомления отключены для {username}",
|
||
'period_set': "✅ Период {period} минут установлен для {username}\n📱 Уведомления будут отправляться в личные сообщения",
|
||
'disable_notifications': "❌ Отключить уведомления",
|
||
'period_minutes': "⏰ {period} минут",
|
||
|
||
# Period notification
|
||
'period_1_minute': "за 1 минуту",
|
||
'period_2_3_4_minutes': "за {period} минуты",
|
||
'period_minutes_text': "за {period} минут",
|
||
'period_hours_text': "за {hours}ч",
|
||
'period_days_text': "за {days}д",
|
||
'period_notification_title': "📊 Статистика {username} • {period_text}\n\n",
|
||
'period_puzzles_section': "🧩 Пазлы: {total} (✅ {solved} - ❌ {failed})\n\n",
|
||
'no_activity': "📭 Нет активности за этот период",
|
||
|
||
# Last year or 1000 games
|
||
'last_year_1000_player_processing': "🔄 Запрос данных для игрока <b>{username}</b>...",
|
||
|
||
# Stats commands (today/yesterday/week)
|
||
'stats_player_processing': "🔄 Запрос данных для игрока <b>{username}</b>...",
|
||
|
||
# Support
|
||
'support_message': (
|
||
"💬 <b>Поддержка и обратная связь</b>\n\n"
|
||
"Вы можете написать разработчику сервиса напрямую и сообщить о проблеме, предложить новые функции или задать вопрос.\n\n"
|
||
"Я буду рад рассмотреть каждое сообщение и ответить на него.\n\n"
|
||
"Разработчик принимает сообщения на <b>английском</b> и <b>русском</b> языках.\n\n"
|
||
"📧 Контакт: <a href=\"https://t.me/vrubelr\">@vrubelr</a>\n\n"
|
||
"📦 Версия бота: <b>{version}</b>"
|
||
),
|
||
|
||
# Common
|
||
'period_minutes_suffix': "м",
|
||
'select_player_period': "⏱️ Выберите игрока, чтобы настроить период уведомлений:",
|
||
'period_set_confirm': "✅ Период {period} установлен для {username}\n📱 Уведомления будут приходить в личные сообщения",
|
||
'period_label_minutes': "{n} минут",
|
||
'period_label_hour': "1 час",
|
||
'period_label_hours': "{n} {hours_word}",
|
||
'unknown_command': (
|
||
"ℹ️ Такой команды нет.\n"
|
||
"/help — список команд."
|
||
),
|
||
'cancel_nothing': (
|
||
"ℹ️ Отменять нечего.\n"
|
||
"/help — список команд."
|
||
),
|
||
'non_text_hint': (
|
||
"ℹ️ Я читаю только текст.\n"
|
||
"Пришлите имя игрока на Lichess\n"
|
||
"текстом, например <code>DrNykterstein</code>."
|
||
),
|
||
|
||
# Language selection
|
||
'lang_prompt': "🌐 Язык / Language",
|
||
'language_set_en': "✅ Language: English",
|
||
'language_set_ru': "✅ Язык: русский",
|
||
|
||
# Profile command
|
||
'select_player_profile': "👤 <b>Выберите игрока:</b>",
|
||
'profile_link_sent': "✅ Ссылка на профиль отправлена",
|
||
}
|
||
}
|
||
|
||
|
||
def _ru_hours_word(n: int) -> str:
|
||
"""Russian plural for 'час': 1 час, 2-4 часа, 5-20 часов, 21 час, ..."""
|
||
if 11 <= n % 100 <= 14:
|
||
return "часов"
|
||
if n % 10 == 1:
|
||
return "час"
|
||
if 2 <= n % 10 <= 4:
|
||
return "часа"
|
||
return "часов"
|
||
|
||
|
||
def format_period(minutes: int, lang: str = 'en') -> str:
|
||
"""Human-readable period length ("15 minutes", "1 hour", "2 часа") in the user's language."""
|
||
if minutes < 60:
|
||
return t('period_label_minutes', lang, n=minutes)
|
||
hours = minutes // 60
|
||
if hours == 1:
|
||
return t('period_label_hour', lang)
|
||
return t('period_label_hours', lang, n=hours, hours_word=_ru_hours_word(hours))
|
||
|
||
|
||
def t(key: str, lang: str = 'en', **kwargs) -> str:
|
||
"""
|
||
Translate a key to the specified language.
|
||
|
||
Args:
|
||
key: Translation key
|
||
lang: Language code ('en' or 'ru')
|
||
**kwargs: Format arguments for the translation string
|
||
|
||
Returns:
|
||
Translated string with formatted arguments
|
||
"""
|
||
# Default to English if language not supported
|
||
if lang not in TRANSLATIONS:
|
||
lang = 'en'
|
||
|
||
translation = TRANSLATIONS[lang].get(key)
|
||
|
||
# Fallback to English if translation not found
|
||
if translation is None:
|
||
translation = TRANSLATIONS['en'].get(key, key)
|
||
|
||
# Format the string if kwargs provided
|
||
if kwargs:
|
||
try:
|
||
return translation.format(**kwargs)
|
||
except KeyError:
|
||
# If formatting fails, return the translation as-is
|
||
return translation
|
||
|
||
return translation
|