658 lines
33 KiB
Python
658 lines
33 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."
|
||
),
|
||
|
||
# /getgamers — state screen (docs/design/product_concepts.md 2.1 for the
|
||
# status wording): one line per player from the DB, no Lichess request.
|
||
'gamers_header': "👥 Players — {n}",
|
||
# {icon} 🟢/⚪/💤/⛔/❓, {name} HTML-escaped, {period} '' or " · every hour"
|
||
'gamer_line': "{icon} <code>{name}</code>\n {status}{period}",
|
||
'status_played_today': "played today",
|
||
'status_played_yesterday': "played yesterday",
|
||
'status_quiet': "{days} quiet", # {days} = "12 days" (format_count)
|
||
'status_quiet_months': "3+ months quiet",
|
||
'status_closed': "account closed",
|
||
'status_not_found': "not found on Lichess",
|
||
'status_unchecked': "not checked yet",
|
||
'gamers_footer': "Another player — just send a name.",
|
||
'btn_ratings': "📈 Ratings",
|
||
'btn_wait': "⏳",
|
||
'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.",
|
||
'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",
|
||
|
||
# "Player quiet for 30 days — keep following?" (product_concepts.md 2.7).
|
||
# {days} = "30 days" (format_count), {date} = format_day(seen_at)
|
||
'silent_prompt': (
|
||
"💤 <b>{name}</b> has not been\n"
|
||
"on Lichess for {days}. No reports\n"
|
||
"since {date}.\n\n"
|
||
"Keep following?"
|
||
),
|
||
'btn_silent_keep': "✅ Yes, keep",
|
||
'btn_silent_delete': "🗑 Remove",
|
||
'silent_kept': "✅ Kept. I'll write when {name} plays.",
|
||
'silent_deleted': "✅ {name} removed",
|
||
'silent_gone': "ℹ️ {name} is no longer tracked",
|
||
|
||
# Report (periodic notification) and the player block of /today
|
||
# (product_concepts.md 2.5 / 2.8). HTML; game rows go into one <pre>.
|
||
'report_title': "♟️ <b>{name}</b> — {games}", # {games} = "5 games"
|
||
'report_title_puzzles': "🧩 <b>{name}</b> — puzzles: {solved} of {total}",
|
||
'stats_title': "<b>{name}</b> — {games}", # /today: no ♟️
|
||
'stats_title_puzzles': "<b>{name}</b> — puzzles: {solved} of {total}",
|
||
'report_span': "over the last {span}", # {span} = "6 hours" / "3 days"
|
||
'mode_line': "{emoji} {mode} {rating} ({change})",
|
||
'mode_wins': " · {wins}/{n} won",
|
||
# column headers of the game rows (StatsFormatter.format_game_rows lays them out)
|
||
'hdr_colour': "colour",
|
||
'hdr_accuracy': "acc.",
|
||
'hdr_opponent': "opponent",
|
||
'colour_white': "white",
|
||
'colour_black': "black",
|
||
'report_more_games': "…and {games} more — /today",
|
||
'puzzles_line': "🧩 Puzzles: {solved} of {total} solved",
|
||
'report_footer': "/today — the whole day",
|
||
'no_activity': "📭 No activity for this period",
|
||
|
||
# Stats commands (today/yesterday/week)
|
||
'unknown_period': "❌ Unknown period",
|
||
'no_data': "📭 No data",
|
||
'stats_collecting_today': "🔄 Collecting today's games…",
|
||
'stats_collecting_yesterday': "🔄 Collecting yesterday's games…",
|
||
'stats_collecting_week': "🔄 Collecting the week's games…",
|
||
'stats_head_today': "📊 Today, {date}",
|
||
'stats_head_yesterday': "📊 Yesterday, {date}",
|
||
'stats_head_week': "📊 Week, {range}",
|
||
'stats_no_play': "<b>{name}</b> — didn't play",
|
||
'stats_status': "<b>{name}</b> — {status}",
|
||
'stats_error': "<b>{name}</b> — ⚠️ could not get data",
|
||
'stats_nobody_today': "📭 None of your players played today",
|
||
'stats_nobody_yesterday': "📭 None of your players played yesterday",
|
||
'stats_nobody_week': "📭 None of your players played this week",
|
||
'btn_today': "📅 Today",
|
||
'btn_yesterday': "📅 Yesterday",
|
||
'btn_week': "📅 Week",
|
||
# Dates in words ("21 October"): month names in the form used after a day number
|
||
'month_names': "January February March April May June July August September October November December",
|
||
|
||
# Set period
|
||
'select_period': "⏱️ Select period for player {username}:\n📱 Notifications will be sent to personal messages",
|
||
'notifications_disabled': "✅ Notifications disabled for {username}",
|
||
'disable_notifications': "❌ Disable notifications",
|
||
|
||
# Last year or 1000 games (/year)
|
||
'last_year_1000_player_processing': "🔄 Requesting data for player <b>{username}</b>...",
|
||
'year_title_1000': "📈 <b>{name}</b>: last 1000 games\nsince {date}, rated",
|
||
'year_title': "📈 <b>{name}</b>: last year, {games}\n{start}–{end}, rated",
|
||
# per mode: "🔥 Blitz 2257 (+45)" (mode_line), then these two
|
||
'year_mode_results': " {games} · +{wins} −{losses} ={draws}",
|
||
'year_mode_accuracy': " accuracy {acc}",
|
||
|
||
# Plural word forms for format_count: "one|many" (en), "one|few|many" (ru)
|
||
'word_games': "game|games",
|
||
'word_days': "day|days",
|
||
'word_hours': "hour|hours",
|
||
|
||
# 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
|
||
'select_player_period': "⏱️ Select a player to set the notification period:",
|
||
'period_set_confirm': "✅ {username}: reports {period}",
|
||
# format_period: the one spelling of a report period everywhere
|
||
'period_every_hour': "every hour",
|
||
'period_every_day': "every day",
|
||
'period_every_minutes': "every {n} min",
|
||
'period_every_hours': "every {n} h",
|
||
'period_every_days': "every {n} d",
|
||
'reports_off': "🔕 reports off",
|
||
'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"
|
||
"начну присылать отчёты."
|
||
),
|
||
|
||
# /getgamers — экран состояния (docs/design/product_concepts.md 2.1):
|
||
# строка на игрока из БД, без запросов к Lichess.
|
||
'gamers_header': "👥 Игроки — {n}",
|
||
'gamer_line': "{icon} <code>{name}</code>\n {status}{period}",
|
||
'status_played_today': "играл сегодня",
|
||
'status_played_yesterday': "играл вчера",
|
||
'status_quiet': "{days} тихо", # {days} = "12 дней" (format_count)
|
||
'status_quiet_months': "больше 3 месяцев тихо",
|
||
'status_closed': "аккаунт закрыт",
|
||
'status_not_found': "не найден на Lichess",
|
||
'status_unchecked': "ещё не проверял",
|
||
'gamers_footer': "Ещё игрок — просто пришлите имя.",
|
||
'btn_ratings': "📈 Рейтинги",
|
||
'btn_wait': "⏳",
|
||
'gamer_not_found': "❌ Игрок не найден",
|
||
|
||
# Delete gamer
|
||
'loading_gamers': "🔄 Загрузка списка игроков...",
|
||
'select_gamer_to_delete': "🗑️ <b>Выберите игрока для удаления:</b>\n\n",
|
||
'gamer_deleted': "✅ Игрок <b>{username}</b> удален из списка отслеживаемых.",
|
||
'last_gamer_deleted': "✅ Игрок <b>{username}</b> удален из списка отслеживаемых.\n\n⚠️ Вы удалили последнего игрока. Пришлите имя игрока на Lichess, чтобы добавить нового.",
|
||
'delete_failed': "❌ Не удалось удалить игрока",
|
||
|
||
# «Игрок молчит 30 дней — продолжать?» (product_concepts.md 2.7)
|
||
'silent_prompt': (
|
||
"💤 <b>{name}</b> не заходил на\n"
|
||
"Lichess {days}. Отчётов по нему\n"
|
||
"не было с {date}.\n\n"
|
||
"Продолжать следить?"
|
||
),
|
||
'btn_silent_keep': "✅ Да, оставить",
|
||
'btn_silent_delete': "🗑 Удалить",
|
||
'silent_kept': "✅ Оставил. Напишу, когда {name} сыграет.",
|
||
'silent_deleted': "✅ {name} удалён",
|
||
'silent_gone': "ℹ️ {name} уже не отслеживается",
|
||
|
||
# Отчёт (периодическое уведомление) и блок игрока в /today
|
||
# (product_concepts.md 2.5 / 2.8). HTML; строки партий — в одном <pre>.
|
||
'report_title': "♟️ <b>{name}</b> — {games}", # {games} = "5 партий"
|
||
'report_title_puzzles': "🧩 <b>{name}</b> — пазлы: {solved} из {total}",
|
||
'stats_title': "<b>{name}</b> — {games}", # /today: без ♟️
|
||
'stats_title_puzzles': "<b>{name}</b> — пазлы: {solved} из {total}",
|
||
'report_span': "за последние {span}", # {span} = "6 часов" / "3 дня"
|
||
'mode_line': "{emoji} {mode} {rating} ({change})",
|
||
'mode_wins': " · {wins}/{n} побед",
|
||
# заголовки колонок строк партий (раскладка — StatsFormatter.format_game_rows)
|
||
'hdr_colour': "цвет",
|
||
'hdr_accuracy': "точн.",
|
||
'hdr_opponent': "соперник",
|
||
'colour_white': "белые",
|
||
'colour_black': "чёрные",
|
||
'report_more_games': "…и ещё {games} — /today",
|
||
'puzzles_line': "🧩 Пазлы: {solved} из {total} решены",
|
||
'report_footer': "/today — весь день",
|
||
'no_activity': "📭 Нет активности за этот период",
|
||
|
||
# Stats commands (today/yesterday/week)
|
||
'unknown_period': "❌ Неизвестный период",
|
||
'no_data': "📭 Нет данных",
|
||
'stats_collecting_today': "🔄 Собираю партии за сегодня…",
|
||
'stats_collecting_yesterday': "🔄 Собираю партии за вчера…",
|
||
'stats_collecting_week': "🔄 Собираю партии за неделю…",
|
||
'stats_head_today': "📊 Сегодня, {date}",
|
||
'stats_head_yesterday': "📊 Вчера, {date}",
|
||
'stats_head_week': "📊 Неделя, {range}",
|
||
'stats_no_play': "<b>{name}</b> — не играл",
|
||
'stats_status': "<b>{name}</b> — {status}",
|
||
'stats_error': "<b>{name}</b> — ⚠️ не удалось получить данные",
|
||
'stats_nobody_today': "📭 Сегодня никто из ваших игроков не играл",
|
||
'stats_nobody_yesterday': "📭 Вчера никто из ваших игроков не играл",
|
||
'stats_nobody_week': "📭 За неделю никто из ваших игроков не играл",
|
||
'btn_today': "📅 Сегодня",
|
||
'btn_yesterday': "📅 Вчера",
|
||
'btn_week': "📅 Неделя",
|
||
# Даты словами («21 октября»): названия месяцев в родительном падеже
|
||
'month_names': "января февраля марта апреля мая июня июля августа сентября октября ноября декабря",
|
||
|
||
# Set period
|
||
'select_period': "⏱️ Выберите период для игрока {username}:\n📱 Уведомления будут отправляться в личные сообщения",
|
||
'notifications_disabled': "✅ Уведомления отключены для {username}",
|
||
'disable_notifications': "❌ Отключить уведомления",
|
||
|
||
# Last year or 1000 games (/year)
|
||
'last_year_1000_player_processing': "🔄 Запрос данных для игрока <b>{username}</b>...",
|
||
'year_title_1000': "📈 <b>{name}</b>: последние 1000 партий\nс {date}, рейтинговые",
|
||
'year_title': "📈 <b>{name}</b>: за год, {games}\n{start}–{end}, рейтинговые",
|
||
'year_mode_results': " {games} · +{wins} −{losses} ={draws}",
|
||
'year_mode_accuracy': " точность {acc}",
|
||
|
||
# Формы слов для format_count: "один|несколько|много"
|
||
'word_games': "партия|партии|партий",
|
||
'word_days': "день|дня|дней",
|
||
'word_hours': "час|часа|часов",
|
||
|
||
# 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
|
||
'select_player_period': "⏱️ Выберите игрока, чтобы настроить период уведомлений:",
|
||
'period_set_confirm': "✅ {username}: отчёты {period}",
|
||
# format_period: единое написание периода отчётов везде
|
||
'period_every_hour': "раз в час",
|
||
'period_every_day': "раз в день",
|
||
'period_every_minutes': "раз в {n} мин",
|
||
'period_every_hours': "раз в {n} ч",
|
||
'period_every_days': "раз в {n} дн",
|
||
'reports_off': "🔕 отчёты выключены",
|
||
'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_plural_index(n: int) -> int:
|
||
"""0 for 1/21/31…, 1 for 2-4/22-24…, 2 for 5-20/25-30… (Russian plural rule)."""
|
||
if 11 <= n % 100 <= 14:
|
||
return 2
|
||
if n % 10 == 1:
|
||
return 0
|
||
if 2 <= n % 10 <= 4:
|
||
return 1
|
||
return 2
|
||
|
||
|
||
def _ru_hours_word(n: int) -> str:
|
||
"""Russian plural for 'час': 1 час, 2-4 часа, 5-20 часов, 21 час, ..."""
|
||
return ("час", "часа", "часов")[_ru_plural_index(n)]
|
||
|
||
|
||
def format_count(n: int, what: str, lang: str = 'en') -> str:
|
||
"""
|
||
"5 партий" / "5 games", "1 день" / "1 day", "3 часа" / "3 hours": a number
|
||
with the right plural form of `what` ('games' | 'days' | 'hours'), the
|
||
word forms coming from the 'word_<what>' key ("one|few|many" for ru,
|
||
"one|many" for en).
|
||
"""
|
||
forms = t(f'word_{what}', lang).split('|')
|
||
if len(forms) == 3:
|
||
word = forms[_ru_plural_index(n)]
|
||
else:
|
||
word = forms[0] if n == 1 else forms[-1]
|
||
return f"{n} {word}"
|
||
|
||
|
||
def format_period(minutes: int, lang: str = 'en') -> str:
|
||
"""
|
||
The one spelling of a report period: "раз в час" / "every hour" (60),
|
||
"раз в день" / "every day" (1440), "раз в 15 мин", "раз в 6 ч", "раз в 3 дн";
|
||
0 is "🔕 отчёты выключены" / "🔕 reports off". Used by /getgamers,
|
||
/setperiod (buttons and confirmation) and everywhere a period is shown.
|
||
"""
|
||
if minutes <= 0:
|
||
return t('reports_off', lang)
|
||
if minutes == 60:
|
||
return t('period_every_hour', lang)
|
||
if minutes == 1440:
|
||
return t('period_every_day', lang)
|
||
if minutes < 60:
|
||
return t('period_every_minutes', lang, n=minutes)
|
||
if minutes % 1440 == 0:
|
||
return t('period_every_days', lang, n=minutes // 1440)
|
||
if minutes % 60 == 0:
|
||
return t('period_every_hours', lang, n=minutes // 60)
|
||
return t('period_every_minutes', lang, n=minutes)
|
||
|
||
|
||
def format_day(dt, lang: str = 'en', today=None) -> str:
|
||
"""
|
||
A date in words: "21 октября" / "21 October"; the year is added only when
|
||
it is not the current one ("21 сентября 2025"). `today` (a date) overrides
|
||
"now" for tests.
|
||
"""
|
||
from datetime import date
|
||
today = today or date.today()
|
||
month = t('month_names', lang).split()[dt.month - 1]
|
||
if dt.year != today.year:
|
||
return f"{dt.day} {month} {dt.year}"
|
||
return f"{dt.day} {month}"
|
||
|
||
|
||
def format_day_range(start, end, lang: str = 'en', today=None) -> str:
|
||
""""15–21 октября" when the two dates share a month, else "28 сентября – 4 октября"."""
|
||
if start.year == end.year and start.month == end.month:
|
||
return f"{start.day}–{format_day(end, lang, today)}"
|
||
return f"{format_day(start, lang, today)} – {format_day(end, lang, today)}"
|
||
|
||
|
||
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
|