drop the 'player quiet for 30 days' prompt (owner decision)
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 29s

The bot sends nothing on its own initiative except reports and the closed /
not-found account notices. Removes the periodic check, the sl: callbacks,
the silent_prompt_at column migration, the i18n keys and their tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-21 11:58:51 +00:00
parent 37d8d8a69e
commit 58bf8b7381
11 changed files with 13 additions and 338 deletions

View file

@ -17,7 +17,6 @@
- Эмодзи bullet — «⚡» без селектора варианта (одинаковая ширина с остальными)
### Добавлено
- **«Игрок молчит 30 дней — продолжать?»**: когда bulk-статус показывает, что игрок не заходил на Lichess 30+ дней (аккаунт при этом не закрыт и не удалён — у тех своё уведомление), периодическая проверка пары один раз присылает «💤 **Имя** не заходил на Lichess 30 дней. Отчётов по нему не было с 21 сентября. Продолжать следить?» с кнопками «✅ Да, оставить» / «🗑 Удалить». «Да» — не спрашивать ещё 90 дней; «Удалить» — пара удаляется без второго подтверждения (сообщение → «✅ Имя удалён»); без ответа ничего не меняется. Новая колонка `user_gamers.silent_prompt_at`. Пары с выключенными отчётами задач не имеют и не спрашиваются. Блокировка бота при отправке вопроса обрабатывается как у отчёта
- Stats-сервис: в строках партий (`GameRow`) новое необязательное поле `tracked_rating_diff` — `ratingDiff` отслеживаемого игрока в этой партии (колонка «±» отчёта); `None`, если сторона неизвестна или Lichess поле не вернул
- `events.log`: `report_sent uid= gamer= games= rows= puzzles= span_min=` при каждом отправленном отчёте (счётчик `periodic_notification` остался — его читает админский `/status`); `silent_prompt uid= gamer= days=`; `silent_prompt_result uid= gamer= result=keep|delete`; `gamer_deleted … via=delgamer|silent_prompt`; `cmd name=getgamers_ratings`; `cmd name=today|yesterday|week via=button`
- Тесты: `tests/bot/test_report.py` (точные тексты отчёта на 1/5/12 партий, пазлы, bullet, два режима, длинное окно, отсутствующие значения, EN, правило 34 символов, блоки `/today`, `/year`, таблица рейтингов), `tests/bot/test_state_screen.py` (`/getgamers` без запросов к Lichess, порядок статусов, кнопка рейтингов, `/delgamer`, вопрос о молчащем игроке и ответы на него, `/today` одним сообщением, кнопки периодов, `/setperiod`), `tests/service`: `tracked_rating_diff`

View file

@ -748,52 +748,6 @@ class LichessBot:
else:
await query.edit_message_text(t('gamer_not_found', lang))
async def handle_silent_prompt(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
Answer to "player quiet for N days — keep following?" (periodic.py,
docs/design/product_concepts.md 2.7): sl:keep:<gamer_id> keeps the
pair and postpones the next question by 90 days (silent_prompt_at =
now); sl:del:<gamer_id> removes the pair like /delgamer, without a
second confirmation (the question was the confirmation), and stops its
task. A pair that is already gone gets "no longer tracked".
"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
lang = self._callback_lang(update)
_, action, gamer_id = query.data.split(':')
gamer_id = int(gamer_id)
pair = next((g for g in self.db.get_user_gamers(user_id) if g['id'] == gamer_id), None)
if pair:
name = pair['username']
else:
# The pair (and maybe the gamer row) is gone: the name is still in
# the question ("💤 Name …"), use that when the DB has nothing
name = self.db.get_gamer_username(gamer_id)
if name is None:
words = (getattr(query.message, 'text', None) or '').split()
name = words[1] if len(words) > 1 else '?'
shown = html.escape(name)
if pair is None:
logger.info(f"silent_prompt: {name} is no longer tracked by user {user_id} (action {action})")
await query.edit_message_text(t('silent_gone', lang, name=shown), parse_mode='HTML')
return
if action == 'keep':
self.db.set_pair_silent_prompt_at(user_id, gamer_id, int(time.time()))
event('silent_prompt_result', uid=user_id, gamer=name, result='keep')
logger.info(f"silent_prompt: user {user_id} keeps {name}")
await query.edit_message_text(t('silent_kept', lang, name=shown), parse_mode='HTML')
return
self.db.remove_user_gamer(user_id, gamer_id)
await self.monitor.stop_periodic_task(gamer_id, user_id)
remaining = len(self.db.get_user_gamers(user_id))
event('silent_prompt_result', uid=user_id, gamer=name, result='delete')
event('gamer_deleted', uid=user_id, gamer=name, remaining=remaining, via='silent_prompt')
logger.info(f"silent_prompt: user {user_id} removed {name} ({remaining} left)")
await query.edit_message_text(t('silent_deleted', lang, name=shown), parse_mode='HTML')
@staticmethod
def _stats_period_bounds(period: str, now_dt: datetime):
"""
@ -1561,7 +1515,6 @@ class LichessBot:
# buttons under /today. All stateless: they keep working after a restart.
application.add_handler(CallbackQueryHandler(self.handle_gamers_ratings, pattern="^gm:ratings$"))
application.add_handler(CallbackQueryHandler(self.handle_wait_button, pattern="^gm:wait$"))
application.add_handler(CallbackQueryHandler(self.handle_silent_prompt, pattern=r"^sl:(keep|del):\d+$"))
application.add_handler(CallbackQueryHandler(self.handle_stats_nav, pattern="^st:(today|yesterday|week)$"))
# Anything that is a private message but not text/command (photo of a profile,

View file

@ -104,14 +104,6 @@ class Database:
# Column already exists
pass
# When the owner was last asked "player quiet for 30 days — keep
# following?" (unix seconds, see periodic.py); NULL = never. Asked
# again no sooner than 90 days later ("keep" refreshes it too).
try:
cursor.execute("ALTER TABLE user_gamers ADD COLUMN silent_prompt_at INTEGER")
except sqlite3.OperationalError:
# Column already exists
pass
# Latest bulk status of each tracked player from POST /api/users
# (player_status.py refreshes it every PLAYER_STATUS_REFRESH_MINUTES).
@ -777,45 +769,27 @@ class Database:
for row in cursor.fetchall()
}
def get_gamer_username(self, gamer_id: int) -> Optional[str]:
"""Username of a gamer by id, or None if the row is gone (nobody tracks it any more)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT username FROM gamers WHERE id = ?", (gamer_id,))
row = cursor.fetchone()
return row[0] if row else None
def get_pair_check_state(self, user_id: int, gamer_id: int) -> Dict[str, Any]:
"""
Per-pair skip state: games_total baseline from the last games request,
whether the closed-account notice went out, and when the "quiet for 30
days" question was last asked (unix seconds or None).
Per-pair skip state: games_total baseline from the last games request
and whether the closed-account notice went out.
"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT last_games_total, closed_notice_sent, silent_prompt_at FROM user_gamers "
"SELECT last_games_total, closed_notice_sent FROM user_gamers "
"WHERE user_id = ? AND gamer_id = ?",
(user_id, gamer_id)
)
row = cursor.fetchone()
if not row:
return {'last_games_total': None, 'closed_notice_sent': False, 'silent_prompt_at': None}
return {'last_games_total': None, 'closed_notice_sent': False}
return {
'last_games_total': int(row[0]) if row[0] is not None else None,
'closed_notice_sent': bool(row[1]),
'silent_prompt_at': int(row[2]) if row[2] is not None else None,
}
def set_pair_silent_prompt_at(self, user_id: int, gamer_id: int, ts: Optional[int]):
"""Remember when the owner was asked about this quiet player (None clears it)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE user_gamers SET silent_prompt_at = ? WHERE user_id = ? AND gamer_id = ?",
(ts, user_id, gamer_id)
)
conn.commit()
def set_pair_last_games_total(self, user_id: int, gamer_id: int, games_total: Optional[int]):
"""Remember the player's games_total as of this pair's last successful games request."""

View file

@ -167,19 +167,6 @@ TRANSLATIONS = {
'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>.
@ -434,18 +421,6 @@ TRANSLATIONS = {
'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>.

View file

@ -16,21 +16,19 @@ window is skipped without any HTTP call; a closed account pauses the pair. See
_decide_skip / _skip_window_end for the exact rules and their safety argument.
"""
import asyncio
import html
import logging
import time
import zlib
from datetime import datetime, timedelta, timezone
from typing import Dict, Any
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.error import Forbidden
import config
from database import Database
from lichess_api import LichessAPI, InvalidTokenError
from formatters import StatsFormatter, ROW_MODES
from i18n import t, format_count, format_day
from i18n import t
from message_counters import MessageCounters
from notifications import AdminNotifier
from player_status import PlayerStatusRefresher
@ -189,79 +187,6 @@ class PeriodicMonitor:
covered_until = datetime.fromtimestamp(status['checked_at'] - cls.STATUS_SAFETY_MARGIN_SECONDS)
return min(period_end_approx, covered_until)
# "Player quiet for N days — keep following?" (docs/design/product_concepts.md
# 2.7): asked once seen_at is this old, and again no sooner than
# SILENT_PROMPT_REPEAT_DAYS after the last question ("keep" counts as one).
SILENT_PROMPT_DAYS = 30
SILENT_PROMPT_REPEAT_DAYS = 90
@classmethod
def _silent_prompt_days(cls, status, silent_prompt_at, now_ts: float):
"""
How many whole days the player has been quiet when the owner should be
asked about them now, else None. Asked only for a player whose status
has a seen_at (bulk status, ms) at least SILENT_PROMPT_DAYS old and who
is neither closed nor gone (those get their own notice), and only if
the question was never asked or was asked more than
SILENT_PROMPT_REPEAT_DAYS ago. Pure function, unit-tested.
"""
if not status or status.get('disabled') or status.get('not_found'):
return None
seen_at = status.get('seen_at')
if seen_at is None:
return None
days = int((now_ts - seen_at / 1000) // 86400)
if days < cls.SILENT_PROMPT_DAYS:
return None
if silent_prompt_at is not None and now_ts - silent_prompt_at < cls.SILENT_PROMPT_REPEAT_DAYS * 86400:
return None
return days
def silent_prompt_text(self, username: str, days: int, seen_at_ms: int, lang: str) -> str:
"""The 2.7 message for a player quiet for `days` days, last seen at seen_at_ms (HTML)."""
seen_day = datetime.fromtimestamp(seen_at_ms / 1000).date()
return t('silent_prompt', lang, name=html.escape(username), days=format_count(days, 'days', lang),
date=format_day(seen_day, lang))
def silent_prompt_keyboard(self, gamer_id: int, lang: str) -> InlineKeyboardMarkup:
"""[✅ Да, оставить] [🗑 Удалить] -> sl:keep:<id> / sl:del:<id> (handled in bot.py)."""
return InlineKeyboardMarkup([[
InlineKeyboardButton(t('btn_silent_keep', lang), callback_data=f"sl:keep:{gamer_id}"),
InlineKeyboardButton(t('btn_silent_delete', lang), callback_data=f"sl:del:{gamer_id}"),
]])
async def _maybe_silent_prompt(self, user_id: int, gamer: Dict[str, Any], status, pair_state, task_key: str) -> bool:
"""
Send the "quiet for N days" question if it is due (_silent_prompt_days)
and record silent_prompt_at. Returns True when the user has blocked the
bot (the pair was stopped, the caller must return). Any other send
failure is logged and the question is retried at the next check. The
periodic check itself continues as usual after this.
"""
days = self._silent_prompt_days(status, pair_state.get('silent_prompt_at'), time.time())
if days is None:
return False
username = gamer['username']
try:
user_lang = self.db.get_user_language(user_id)
await self.application.bot.send_message(
chat_id=user_id,
text=self.silent_prompt_text(username, days, status['seen_at'], user_lang),
parse_mode='HTML',
reply_markup=self.silent_prompt_keyboard(gamer['id'], user_lang)
)
except Forbidden:
self._stop_pair_blocked(user_id, gamer, task_key)
return True
except Exception as notify_err:
logger.error(f"Failed to ask user {user_id} about quiet player {username}: {notify_err}")
return False
now_ts = int(time.time())
self.db.set_pair_silent_prompt_at(user_id, gamer['id'], now_ts)
pair_state['silent_prompt_at'] = now_ts
logger.info(f"💤 Asked user {user_id} whether to keep {username} (quiet for {days} days)")
event('silent_prompt', uid=user_id, gamer=username, days=days)
return False
def _stop_pair_blocked(self, user_id: int, gamer: Dict[str, Any], task_key: str) -> None:
"""
@ -421,13 +346,6 @@ class PeriodicMonitor:
self.db.set_pair_closed_notice_sent(user_id, gamer['id'], False)
pair_state['closed_notice_sent'] = False
# A player quiet for 30+ days: ask the owner once whether to keep
# them (see _maybe_silent_prompt). Before the decision for the same
# reason as the reopened notice: such a pair skips every window.
# Does not touch the checkpoint or the decision below.
if await self._maybe_silent_prompt(user_id, gamer, status, pair_state, task_key):
return
decision = self._decide_skip(
status, pair_state, time.time(), has_token=bool(gamer.get('token')),
since_ts=since_time.timestamp()

View file

@ -154,7 +154,6 @@ Zhigalko_Sergei — не играл
- Если бот какое-то время не работал (обновление, сбой), он закрывает пропущенное одним отчётом за всё окно; при окне от 6 часов под первой строкой будет «за последние N часов». Если простой был дольше, чем «период + 2 часа», старая активность уже не присылается.
- **Закрытый аккаунт.** Если игрок закрыл аккаунт на Lichess, бот один раз пришлёт «⛔ Аккаунт … на Lichess закрыт. Уведомления по нему приостановлены; если его откроют, они возобновятся автоматически» и перестанет его проверять. Когда аккаунт снова откроют, придёт «✅ Аккаунт … на Lichess снова активен, уведомления возобновлены». В `/getgamers` и `/delgamer` такой игрок помечен ⛔.
- **Аккаунта больше нет.** Если игрок удалил аккаунт или сменил имя, так что Lichess больше не знает прежнего ника, бот ставит его на паузу точно так же, один раз прислав «❌ Аккаунта … на Lichess больше нет (удалён или переименован). Уведомления по нему приостановлены»; в `/getgamers` и `/delgamer` он помечен ❓. Если ник снова появится на Lichess, уведомления возобновятся с тем же сообщением «✅ … снова активен»; под новым ником игрока нужно добавить заново через `/addgamer`.
- **Игрок давно не играет.** Если игрок не заходил на Lichess 30 дней, бот один раз спросит: «💤 Имя не заходил на Lichess 30 дней. Отчётов по нему не было с 21 сентября. Продолжать следить?» с кнопками «✅ Да, оставить» и «🗑 Удалить». «Да» — вопрос не повторится ещё 90 дней; «Удалить» — игрок удаляется сразу, без второго подтверждения. Без ответа ничего не меняется: сам бот игроков не удаляет. Для закрытых и не найденных аккаунтов этого вопроса нет — у них свои уведомления (выше).
- Если вы заблокировали бота, уведомления по всем вашим игрокам выключаются (период сбрасывается). После разблокировки включите их заново через `/setperiod`.
- Бот проверяет игроков с задержкой: за один период может прийти уведомление с опозданием на несколько минут — это нормально.

View file

@ -49,7 +49,7 @@
1. **Новый почасовой отчёт** (макет дизайнера, раздел 2): первая строка «♟️ Имя — 5 партий», вторая — режим, рейтинг, ±, «3/5 побед»; по строке на партию (результат · ±рейтинг · цвет фигур игрока словом · точность игрока · рейтинг и точность соперника) под шапкой «± цвет точн. соперник»; имя не повторяется; `<pre>` только для строк; склонения; лимит строк с «и ещё N»; 0 партий — ничего не отправляется (как сейчас). Кнопка «🏠 Домой» появится в итерации 3, пока — строка «/today — весь день».
2. **`/getgamers` как экран состояния** без запросов к Lichess: по строке на игрока «🟢 играл сегодня · раз в час», «⚪ 12 дней тихо · раз в час», «⛔ закрыт», «🔕 выключено»; данные из `gamer_status.seen_at` и `user_gamers.period_minutes`. Рейтинги — по кнопке у строки, не при открытии списка.
3. **Уснувший игрок**: одно сообщение «Имя не играл 30 дней. Продолжать следить?» с кнопками «Оставить» / «Удалить», не чаще раза в 30 дней на пару (новая колонка `silent_notice_at`).
3. ~~**Уснувший игрок**: вопрос «не играл 30 дней, продолжать?»~~ — отклонено владельцем 2026-10-21, бот не пишет по своей инициативе ничего, кроме отчётов и уведомлений о закрытии аккаунта.
4. **Баги текстов**: `active_gamer_deleted` отправляет к выбору игрока в `/getgamers`, которого не существует (статистика считается по всем игрокам) — заменить на обычный `gamer_deleted`; убрать 🟢/⚪ «активности» из `/delgamer`; `/year` с английским заголовком и строкой 48 символов; N/A в русском; четыре написания периода → одно.
5. **`/today` одним сообщением**: сначала «⏳ Считаю 3 игроков…», затем это же сообщение редактируется в итог; вместо N мигающих «🔄» и N сообщений.

View file

@ -324,6 +324,8 @@ Zhigalko_Sergei — 3 партии
### 2.7 «Игрок молчит 30 дней — продолжать?»
> Отклонено владельцем 2026-10-21: реализовано в итерации 1 и убрано до выпуска. Оставлено как справка.
```
.........|.........|.........|....
💤 Zhigalko_Sergei не заходил на

View file

@ -183,19 +183,13 @@ class DatabaseTests(unittest.TestCase):
def test_pair_check_state(self):
a = self.ids()['Alpha']
empty = {'last_games_total': None, 'closed_notice_sent': False, 'silent_prompt_at': None}
empty = {'last_games_total': None, 'closed_notice_sent': False}
self.assertEqual(empty, self.db.get_pair_check_state(1, a))
self.db.set_pair_last_games_total(1, a, 42)
self.db.set_pair_closed_notice_sent(1, a, True)
self.db.set_pair_silent_prompt_at(1, a, 1_800_000_000)
self.assertEqual({'last_games_total': 42, 'closed_notice_sent': True, 'silent_prompt_at': 1_800_000_000},
self.assertEqual({'last_games_total': 42, 'closed_notice_sent': True},
self.db.get_pair_check_state(1, a))
self.db.set_pair_silent_prompt_at(1, a, None)
self.assertIsNone(self.db.get_pair_check_state(1, a)['silent_prompt_at'])
self.assertEqual(empty, self.db.get_pair_check_state(9, a))
with sqlite3.connect(self.path) as conn:
cols = {row[1] for row in conn.execute("PRAGMA table_info(user_gamers)")}
self.assertIn('silent_prompt_at', cols)
def test_gamer_statuses_bulk_and_username(self):
ids = self.ids()
@ -208,8 +202,6 @@ class DatabaseTests(unittest.TestCase):
self.assertEqual({a, c}, set(statuses)) # Bravo has no row
self.assertEqual(self.db.get_gamer_status(a), statuses[a])
self.assertEqual(self.db.get_gamer_status(c), statuses[c])
self.assertEqual('Alpha', self.db.get_gamer_username(a))
self.assertIsNone(self.db.get_gamer_username(10 ** 6))
def test_remove_user_gamer_cascade(self):
ids = self.ids()

View file

@ -1,8 +1,7 @@
"""
Iteration-1 screens on fake Update/Context objects (tests/bot/_fakes.py):
/getgamers as a state screen without any Lichess request, its 📈 Ratings
button, the "quiet for 30 days" question (periodic.py) and its answers
(sl:keep / sl:del), and /today as one message edited into the result with
button, and /today as one message edited into the result with
the st:<period> buttons.
"""
from tests.bot import _env # noqa: F401 (environment before bot imports)
@ -11,15 +10,11 @@ import asyncio
import time
import unittest
from datetime import date, datetime
from types import SimpleNamespace
from telegram.error import Forbidden
import periodic as periodic_module
from bot import LichessBot
from formatters import StatsFormatter
from i18n import format_day, t
from periodic import PeriodicMonitor
from i18n import t
from tests.bot._fakes import buttons, make_bot, make_context, make_update, restore_events
from tests.bot.test_report import FIVE_GAMES, FIVE_ROWS, TodayBlockTests
@ -203,138 +198,6 @@ class GetGamersTests(ScreenTestCase):
self.assertEqual({'uid': 1, 'gamer': 'Ab', 'remaining': 1, 'via': 'delgamer'}, self.last_event('gamer_deleted'))
class FakeTgBot:
def __init__(self, forbidden=False):
self.sent = []
self.forbidden = forbidden
async def send_message(self, chat_id, text, **kwargs):
if self.forbidden:
raise Forbidden("blocked")
self.sent.append((chat_id, text, kwargs))
class SilentPromptDecisionTests(unittest.TestCase):
NOW = 1_800_000_000.0
def status(self, days, **over):
st = {'disabled': False, 'not_found': False, 'games_total': 1, 'checked_at': self.NOW, 'missing_count': 0,
'seen_at': None if days is None else int((self.NOW - days * DAY) * 1000)}
st.update(over)
return st
def test_table(self):
f = PeriodicMonitor._silent_prompt_days
cases = [
(None, None, None, None), # no status
(None, self.status(None), None, None), # no seen_at
(None, self.status(29.9), None, None), # not yet
(30, self.status(30), None, None), # due
(45, self.status(45.7), None, None), # whole days
(None, self.status(45), self.NOW - 89 * DAY, None), # asked 89 days ago
(135, self.status(135), self.NOW - 91 * DAY, None), # asked 91 days ago: again
(None, self.status(45, disabled=True), None, None), # closed: own notice
(None, self.status(45, not_found=True), None, None), # gone: own notice
]
for expected, st, asked, _ in cases:
with self.subTest(status=st, asked=asked):
self.assertEqual(expected, f(st, asked, self.NOW))
class SilentPromptTests(ScreenTestCase):
def setUp(self):
super().setUp()
self._orig_periodic_event = periodic_module.event
self.periodic_events = []
periodic_module.event = lambda _name, **fields: self.periodic_events.append((_name, fields))
def tearDown(self):
periodic_module.event = self._orig_periodic_event
super().tearDown()
def monitor(self, forbidden=False):
mon = PeriodicMonitor(self.bot.db, self.bot.lichess_api, SimpleNamespace(), SimpleNamespace())
mon.application = SimpleNamespace(bot=FakeTgBot(forbidden))
return mon
def test_text_and_keyboard(self):
mon = self.monitor()
seen = datetime(date.today().year, 9, 21, 12, 0)
text = mon.silent_prompt_text('Zhigalko_Sergei', 30, int(seen.timestamp() * 1000), 'ru')
self.assertEqual("💤 <b>Zhigalko_Sergei</b> не заходил на\nLichess 30 дней. Отчётов по нему\n"
"не было с 21 сентября.\n\nПродолжать следить?", text)
en = mon.silent_prompt_text('Zhigalko_Sergei', 31, int(seen.timestamp() * 1000), 'en')
self.assertEqual("💤 <b>Zhigalko_Sergei</b> has not been\non Lichess for 31 days. No reports\n"
"since 21 September.\n\nKeep following?", en)
self.assertIn("&lt;b&gt;", mon.silent_prompt_text('<b>', 30, int(seen.timestamp() * 1000), 'ru'))
kb = mon.silent_prompt_keyboard(7, 'ru')
self.assertEqual([[("✅ Да, оставить", "sl:keep:7"), ("🗑 Удалить", "sl:del:7")]],
[[(b.text, b.callback_data) for b in row] for row in kb.inline_keyboard])
def test_sends_once_and_records(self):
gid = add_player(self.bot, 1, 'Zhigalko_Sergei', 60)
set_status(self.bot, gid, 40)
mon = self.monitor()
gamer = {'id': gid, 'username': 'Zhigalko_Sergei', 'token': None, 'period_minutes': 60}
status = self.bot.db.get_gamer_status(gid)
state = self.bot.db.get_pair_check_state(1, gid)
blocked = run(mon._maybe_silent_prompt(1, gamer, status, state, f"{gid}_1"))
self.assertFalse(blocked)
self.assertEqual(1, len(mon.application.bot.sent))
chat_id, text, kw = mon.application.bot.sent[0]
self.assertEqual(1, chat_id)
self.assertEqual('HTML', kw['parse_mode'])
self.assertTrue(text.startswith("💤 <b>Zhigalko_Sergei</b> не заходил на\nLichess 40 дней."), text)
self.assertIsNotNone(self.bot.db.get_pair_check_state(1, gid)['silent_prompt_at'])
self.assertEqual(('silent_prompt', {'uid': 1, 'gamer': 'Zhigalko_Sergei', 'days': 40}), self.periodic_events[-1])
# second check right after: not asked again
state = self.bot.db.get_pair_check_state(1, gid)
self.assertFalse(run(mon._maybe_silent_prompt(1, gamer, status, state, f"{gid}_1")))
self.assertEqual(1, len(mon.application.bot.sent))
def test_forbidden_stops_the_pair(self):
gid = add_player(self.bot, 1, 'Zhigalko_Sergei', 60)
set_status(self.bot, gid, 40)
mon = self.monitor(forbidden=True)
gamer = {'id': gid, 'username': 'Zhigalko_Sergei', 'token': None, 'period_minutes': 60}
blocked = run(mon._maybe_silent_prompt(1, gamer, self.bot.db.get_gamer_status(gid),
self.bot.db.get_pair_check_state(1, gid), f"{gid}_1"))
self.assertTrue(blocked)
self.assertEqual(0, self.bot.db.get_user_gamers(1)[0]['period_minutes'])
self.assertIsNone(self.bot.db.get_pair_check_state(1, gid)['silent_prompt_at'])
self.assertEqual('blocked', self.periodic_events[-1][0])
def test_keep(self):
gid = add_player(self.bot, 1, 'Zhigalko_Sergei', 60)
run(self.bot.handle_silent_prompt(make_update(self.out, uid=1, callback=f'sl:keep:{gid}'), make_context()))
self.assertEqual(('edit', "✅ Оставил. Напишу, когда Zhigalko_Sergei сыграет."), self.out[0][:2])
self.assertAlmostEqual(time.time(), self.bot.db.get_pair_check_state(1, gid)['silent_prompt_at'], delta=5)
self.assertEqual({'uid': 1, 'gamer': 'Zhigalko_Sergei', 'result': 'keep'}, self.last_event('silent_prompt_result'))
self.assertEqual(1, len(self.bot.db.get_user_gamers(1)))
def test_delete(self):
gid = add_player(self.bot, 1, 'Zhigalko_Sergei', 60)
add_player(self.bot, 1, 'Other', 60)
run(self.bot.handle_silent_prompt(make_update(self.out, uid=1, callback=f'sl:del:{gid}'), make_context()))
self.assertEqual(('edit', "✅ Zhigalko_Sergei удалён"), self.out[0][:2])
self.assertEqual(['Other'], [g['username'] for g in self.bot.db.get_user_gamers(1)])
self.assertEqual([(gid, 1)], self.bot.monitor.stopped)
self.assertEqual({'uid': 1, 'gamer': 'Zhigalko_Sergei', 'result': 'delete'}, self.last_event('silent_prompt_result'))
self.assertEqual({'uid': 1, 'gamer': 'Zhigalko_Sergei', 'remaining': 1, 'via': 'silent_prompt'},
self.last_event('gamer_deleted'))
# pressed again: the pair (and the gamer row, nobody else tracks it) is
# gone; the name comes from the question's text, as Telegram shows it
question = "💤 Zhigalko_Sergei не заходил на\nLichess 30 дней."
self.out.clear()
run(self.bot.handle_silent_prompt(make_update(self.out, uid=1, text=question, callback=f'sl:del:{gid}'), make_context()))
self.assertEqual(('edit', "ℹ️ Zhigalko_Sergei уже не отслеживается"), self.out[0][:2])
self.assertEqual(['Other'], [g['username'] for g in self.bot.db.get_user_gamers(1)])
self.bot.db.set_user_language(1, 'en')
self.out.clear()
run(self.bot.handle_silent_prompt(make_update(self.out, uid=1, text=question, callback=f'sl:keep:{gid}'), make_context()))
self.assertEqual(('edit', "ℹ️ Zhigalko_Sergei is no longer tracked"), self.out[0][:2])
class TodayTests(ScreenTestCase):
NOACT = {'message': 'Активности за сегодняшний день не было', 'data': None}

View file

@ -21,7 +21,7 @@ class WiringTests(unittest.TestCase):
bot = LichessBot()
bot.setup_handlers(application)
# 1 conversation + 17 commands + name text + 11 callbacks + non-text + unknown command
self.assertEqual({-1: 1, 0: 30}, handler_groups(application))
self.assertEqual({-1: 1, 0: 29}, handler_groups(application))
self.assertIs(application, bot.monitor.application)
def test_admin_bot_handlers(self):