diff --git a/LichessClientTG_bot/admin_bot.py b/LichessClientTG_bot/admin_bot.py
index ae7b6aa..f8a2b97 100644
--- a/LichessClientTG_bot/admin_bot.py
+++ b/LichessClientTG_bot/admin_bot.py
@@ -3,6 +3,7 @@ Admin Panel Telegram Bot
Sends notifications about new users and new tracked players
"""
+import html
import logging
import sqlite3
import aiohttp
@@ -19,6 +20,7 @@ from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, DATABASE_PATH, TELEGRAM_BOT_TO
from database import Database
from message_counters import MessageCounters
from notifications import AdminNotifier
+from events import last_summary_line
# NOTE: no logging.basicConfig() at import time. This module is imported by bot.py,
# and a module-level basicConfig here used to win over bot.py's own one, silently
@@ -125,6 +127,11 @@ class AdminBot:
f"Сегодня отправлено: {stats['total_today']}\n\n"
f"По командам:\n{counters_text}"
)
+ # Last daily SUMMARY line from events.log (written by the bot at midnight), if any
+ summary_line = last_summary_line()
+ if summary_line:
+ summary_fields = summary_line.split(" SUMMARY ", 1)[1]
+ message += f"\n\n📅 Вчера: {html.escape(summary_fields)}"
await update.message.reply_text(message, parse_mode='HTML')
except Exception as e:
logger.error(f"Error getting status: {e}")
diff --git a/LichessClientTG_bot/bot.py b/LichessClientTG_bot/bot.py
index 28cc24f..48f7a3d 100644
--- a/LichessClientTG_bot/bot.py
+++ b/LichessClientTG_bot/bot.py
@@ -25,6 +25,7 @@ from message_counters import MessageCounters
from notifications import AdminNotifier
from onboarding import link_player
from periodic import PeriodicMonitor
+from events import event
import time
# Configure logging (level from LOG_LEVEL env, INFO by default)
@@ -86,6 +87,7 @@ class LichessBot:
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start command handler"""
logger.info(f"📝 start() method called for user {update.effective_user.id}")
+ event('cmd', uid=update.effective_user.id, name='start')
# Register user in database
user = update.effective_user
lang_code = user.language_code if user else None
@@ -97,6 +99,7 @@ class LichessBot:
last_name=user.last_name,
language_code=lang_code
)
+ event('user_start', uid=user.id, new=is_new_user, lang=self.db.get_user_language(user.id), tg_lang=lang_code)
# Notify admin bot about new user
if is_new_user:
try:
@@ -117,6 +120,7 @@ class LichessBot:
async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Help command handler"""
+ event('cmd', uid=update.effective_user.id, name='help')
lang = self.get_user_language_from_update(update)
help_msg = t('help_message', lang)
await update.message.reply_text(help_msg)
@@ -140,6 +144,11 @@ class LichessBot:
except:
pass
+ async def addgamer_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
+ """/addgamer entry point: the event line, then the shared menu (also shown by /start)."""
+ event('cmd', uid=update.effective_user.id, name='addgamer')
+ await self.addgamer_start(update, context)
+
async def addgamer_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start addgamer command - show menu with options"""
user_id = update.effective_user.id
@@ -299,10 +308,11 @@ class LichessBot:
async def addtoken_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start addtoken command - token required"""
+ event('cmd', uid=update.effective_user.id, name='addtoken')
# Reset any existing conversation state
if context and hasattr(context, "user_data"):
context.user_data.clear()
-
+
lang = self.get_user_language_from_update(update)
await update.message.reply_text(t('addtoken_prompt', lang))
self.counters.increment('addtoken')
@@ -329,6 +339,7 @@ class LichessBot:
if existing_gamer:
# Update token for existing gamer
self.db.add_user_gamer(user_id, existing_gamer['id'], token)
+ event('addtoken_result', uid=user_id, result='token_updated', canonical=username)
await update.message.reply_text(
t('token_added', lang, username=username)
)
@@ -340,24 +351,28 @@ class LichessBot:
logger.error(f"Admin notify failed after token update: {e}")
else:
# Add new gamer and link with token (shared with /addgamer, see onboarding.py)
- result = await link_player(self, user_id, update.effective_user, username, token)
+ result = await link_player(self, user_id, update.effective_user, username, token, via='addtoken')
if not result.added:
# Pair appeared between the check above and the insert; the token is stored
+ event('addtoken_result', uid=user_id, result='token_updated', canonical=username)
await update.message.reply_text(
t('token_added', lang, username=username)
)
else:
+ event('addtoken_result', uid=user_id, result='added', canonical=username)
await update.message.reply_text(
t('gamer_added_with_token', lang, username=username)
)
return ConversationHandler.END
else:
+ event('addtoken_result', uid=user_id, result='no_username')
lang = self.get_user_language_from_update(update)
await update.message.reply_text(
t('token_username_error', lang)
)
return WAITING_FOR_TOKEN
else:
+ event('addtoken_result', uid=user_id, result='invalid_token')
lang = self.get_user_language_from_update(update)
await update.message.reply_text(
t('invalid_token', lang)
@@ -376,20 +391,23 @@ class LichessBot:
await update.message.reply_text(t('text_not_expected', lang))
return
username = update.message.text.strip()
-
+ event('addgamer_input', uid=user_id, text=username)
+
lang = self.get_user_language_from_update(update)
if not username:
+ event('addgamer_result', uid=user_id, username=username, result='empty')
await update.message.reply_text(
t('empty_username', lang)
)
return
-
+
# Check if user exists on Lichess
logger.info(f"addgamer: user {user_id} entered username {username!r}")
lichess_user = await self.lichess_api.check_user_exists(username)
if lichess_user is None:
# Transient API failure (rate limit, network error, unexpected status) —
# don't tell the user the name is wrong, it may well be valid.
+ event('addgamer_result', uid=user_id, username=username, result='lichess_error')
await update.message.reply_text(
t('lichess_temporarily_unavailable', lang) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
@@ -397,6 +415,7 @@ class LichessBot:
return
if not lichess_user:
logger.info(f"addgamer: username {username!r} not found on Lichess (user {user_id})")
+ event('addgamer_result', uid=user_id, username=username, result='not_found')
await update.message.reply_text(
t('user_not_found', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
@@ -406,33 +425,37 @@ class LichessBot:
# Lichess answers 200 for closed accounts too; they never have new games,
# tracking one is just a wasted request every period.
logger.info(f"addgamer: username {username!r} is a closed Lichess account (user {user_id})")
+ event('addgamer_result', uid=user_id, username=username, result='closed')
await update.message.reply_text(
t('user_closed', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
return
# Store the canonical spelling Lichess uses, not whatever case the user typed
+ typed_username = username
username = lichess_user['username']
-
+
# Check if this gamer is already tracked by this user
user_gamers = self.db.get_user_gamers(user_id)
existing_gamer = next((g for g in user_gamers if g['username'].lower() == username.lower()), None)
-
+
if existing_gamer:
# Player is already being tracked by this user
+ event('addgamer_result', uid=user_id, username=typed_username, result='already', canonical=username)
await update.message.reply_text(
t('gamer_already_added', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
# Keep awaiting flag - don't clear it, so user can try again
return
-
+
# Add gamer to database (without token) and link it to this user
# (shared with /addtoken, see onboarding.py)
- result = await link_player(self, user_id, update.effective_user, username, None)
+ result = await link_player(self, user_id, update.effective_user, username, None, via='addgamer')
# If add_user_gamer returned False, it means the pair already exists (shouldn't happen after our check, but just in case)
if not result.added:
+ event('addgamer_result', uid=user_id, username=typed_username, result='already', canonical=username)
await update.message.reply_text(
t('gamer_already_added', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
@@ -440,6 +463,7 @@ class LichessBot:
# Keep awaiting flag - don't clear it, so user can try again
return
+ event('addgamer_result', uid=user_id, username=typed_username, result='added', canonical=username)
lang = self.get_user_language_from_update(update)
await update.message.reply_text(
t('gamer_added', lang, username=username),
@@ -455,8 +479,9 @@ class LichessBot:
async def getgamers(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Get all gamers for the current user and allow selection"""
user_id = update.effective_user.id
+ event('cmd', uid=user_id, name='getgamers')
gamers = self.db.get_user_gamers(user_id)
-
+
logger.info(f"getgamers: user_id={user_id}, found {len(gamers)} gamers")
lang = self.get_user_language_from_update(update)
@@ -600,6 +625,7 @@ class LichessBot:
async def delgamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show gamers list for deletion"""
user_id = update.effective_user.id
+ event('cmd', uid=user_id, name='delgamer')
gamers = self.db.get_user_gamers(user_id)
lang = self.get_user_language_from_update(update)
@@ -707,7 +733,8 @@ class LichessBot:
# Check how many gamers remain after deletion
remaining_gamers = self.db.get_user_gamers(user_id)
remaining_count = len(remaining_gamers)
-
+ event('gamer_deleted', uid=user_id, gamer=username, remaining=remaining_count)
+
# Determine which message to show
if remaining_count == 0:
# Last gamer deleted
@@ -882,18 +909,22 @@ class LichessBot:
async def today(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Today command"""
+ event('cmd', uid=update.effective_user.id, name='today')
await self.get_stats(update, context, "today")
-
+
async def yesterday(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Yesterday command"""
+ event('cmd', uid=update.effective_user.id, name='yesterday')
await self.get_stats(update, context, "yesterday")
-
+
async def week(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Week command"""
+ event('cmd', uid=update.effective_user.id, name='week')
await self.get_stats(update, context, "week")
-
+
async def support(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Support command - show contact information"""
+ event('cmd', uid=update.effective_user.id, name='support')
lang = self.get_user_language_from_update(update)
support_msg = t('support_message', lang, version=BOT_VERSION)
await update.message.reply_text(support_msg, parse_mode='HTML')
@@ -902,7 +933,8 @@ class LichessBot:
async def last_year_or_1000games(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Get last year stats or last 1000 rated games for all players with activity"""
user_id = update.effective_user.id
-
+ event('cmd', uid=user_id, name='lastyear')
+
# Get all gamers for this user
gamers = self.db.get_user_gamers(user_id)
@@ -969,7 +1001,8 @@ class LichessBot:
async def setperiod(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Set period command - first select gamer, then select period"""
user_id = update.effective_user.id
-
+ event('cmd', uid=user_id, name='setperiod')
+
# Get all gamers for this user
gamers = self.db.get_user_gamers(user_id)
@@ -1105,6 +1138,7 @@ class LichessBot:
# Set period for this user-gamer pair
self.db.set_user_gamer_period(user_id, gamer_id, period)
+ event('period_set', uid=user_id, gamer=selected_gamer['username'], minutes=period)
if period == 0:
# Отключаем мониторинг: чистим чекпоинт, чтобы при повторном включении
@@ -1128,7 +1162,8 @@ class LichessBot:
if not user:
await update.message.reply_text("❌ Failed to get user information")
return
-
+ event('cmd', uid=user.id, name='set_lang')
+
# Get current language to show menu in user's language
lang = self.get_user_language_from_update(update)
@@ -1167,8 +1202,9 @@ class LichessBot:
# Save selected language to database
success = self.db.set_user_language(user_id, selected_lang)
-
+
if success:
+ event('lang_set', uid=user_id, lang=selected_lang)
# Get message in selected language
message = t('language_set_ru', selected_lang) if selected_lang == 'ru' else t('language_set_en', selected_lang)
await query.edit_message_text(message)
@@ -1181,6 +1217,7 @@ class LichessBot:
async def profile(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show list of players to view their profiles"""
user_id = update.effective_user.id
+ event('cmd', uid=user_id, name='profile')
gamers = self.db.get_user_gamers(user_id)
lang = self.get_user_language_from_update(update)
@@ -1248,14 +1285,20 @@ class LichessBot:
uid = user.id if user else None
if update.callback_query:
logger.info(f"⬅️ callback from user {uid}: {update.callback_query.data!r}")
+ event('callback', uid=uid, data=update.callback_query.data)
elif update.message:
msg = update.message
if msg.text is not None:
logger.info(f"⬅️ text from user {uid}: {msg.text[:80]!r}")
+ # Commands are recorded by their handlers ("cmd" lines); here only plain text.
+ if not msg.text.startswith('/'):
+ user_data = getattr(context, 'user_data', None) or {}
+ event('text', uid=uid, len=len(msg.text), in_flow=bool(user_data.get('awaiting_addgamer_username')))
else:
kind = next((k for k in ('photo', 'sticker', 'document', 'contact', 'voice', 'video', 'location')
if getattr(msg, k, None)), 'other')
logger.info(f"⬅️ non-text message ({kind}) from user {uid}")
+ event('non_text', uid=uid, kind=kind)
else:
logger.info(f"⬅️ update of another type from user {uid}")
@@ -1290,7 +1333,7 @@ class LichessBot:
# Add handlers - ConversationHandler must be before general MessageHandler
application.add_handler(CommandHandler("start", self.start_and_addgamer))
application.add_handler(CommandHandler("help", self.help_command))
- application.add_handler(CommandHandler("addgamer", self.addgamer_start))
+ application.add_handler(CommandHandler("addgamer", self.addgamer_command))
application.add_handler(addtoken_conv) # Add before general MessageHandler
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_username))
application.add_handler(CommandHandler("getgamers", self.getgamers))
@@ -1354,12 +1397,16 @@ def main():
# traceback.format_exc() here printed "NoneType: None": the error handler runs
# outside the except block, so the traceback has to come from context.error itself.
who = ""
+ uid = None
+ what = type(update).__name__
if isinstance(update, Update):
user = update.effective_user
+ uid = user.id if user else None
what = (update.message.text[:60] if update.message and update.message.text
else (update.callback_query.data if update.callback_query else type(update).__name__))
- who = f" (user {user.id if user else None}, update: {what!r})"
+ who = f" (user {uid}, update: {what!r})"
logger.error(f"Exception while handling an update{who}: {context.error!r}", exc_info=context.error)
+ event('tg_error', uid=uid, handler=what, error=repr(context.error)[:80])
application.add_error_handler(error_handler)
diff --git a/LichessClientTG_bot/events.py b/LichessClientTG_bot/events.py
new file mode 100644
index 0000000..799d590
--- /dev/null
+++ b/LichessClientTG_bot/events.py
@@ -0,0 +1,124 @@
+"""
+Structured event log: one compact, grep-able line per thing a user or the
+system did, kept apart from the noisy container log.
+
+File:
/events.log (i.e. the data volume, so it
+survives container recreation), rotated at 10 MB x 5 backups. Line format:
+
+ 2026-10-20T22:15:12Z EVT key=value key2=value2 ...
+ 2026-10-20T00:00:01Z SUMMARY date=2026-10-19 users=... checks=... ...
+
+Values: ints as-is, True/False as 1/0, None as "-", strings truncated to 80
+chars and repr-quoted when they contain a space or "=". Fields keep the order
+they were passed in, so a name's lines always look alike and `grep -c "EVT
+gamer_added"` / `grep "uid=12345"` answer the usual questions directly.
+
+Both the bot and the admin-bot process import this and may write to the SAME
+file (there is one data volume): that is acceptable here — the handler opens
+the file in append mode and lines are short (one write() each), so they
+interleave but never corrupt each other. Only the rotation itself can race
+(two processes rotating at the same instant); the admin bot writes a handful
+of lines a day, so it practically never triggers it.
+
+event() never raises: a logging failure must not break the handler that
+called it. The first failure is reported once to the normal logger.
+"""
+import logging
+import os
+import time
+from logging.handlers import RotatingFileHandler
+
+import config
+
+# NOT getLogger(__name__): this module is named "events", which is exactly the
+# dedicated file logger below; the warnings here must reach the container log.
+logger = logging.getLogger("bot.events")
+
+EVENTS_LOG_PATH = os.path.join(os.path.dirname(config.DATABASE_PATH), "events.log")
+MAX_BYTES = 10 * 1024 * 1024
+BACKUP_COUNT = 5
+MAX_STR_LEN = 80
+
+_events_logger = None
+_setup_failed_reported = False
+
+
+def _get_logger() -> logging.Logger:
+ """Lazily build the dedicated 'events' logger (propagate=False: not in the container log)."""
+ global _events_logger
+ if _events_logger is not None:
+ return _events_logger
+ lg = logging.getLogger("events")
+ lg.setLevel(logging.INFO)
+ lg.propagate = False
+ if not lg.handlers:
+ handler = RotatingFileHandler(EVENTS_LOG_PATH, maxBytes=MAX_BYTES, backupCount=BACKUP_COUNT, encoding="utf-8")
+ handler.setFormatter(logging.Formatter("%(message)s"))
+ lg.addHandler(handler)
+ _events_logger = lg
+ return lg
+
+
+def _fmt_value(value) -> str:
+ if value is None:
+ return "-"
+ if value is True:
+ return "1"
+ if value is False:
+ return "0"
+ if isinstance(value, int):
+ return str(value)
+ if isinstance(value, float):
+ return f"{value:.1f}"
+ s = str(value)
+ if len(s) > MAX_STR_LEN:
+ s = s[:MAX_STR_LEN]
+ if " " in s or "=" in s or s == "":
+ return repr(s)
+ return s
+
+
+def _format_line(kind: str, name: str, fields: dict) -> str:
+ ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ parts = [ts, kind]
+ if name:
+ parts.append(name)
+ for key, value in fields.items():
+ parts.append(f"{key}={_fmt_value(value)}")
+ return " ".join(parts)
+
+
+def _write(kind: str, name: str, fields: dict) -> None:
+ global _setup_failed_reported
+ try:
+ _get_logger().info(_format_line(kind, name, fields))
+ except Exception as e:
+ if not _setup_failed_reported:
+ _setup_failed_reported = True
+ logger.warning(f"events.log unavailable ({EVENTS_LOG_PATH}): {e!r}; events will be dropped")
+
+
+def event(name: str, /, **fields) -> None:
+ """Write one `EVT k=v ...` line. Never raises. `name` is positional-only so a field may also be called name= (e.g. cmd name=start)."""
+ _write("EVT", name, fields)
+
+
+def summary(**fields) -> None:
+ """Write one `SUMMARY k=v ...` line (daily totals, see periodic.daily_counter_reset_task). Never raises."""
+ _write("SUMMARY", "", fields)
+
+
+def last_summary_line() -> str:
+ """The last SUMMARY line of events.log (used by the admin bot's /status), or '' if none / no file."""
+ try:
+ if not os.path.exists(EVENTS_LOG_PATH):
+ return ""
+ last = ""
+ with open(EVENTS_LOG_PATH, "r", encoding="utf-8", errors="replace") as f:
+ for line in f:
+ if " SUMMARY " in line:
+ last = line.rstrip("\n")
+ return last
+ except Exception as e:
+ logger.warning(f"Could not read last SUMMARY from {EVENTS_LOG_PATH}: {e!r}")
+ return ""
diff --git a/LichessClientTG_bot/lichess_api.py b/LichessClientTG_bot/lichess_api.py
index cf8e0d9..cf86216 100644
--- a/LichessClientTG_bot/lichess_api.py
+++ b/LichessClientTG_bot/lichess_api.py
@@ -106,7 +106,7 @@ class LichessAPI:
logger.error(f"Error getting week stats: {e}")
return None
- async def get_games_period(self, username: str, since: int, until: int, rated_only: Optional[bool] = None, include_games: bool = False, priority: str = "background") -> Optional[Dict[str, Any]]:
+ async def get_games_period(self, username: str, since: int, until: int, rated_only: Optional[bool] = None, include_games: bool = False, priority: str = "background", by_finish: bool = False) -> Optional[Dict[str, Any]]:
"""
Get games for a specific period.
@@ -114,6 +114,12 @@ class LichessAPI:
/week) jumps ahead of "background" (periodic_check) in the stats
service's shared Lichess-token queue, so an on-demand command doesn't
wait behind the whole periodic-check backlog.
+
+ by_finish=True selects games by the time they FINISHED (lastMoveAt in
+ (since, until]) instead of by creation time, which is what Lichess's own
+ since/until filter uses; see the stats service for the semantics.
+ periodic_check uses it so that a game is reported in the window in
+ which it ended. Default False keeps creation-time semantics.
"""
try:
url = f"{self.stats_base_url}/games/{username}/period"
@@ -122,6 +128,8 @@ class LichessAPI:
params["rated_only"] = "true" if rated_only else "false"
if include_games:
params["include_games"] = "true"
+ if by_finish:
+ params["by_finish"] = "true"
logger.debug(f"🔍 LichessAPI.get_games_period: URL={url}, params={params}")
async with aiohttp.ClientSession() as session:
diff --git a/LichessClientTG_bot/notifications.py b/LichessClientTG_bot/notifications.py
index edeee4b..b1b2491 100644
--- a/LichessClientTG_bot/notifications.py
+++ b/LichessClientTG_bot/notifications.py
@@ -14,6 +14,7 @@ import aiohttp
from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, TTS_URL
from database import Database
+from events import event
logger = logging.getLogger(__name__)
@@ -22,13 +23,19 @@ class AdminNotifier:
def __init__(self, db: Database):
self.db = db
- async def _send(self, text_html: str) -> None:
- """Post one HTML message to the admin chat via the Telegram Bot API. Never raises."""
+ async def _send(self, text_html: str, kind: str = 'other') -> bool:
+ """
+ Post one HTML message to the admin chat via the Telegram Bot API. Never
+ raises; returns True when Telegram accepted it. `kind` only labels the
+ `admin_notify` event line.
+ """
+ ok = False
try:
admin_chat_id = self.db.get_admin_chat_id()
if not admin_chat_id:
logger.warning("Admin chat id is not set; cannot send admin notification.")
- return
+ event('admin_notify', kind=kind, ok=False)
+ return False
url = f"https://api.telegram.org/bot{ADMINPANEL_TELEGRAM_BOT_TOKEN}/sendMessage"
logger.info(f"Sending admin notification via direct API to chat_id={admin_chat_id}")
async with aiohttp.ClientSession() as session:
@@ -39,11 +46,14 @@ class AdminNotifier:
}, timeout=aiohttp.ClientTimeout(total=10)) as response:
if response.status == 200:
logger.info("Admin notification sent successfully via direct API")
+ ok = True
else:
error_text = await response.text()
logger.error(f"Failed to send admin notification: {response.status} - {error_text}")
except Exception as e:
logger.error(f"Failed to send admin notification via API: {e}")
+ event('admin_notify', kind=kind, ok=ok)
+ return ok
async def _call_tts_service(self, text: str):
"""Call the optional TTS announcer (config.TTS_URL); no-op when it is not configured."""
@@ -73,7 +83,7 @@ class AdminNotifier:
f"Username: {username_text}\n"
f"Имя: {name_text}"
)
- await self._send(message)
+ await self._send(message, kind='new_user')
# Call TTS service with user count
try:
@@ -92,7 +102,7 @@ class AdminNotifier:
f"Игрок: {player_username}\n"
f"Добавил: {added_by_text}"
)
- await self._send(message)
+ await self._send(message, kind='new_player')
# Call TTS service if this is a new gamer
if is_new_gamer:
@@ -119,4 +129,4 @@ class AdminNotifier:
f"Подряд идущих ошибок: {consecutive_errors} (~{hours:.1f} ч)\n\n"
f"Проверьте токен игрока или доступность Lichess API."
)
- await self._send(message)
+ await self._send(message, kind='check_failing')
diff --git a/LichessClientTG_bot/onboarding.py b/LichessClientTG_bot/onboarding.py
index 4196f48..ca1107e 100644
--- a/LichessClientTG_bot/onboarding.py
+++ b/LichessClientTG_bot/onboarding.py
@@ -11,6 +11,8 @@ import traceback
from dataclasses import dataclass
from typing import Optional
+from events import event
+
logger = logging.getLogger(__name__)
# Every newly linked player starts with hourly periodic notifications.
@@ -24,14 +26,15 @@ class LinkResult:
added: bool # False when the (user, gamer) pair already existed
-async def link_player(bot, user_id: int, tg_user, username: str, token: Optional[str]) -> LinkResult:
+async def link_player(bot, user_id: int, tg_user, username: str, token: Optional[str], via: str = 'addgamer') -> LinkResult:
"""
Add `username` to the global gamers table (if new), link it to `user_id`
(with `token`, may be None), give the pair the default period, start its
periodic task and notify the admin.
`bot` is the LichessBot (uses bot.db, bot.counters, bot.monitor,
- bot.notifier); `tg_user` is update.effective_user (may be None).
+ bot.notifier); `tg_user` is update.effective_user (may be None); `via` is
+ the command that got here ('addgamer' | 'addtoken'), for the event log only.
When the returned `added` is False the pair already existed (callers check
first, so only a race gets here); `add_user_gamer` has then only refreshed
@@ -49,6 +52,7 @@ async def link_player(bot, user_id: int, tg_user, username: str, token: Optional
db.set_user_gamer_period(user_id, gamer_id, DEFAULT_PERIOD_MINUTES)
bot.counters.increment('gamer_added')
logger.info(f"addgamer: player {username} added for user {user_id} (new_gamer={is_new_gamer})")
+ event('gamer_added', uid=user_id, gamer=username, gamer_id=gamer_id, new_gamer=is_new_gamer, via=via)
# If this is the first gamer for this user, make it active
user_gamers = db.get_user_gamers(user_id)
diff --git a/LichessClientTG_bot/periodic.py b/LichessClientTG_bot/periodic.py
index 88ef2b4..86aae5f 100644
--- a/LichessClientTG_bot/periodic.py
+++ b/LichessClientTG_bot/periodic.py
@@ -19,6 +19,7 @@ import asyncio
import logging
import time
import zlib
+from collections import Counter
from datetime import datetime, timedelta
from typing import Dict, Any
@@ -32,6 +33,7 @@ from i18n import t
from message_counters import MessageCounters
from notifications import AdminNotifier
from player_status import PlayerStatusRefresher
+from events import event, summary
logger = logging.getLogger(__name__)
@@ -52,6 +54,11 @@ class PeriodicMonitor:
# tasks start and then forever alongside them. None disables it (tests).
self.status_refresher = PlayerStatusRefresher(db, lichess_api)
self._status_refresh_task = None
+ # In-memory daily totals for the SUMMARY line written at midnight
+ # (daily_counter_reset_task): 'checks' = windows that made a games
+ # request, 'skipped' = windows skipped on bulk status, 'notifications',
+ # 'errors' (failed iterations). Lost on restart, which is acceptable.
+ self.stats = Counter()
async def start_periodic_task(self, gamer: Dict[str, Any], user_id: int, period_minutes: int):
"""Start periodic task for a gamer"""
@@ -180,6 +187,21 @@ class PeriodicMonitor:
covered_until = datetime.fromtimestamp(status['checked_at'] - cls.STATUS_SAFETY_MARGIN_SECONDS)
return min(period_end_approx, covered_until)
+ def _stop_pair_blocked(self, user_id: int, gamer: Dict[str, Any], task_key: str) -> None:
+ """
+ telegram.error.Forbidden: the user blocked the bot. Permanent, not worth
+ retrying: disable the pair's period and drop its task (the caller then
+ returns from periodic_check). Without this, consecutive_errors gets reset
+ to 0 right before the send, so the outer handler's backoff never grows
+ past 60s and the pair retries forever, wasting queue capacity that other
+ users' real checks need.
+ """
+ logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {gamer['username']}")
+ event('blocked', uid=user_id, gamer=gamer['username'])
+ self.db.set_user_gamer_period(user_id, gamer['id'], 0)
+ self.periodic_tasks.pop(task_key, None)
+ self.period_start_times.pop(task_key, None)
+
async def periodic_check(self, gamer: Dict[str, Any], user_id: int, period_minutes: int):
"""Periodic check for gamer activity"""
task_key = f"{gamer['id']}_{user_id}"
@@ -297,10 +319,35 @@ class PeriodicMonitor:
# proves that without a games request.
status = self.db.get_gamer_status(gamer['id'])
pair_state = self.db.get_pair_check_state(user_id, gamer['id'])
+
+ # An account that was reported closed and now shows as active
+ # again: tell the owner once and clear the flag. Done BEFORE the
+ # decision: with an unchanged games total the pair keeps skipping,
+ # and if this lived on the 'request' path the owner would only
+ # hear about it after the player's next game (tester observation).
+ if pair_state['closed_notice_sent'] and status and not status.get('disabled'):
+ try:
+ user_lang = self.db.get_user_language(user_id)
+ await self.application.bot.send_message(
+ chat_id=user_id,
+ text=t('gamer_account_reopened', user_lang, username=username)
+ )
+ except Forbidden:
+ self._stop_pair_blocked(user_id, gamer, task_key)
+ return
+ except Exception as notify_err:
+ logger.error(f"Failed to notify user {user_id} that {username} is active again: {notify_err}")
+ else:
+ logger.info(f"✅ {username} is active again on Lichess; notifications resumed for user {user_id}")
+ event('reopened_notice', uid=user_id, gamer=username)
+ self.db.set_pair_closed_notice_sent(user_id, gamer['id'], False)
+ pair_state['closed_notice_sent'] = False
+
decision = self._decide_skip(
status, pair_state, time.time(), has_token=bool(gamer.get('token')),
since_ts=since_time.timestamp()
)
+ window_seconds = int((period_end_approx - since_time).total_seconds())
# Baseline candidate for this iteration, snapshotted NOW (before the
# games request) and stored only together with the checkpoint below.
# It is only valid if the status was refreshed no later than the
@@ -321,6 +368,10 @@ class PeriodicMonitor:
self.period_start_times[task_key] = skip_end
self.db.set_period_checkpoint(user_id, gamer['id'], int(skip_end.timestamp()))
consecutive_errors = 0
+ self.stats['skipped'] += 1
+ event('check', uid=user_id, gamer=username, decision=decision, window_s=window_seconds,
+ stale=is_stale_backlog, games=None, puzzles=None, notified=False,
+ lag_s=int((datetime.now() - period_end_approx).total_seconds()))
if decision == 'skip_unchanged':
logger.info(f"⏭️ Skipped check for {username} (user {user_id}): no new games since last check (total={status['games_total']})")
continue
@@ -334,39 +385,17 @@ class PeriodicMonitor:
)
except Forbidden:
# Same handling as the notification path below: permanent, stop the pair.
- logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {username}")
- self.db.set_user_gamer_period(user_id, gamer['id'], 0)
- self.periodic_tasks.pop(task_key, None)
- self.period_start_times.pop(task_key, None)
+ self._stop_pair_blocked(user_id, gamer, task_key)
return
except Exception as notify_err:
# Not marked as sent: try again at the next skipped check.
logger.error(f"Failed to notify user {user_id} that {username} is closed: {notify_err}")
else:
+ event('closed_notice', uid=user_id, gamer=username)
self.db.set_pair_closed_notice_sent(user_id, gamer['id'], True)
continue
- # 'request' path. An account that was reported closed and now shows
- # as active again: tell the owner once and clear the flag.
- if pair_state['closed_notice_sent'] and status and not status.get('disabled'):
- try:
- user_lang = self.db.get_user_language(user_id)
- await self.application.bot.send_message(
- chat_id=user_id,
- text=t('gamer_account_reopened', user_lang, username=username)
- )
- except Forbidden:
- logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {username}")
- self.db.set_user_gamer_period(user_id, gamer['id'], 0)
- self.periodic_tasks.pop(task_key, None)
- self.period_start_times.pop(task_key, None)
- return
- except Exception as notify_err:
- logger.error(f"Failed to notify user {user_id} that {username} is active again: {notify_err}")
- else:
- logger.info(f"✅ {username} is active again on Lichess; notifications resumed for user {user_id}")
- self.db.set_pair_closed_notice_sent(user_id, gamer['id'], False)
-
+ # 'request' path.
since_timestamp = int(since_time.timestamp() * 1000)
# Используем приблизительное время как until_timestamp
# После получения ответа пересчитаем фактическое время
@@ -383,11 +412,21 @@ class PeriodicMonitor:
# Запрос к локальному stats-сервису; очередь и пейсинг общего
# Lichess-токена — на его стороне (SharedTokenGate), здесь только
# ограничиваем число одновременно открытых соединений.
+ #
+ # by_finish=True: a game is reported in the window in which it
+ # FINISHED (lastMoveAt in (since, until]), not the one in which
+ # it was created. Lichess's own since/until filter by createdAt
+ # and omit games still in progress, so a game created at 14:58
+ # and finished at 15:06 was in neither the 14:00-15:00 window
+ # (still running when checked) nor the 15:00-16:00 one (created
+ # before 15:00). The service looks back a few hours before
+ # `since` and filters by finish time itself. Consistent with the
+ # bulk-status skip: games_total also grows at game end.
logger.debug(f"📥 Requesting games for {gamer['username']}")
async with self._request_slots:
games_data = await self.lichess_api.get_games_period(
gamer['username'], since_timestamp, until_timestamp_approx,
- include_games=True
+ include_games=True, by_finish=True
)
if games_data is None:
raise RuntimeError("Games period API returned no data")
@@ -397,6 +436,8 @@ class PeriodicMonitor:
except Exception as e:
logger.error(f"❌ Error getting games data for {gamer['username']}: {e}")
consecutive_errors += 1
+ self.stats['errors'] += 1
+ event('check_error', uid=user_id, gamer=username, error=repr(e)[:80], consecutive=consecutive_errors)
backoff_seconds = min(300, 60 * consecutive_errors)
if consecutive_errors >= max_consecutive_errors:
logger.error(f"⚠️ {consecutive_errors} consecutive errors for {gamer['username']}; still retrying the same period (backoff {backoff_seconds}s)")
@@ -426,6 +467,7 @@ class PeriodicMonitor:
)
except InvalidTokenError:
logger.warning(f"🔑 Token rejected by Lichess for {gamer['username']} (user {user_id}); disabling puzzle tracking for this pair")
+ event('token_rejected', uid=user_id, gamer=username)
self.db.clear_user_gamer_token(user_id, gamer['id'])
gamer['token'] = None
puzzles_data = None
@@ -505,6 +547,7 @@ class PeriodicMonitor:
# всплыть во внешний обработчик, чтобы чекпоинт не продвинулся и уже
# обнаруженная активность была отправлена повторно на следующей попытке,
# а не потеряна молча.
+ notified = False
if (has_games or has_puzzles) and not is_stale_backlog:
logger.info(f"📊 Activity detected for {gamer['username']}, preparing notification...")
user_lang = self.db.get_user_language(user_id)
@@ -520,11 +563,8 @@ class PeriodicMonitor:
if not self.application:
raise RuntimeError(f"Application not initialized, cannot send notification for {gamer['username']} to user {user_id}")
- # Forbidden (user blocked the bot) is permanent, not worth retrying:
- # without this, consecutive_errors gets reset to 0 above right before
- # this call succeeds/fails, so the outer handler's backoff never grows
- # past 60s and this pair retries forever, wasting queue capacity that
- # other users' real checks need.
+ # Forbidden (user blocked the bot) is permanent, not worth retrying
+ # (see _stop_pair_blocked).
try:
await self.application.bot.send_message(
chat_id=user_id,
@@ -532,16 +572,13 @@ class PeriodicMonitor:
parse_mode='Markdown'
)
except Forbidden:
- logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {gamer['username']}")
- self.db.set_user_gamer_period(user_id, gamer['id'], 0)
- if task_key in self.periodic_tasks:
- del self.periodic_tasks[task_key]
- if task_key in self.period_start_times:
- del self.period_start_times[task_key]
+ self._stop_pair_blocked(user_id, gamer, task_key)
return
logger.info(f"✅ Sent periodic notification for {gamer['username']} to user {user_id}")
# Increment periodic notification counter
self.counters.increment('periodic_notification')
+ self.stats['notifications'] += 1
+ notified = True
elif is_stale_backlog and (has_games or has_puzzles):
logger.info(f"⏭️ Suppressed stale backlog notification for {gamer['username']} (had activity, but window too old)")
else:
@@ -573,15 +610,22 @@ class PeriodicMonitor:
delay = (request_end_time - period_end_approx).total_seconds()
if delay > 0:
logger.debug(f"⏱️ Request completed with {delay:.1f}s delay after planned period end")
-
+ self.stats['checks'] += 1
+ event('check', uid=user_id, gamer=username, decision='request', window_s=window_seconds,
+ stale=is_stale_backlog, games=total_games,
+ puzzles=total_puzzles if puzzles_data is not None else None, notified=notified,
+ lag_s=int((datetime.now() - period_end_approx).total_seconds()))
+
except asyncio.CancelledError:
logger.info(f"Periodic check cancelled for {gamer['username']}")
break
except Exception as e:
consecutive_errors += 1
+ self.stats['errors'] += 1
logger.error(f"Error in periodic check for {gamer['username']}: {e}")
import traceback
logger.error(f"Full traceback: {traceback.format_exc()}")
+ event('check_error', uid=user_id, gamer=username, error=repr(e)[:80], consecutive=consecutive_errors)
# Не убиваем задачу навсегда: ретраим то же окно с растущим бэкоффом
# (капается на 300с), пока Lichess/Telegram не восстановятся.
@@ -652,6 +696,24 @@ class PeriodicMonitor:
import traceback
logger.error(traceback.format_exc())
+ def write_daily_summary(self, for_date=None):
+ """
+ One SUMMARY line for the day that just ended (default: yesterday) from
+ self.stats and the DB counts, then reset self.stats. lichess_429 is only
+ known inside the stats service (its own events go to its container log),
+ so it is written as '-'. Never raises.
+ """
+ try:
+ day = for_date or (datetime.now() - timedelta(days=1)).date()
+ counts = self.db.get_counts()
+ pairs_active = sum(1 for g in self.db.get_all_gamers_with_periods() if g['period_minutes'] > 0)
+ summary(date=day.isoformat(), users=counts['users'], gamers=counts['gamers'], pairs_active=pairs_active,
+ checks=self.stats['checks'], skipped=self.stats['skipped'],
+ notifications=self.stats['notifications'], lichess_429=None, errors=self.stats['errors'])
+ except Exception as e:
+ logger.error(f"Failed to write daily summary: {e}")
+ self.stats = Counter()
+
async def daily_counter_reset_task(self):
"""Background task to reset daily counters at midnight"""
while True:
@@ -663,7 +725,10 @@ class PeriodicMonitor:
logger.info(f"Daily counter reset task: waiting {seconds_until_midnight} seconds until next midnight")
await asyncio.sleep(seconds_until_midnight)
-
+
+ # Daily SUMMARY line to events.log before the counters go (see events.py)
+ self.write_daily_summary()
+
# Reset daily counters
self.counters._reset_daily_counters_if_needed()
logger.info("Daily counters reset at midnight")
diff --git a/LichessClientTG_bot/player_status.py b/LichessClientTG_bot/player_status.py
index a43213a..8ba56e7 100644
--- a/LichessClientTG_bot/player_status.py
+++ b/LichessClientTG_bot/player_status.py
@@ -24,6 +24,7 @@ import time
import config
from database import Database
from lichess_api import LichessAPI
+from events import event
logger = logging.getLogger(__name__)
@@ -46,6 +47,7 @@ class PlayerStatusRefresher:
tracked = self.db.get_all_tracked_gamers()
if not tracked:
logger.info("🩺 Player status refresh: 0 tracked, nothing to do")
+ event('status_refresh', tracked=0, answered=0, closed=0, took_s=0.0, ok=True)
return {'tracked': 0, 'answered': 0, 'closed': 0, 'seconds': 0.0}
# Lichess answers with the canonical spelling; match on the lowercase id,
@@ -57,6 +59,8 @@ class PlayerStatusRefresher:
chunk = tracked[start:start + BULK_CHUNK_SIZE]
players = await self.lichess_api.get_users_status([g['username'] for g in chunk])
if players is None:
+ event('status_refresh', tracked=len(tracked), answered=len(rows), closed=closed,
+ took_s=time.monotonic() - started, ok=False)
raise RuntimeError(f"users/status returned no data for chunk {start // BULK_CHUNK_SIZE + 1}")
# checked_at is taken after the answer arrives, per chunk: it must not be
# newer than the data it describes.
@@ -80,6 +84,7 @@ class PlayerStatusRefresher:
f"🩺 Player status refresh: {len(tracked)} tracked, {len(rows)} answered, "
f"{closed} closed, took {seconds:.1f}s"
)
+ event('status_refresh', tracked=len(tracked), answered=len(rows), closed=closed, took_s=seconds, ok=True)
return {'tracked': len(tracked), 'answered': len(rows), 'closed': closed, 'seconds': seconds}
async def run_forever(self):
diff --git a/LichessWebServices/API_DOCUMENTATION.md b/LichessWebServices/API_DOCUMENTATION.md
index 754ba64..bb759ff 100644
--- a/LichessWebServices/API_DOCUMENTATION.md
+++ b/LichessWebServices/API_DOCUMENTATION.md
@@ -151,6 +151,7 @@ curl http://localhost:8001/stats/magnus/week
- `since` (integer, обязательный) - начало периода (Unix timestamp в миллисекундах)
- `until` (integer, обязательный) - конец периода (Unix timestamp в миллисекундах)
- `rated_only` (boolean, опциональный) - только рейтинговые игры (по умолчанию true - рекомендуется)
+- `by_finish` (boolean, опциональный, по умолчанию false) - относить партию к периоду по моменту её **окончания** (`lastMoveAt` в `(since, until]`), а не создания, как фильтрует сам Lichess; запрос к Lichess при этом расширяется на 3 часа назад. Так работают периодические проверки бота: партия попадает в то окно, в котором закончилась
**Пример запроса:**
```bash
diff --git a/LichessWebServices/events.py b/LichessWebServices/events.py
new file mode 100644
index 0000000..13a233d
--- /dev/null
+++ b/LichessWebServices/events.py
@@ -0,0 +1,46 @@
+"""
+Structured event lines for the stats service, same format as the bot's
+events.py (LichessClientTG_bot/events.py):
+
+ 2026-10-20T22:15:12Z EVT lichess_429 endpoint=games kind=burst user=Magnus
+
+The service has no data volume, so instead of a file the lines go to the
+stdout logger "events" at INFO (i.e. into the container log), where they are
+still grep-able: `docker logs lichess-api 2>&1 | grep "EVT lichess_429"`.
+Values: ints as-is, True/False as 1/0, None as "-", strings truncated to 80
+chars and repr-quoted when they contain a space or "=". event() never raises.
+"""
+import logging
+import time
+
+_events_logger = logging.getLogger("events")
+MAX_STR_LEN = 80
+
+
+def _fmt_value(value) -> str:
+ if value is None:
+ return "-"
+ if value is True:
+ return "1"
+ if value is False:
+ return "0"
+ if isinstance(value, int):
+ return str(value)
+ if isinstance(value, float):
+ return f"{value:.1f}"
+ s = str(value)
+ if len(s) > MAX_STR_LEN:
+ s = s[:MAX_STR_LEN]
+ if " " in s or "=" in s or s == "":
+ return repr(s)
+ return s
+
+
+def event(name: str, /, **fields) -> None:
+ """Write one `EVT k=v ...` line to the container log. Never raises. `name` is positional-only so a field may also be called name=."""
+ try:
+ ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ parts = [ts, "EVT", name] + [f"{k}={_fmt_value(v)}" for k, v in fields.items()]
+ _events_logger.info(" ".join(parts))
+ except Exception:
+ pass
diff --git a/LichessWebServices/lichess_client.py b/LichessWebServices/lichess_client.py
index 7efcc2b..8caa7fa 100644
--- a/LichessWebServices/lichess_client.py
+++ b/LichessWebServices/lichess_client.py
@@ -20,6 +20,7 @@ from datetime import datetime, timedelta
import logging
import json
from rate_limiter import get_rate_limiter, get_shared_token_gate
+from events import event
# Настройка логирования для модуля
logger = logging.getLogger(__name__)
@@ -59,7 +60,7 @@ class LichessClient:
if not self.app_token:
logger.warning("LICHESS_APP_TOKEN не задан — анонимные запросы к games/user и user/activity будут получать 404 от Lichess")
- def _handle_429(self, username: str, response: httpx.Response) -> None:
+ def _handle_429(self, username: str, response: httpx.Response, endpoint: str = "unknown") -> None:
"""
Разбирает 429 от lichess.org, чтобы в логах было видно, КАКОЙ из двух
лимитеров сработал (см. docstring SharedTokenGate в rate_limiter.py):
@@ -71,7 +72,8 @@ class LichessClient:
токеном — gate.pause(60).
Вызывается ТОЛЬКО после release() гейта (из except вне try/finally),
иначе pause() + удержание гейта = дедлок. Исключение не глотает —
- вызывающий код пробрасывает его как и раньше.
+ вызывающий код пробрасывает его как и раньше. `endpoint`
+ (games|activity|users) — только для строки события lichess_429.
"""
body = (response.text or "").strip().replace("\n", " ")[:120]
logger.warning(f"429 from lichess.org for {username}: body={body!r}")
@@ -80,8 +82,11 @@ class LichessClient:
f"429 for {username} is the concurrency limiter (slots held by another "
f"process using the same token/IP); request spacing won't help, not pausing the gate"
)
+ event('lichess_429', endpoint=endpoint, kind='concurrency', user=username)
return
+ kind = 'burst' if 'Too many requests' in body or 'too many requests' in body.lower() else 'unknown'
logger.warning(f"429 for {username} is the burst limiter (or unknown): pausing all shared-token calls for 60s")
+ event('lichess_429', endpoint=endpoint, kind=kind, user=username)
self.shared_token_gate.pause(60)
async def get_user_activity(self, username: str) -> Optional[List[Dict[str, Any]]]:
@@ -131,11 +136,14 @@ class LichessClient:
if e.response.status_code == 404:
# Пользователь не найден - это нормальная ситуация
logger.warning(f"⚠️ Пользователь {username} не найден (404)")
+ event('lichess_error', endpoint='activity', status=404, user=username)
return None
else:
if e.response.status_code == 429:
# Гейт уже отпущен (finally выше) — pause() здесь безопасен
- self._handle_429(username, e.response)
+ self._handle_429(username, e.response, endpoint='activity')
+ else:
+ event('lichess_error', endpoint='activity', status=e.response.status_code, user=username)
# Другие HTTP ошибки - логируем и пробрасываем
logger.error(f"❌ HTTP ошибка при получении активности пользователя {username}: status={e.response.status_code}, error={e}")
raise
@@ -234,11 +242,14 @@ class LichessClient:
if e.response.status_code == 404:
# Пользователь не найден - это нормальная ситуация
logger.warning(f"Пользователь {username} не найден")
+ event('lichess_error', endpoint='games', status=404, user=username)
return None
else:
if e.response.status_code == 429:
# Гейт уже отпущен (finally выше) — pause() здесь безопасен
- self._handle_429(username, e.response)
+ self._handle_429(username, e.response, endpoint='games')
+ else:
+ event('lichess_error', endpoint='games', status=e.response.status_code, user=username)
# Другие HTTP ошибки - логируем и пробрасываем
logger.error(f"HTTP ошибка при получении игр пользователя {username}: {e}")
raise
@@ -311,7 +322,9 @@ class LichessClient:
except httpx.HTTPStatusError as e:
if e.response.status_code == 429:
# Гейт уже отпущен (finally выше) — pause() здесь безопасен
- self._handle_429("", e.response)
+ self._handle_429("", e.response, endpoint='users')
+ else:
+ event('lichess_error', endpoint='users', status=e.response.status_code, user='')
logger.error(f"HTTP ошибка при bulk-запросе статуса пользователей: {e}")
raise
except Exception as e:
diff --git a/LichessWebServices/main.py b/LichessWebServices/main.py
index e2b58c3..c311280 100644
--- a/LichessWebServices/main.py
+++ b/LichessWebServices/main.py
@@ -514,7 +514,10 @@ async def get_games_of_period(
priority: str = Query("background",
pattern="^(background|interactive)$",
description="\"interactive\" (запросы из /today и т.п.) обгоняет \"background\" (периодические проверки) в общей очереди shared-token запросов к Lichess",
- example="background")
+ example="background"),
+ by_finish: bool = Query(False,
+ description="Относить партию к периоду по моменту её окончания (lastMoveAt в (since, until]), а не по моменту создания; запрос к Lichess расширяется назад на 3 ч. Используют периодические проверки бота",
+ example=False)
):
"""
## Статистика игр за период
@@ -535,7 +538,8 @@ async def get_games_of_period(
- **since**: Начало периода в Unix timestamp (миллисекунды) (обязательно)
- **until**: Конец периода в Unix timestamp (миллисекунды) (обязательно)
- **rated_only**: Только рейтинговые игры (по умолчанию true - рекомендуется)
-
+ - **by_finish**: Относить партию к периоду по моменту окончания, а не создания (по умолчанию false)
+
### Примеры использования:
- Статистика за последние 7 дней: `since=1640995200000&until=1641081600000` (по умолчанию только рейтинговые)
- Только рейтинговые игры: `rated_only=true` (рекомендуется)
@@ -568,7 +572,7 @@ async def get_games_of_period(
# Конвертируем миллисекунды в секунды для внутренней логики
since_seconds = since // 1000
until_seconds = until // 1000
- result = await stats_service.get_games_of_period(username, since_seconds, until_seconds, rated_only, include_games, priority=priority)
+ result = await stats_service.get_games_of_period(username, since_seconds, until_seconds, rated_only, include_games, priority=priority, by_finish=by_finish)
if not result.success:
# Реальная ошибка при обращении к Lichess — не маскируем её под "0 игр"
raise HTTPException(status_code=502, detail=result.message)
diff --git a/LichessWebServices/stats_service.py b/LichessWebServices/stats_service.py
index 59b6fc3..e23c474 100644
--- a/LichessWebServices/stats_service.py
+++ b/LichessWebServices/stats_service.py
@@ -22,6 +22,17 @@ import logging
# Настройка логирования для модуля
logger = logging.getLogger(__name__)
+# get_games_of_period(by_finish=True): на сколько раньше `since` спрашивать
+# Lichess. Его since/until фильтруют по createdAt, а партии в процессе он не
+# отдаёт вовсе, поэтому партия, начатая в 14:58 и законченная в 15:06, не
+# попадала ни в окно 14:00–15:00 (ещё шла), ни в окно 15:00–16:00 (создана
+# раньше). С by_finish окно считается по lastMoveAt (моменту окончания), а
+# запрос к Lichess расширяется назад на этот запас, чтобы захватить партии,
+# начатые до `since`. 3 часа покрывают любую партию в реальном времени
+# (classical с инкрементом редко длится больше 2–3 ч); заочные
+# (correspondence) партии не ловятся ни так, ни иначе — они могут идти днями.
+FINISH_LOOKBACK_SECONDS = 3 * 3600
+
class StatsService:
"""
Сервис для обработки и агрегации статистики Lichess.
@@ -698,7 +709,23 @@ class StatsService:
total=create_game_stats(stats['total'])
)
- async def get_games_of_period(self, username: str, since_timestamp: int, until_timestamp: int, rated_only: bool = True, include_games: bool = False, priority: str = "background") -> GamesOfPeriodResponse:
+ @staticmethod
+ def _finished_in(games: List[Dict[str, Any]], since_ms: int, until_ms: int) -> List[Dict[str, Any]]:
+ """
+ Партии, закончившиеся в (since_ms, until_ms]: по lastMoveAt (мс), а при
+ его отсутствии — по createdAt. Полуинтервал открыт слева, чтобы стыкующиеся
+ окна периодических проверок не считали одну партию дважды.
+ """
+ kept = []
+ for g in games:
+ finished = g.get('lastMoveAt')
+ if not isinstance(finished, int):
+ finished = g.get('createdAt')
+ if isinstance(finished, int) and since_ms < finished <= until_ms:
+ kept.append(g)
+ return kept
+
+ async def get_games_of_period(self, username: str, since_timestamp: int, until_timestamp: int, rated_only: bool = True, include_games: bool = False, priority: str = "background", by_finish: bool = False) -> GamesOfPeriodResponse:
"""
Получает статистику игр пользователя за определенный период.
@@ -713,6 +740,12 @@ class StatsService:
include_games: Включить построчный список отдельных партий (только blitz/rapid/classical)
priority: "interactive" для запросов из /today и т.п. (обгоняют фоновые
периодические проверки в общей очереди shared_token_gate), иначе "background"
+ by_finish: считать партию принадлежащей периоду по моменту ОКОНЧАНИЯ
+ (lastMoveAt в (since, until]), а не по моменту создания, как фильтрует
+ сам Lichess. Запрос к Lichess при этом делается с
+ since − FINISH_LOOKBACK_SECONDS (см. комментарий к константе), а
+ отбор по окну — здесь. По умолчанию False — прежнее поведение
+ (/today, /yesterday, /week, /lastYear).
Returns:
GamesOfPeriodResponse с статистикой игр
@@ -723,8 +756,9 @@ class StatsService:
until_ms = until_timestamp * 1000
# Получаем игры (без фильтра rated в запросе к Lichess — см. lichess_client)
- games = await self.lichess_client.get_games_of_period(username, since_ms, until_ms, rated_only=False, priority=priority)
-
+ lichess_since_ms = since_ms - FINISH_LOOKBACK_SECONDS * 1000 if by_finish else since_ms
+ games = await self.lichess_client.get_games_of_period(username, lichess_since_ms, until_ms, rated_only=False, priority=priority)
+
if games is None:
return GamesOfPeriodResponse(
message=f"Пользователь {username} не найден",
@@ -733,7 +767,15 @@ class StatsService:
period_end=until_timestamp,
games_count=0
)
-
+
+ # by_finish: из расширенного назад списка оставляем только то, что
+ # закончилось в окне; всё ниже (агрегация, games_count, earliest_game_ts,
+ # построчные ряды) работает уже с отфильтрованным списком.
+ if by_finish:
+ fetched = len(games)
+ games = self._finished_in(games, since_ms, until_ms)
+ logger.info(f"by_finish: {len(games)} of {fetched} fetched games for {username} finished in ({since_ms}, {until_ms}]")
+
# Фильтр по рейтинговости на нашей стороне (API Lichess с param rated даёт неверный результат)
if rated_only:
games = [g for g in games if g.get('rated') is True]
diff --git a/README.md b/README.md
index 9813486..77181a1 100644
--- a/README.md
+++ b/README.md
@@ -110,7 +110,7 @@ Telegram бот для управления отслеживанием игро
- Статистика за последний год или последние 1000 рейтинговых игр
- Статистика по режимам (Bullet, Blitz, Rapid, Classical, Correspondence)
- Статистика решения задач (puzzles)
-- Настройка периодических уведомлений с гибкими интервалами (15 минут - 24 часа)
+- Настройка периодических уведомлений с гибкими интервалами (15 минут - 24 часа). Партия засчитывается в то окно, в котором она **закончилась** (параметр `by_finish` у `GET /games/{username}/period`): партия, начатая в 14:58 и доигранная в 15:06, придёт в уведомлении за 15:00–16:00, а не потеряется между окнами
- Информативные сообщения о процессе обработки запросов
- Каждый пользователь имеет свой набор игроков
- Версионность бота (отображается в команде /support)
@@ -217,6 +217,34 @@ docker logs lichesswebservices_lichess-api_1 -f
docker logs lichess-telegram-bot -f
```
+### Журнал событий (`events.log`)
+
+Помимо контейнерного лога бот пишет компактный структурированный журнал событий — что сделали пользователи и система. Файл лежит рядом с базой: `LichessClientTG_bot/data/events.log` (на проде — в volume `data`, переживает пересоздание контейнера; ротация 10 МБ × 5). Пишут в него оба процесса (бот и админ-бот), модуль `LichessClientTG_bot/events.py`.
+
+Формат — одна строка на событие, UTC-время, имя события, поля `key=value` в фиксированном порядке (`-` = нет значения, строки с пробелами в кавычках):
+
+```
+2026-10-20T22:15:12Z EVT user_start uid=12345 new=1 lang=ru tg_lang=ru
+2026-10-20T22:15:40Z EVT addgamer_result uid=12345 username=magnus result=added canonical=Magnus
+2026-10-20T23:00:07Z EVT check uid=12345 gamer=Magnus decision=request window_s=3600 stale=0 games=2 puzzles=- notified=1 lag_s=7
+2026-10-21T00:00:00Z SUMMARY date=2026-10-20 users=900 gamers=700 pairs_active=450 checks=120 skipped=9800 notifications=60 lichess_429=- errors=3
+```
+
+События: `user_start`, `cmd`, `callback`, `text`, `non_text`, `addgamer_input`, `addgamer_result`, `addtoken_result`, `gamer_added`, `gamer_deleted`, `period_set`, `lang_set`, `check`, `check_error`, `closed_notice`, `reopened_notice`, `blocked`, `token_rejected`, `status_refresh`, `admin_notify`, `tg_error`. Строка `SUMMARY` пишется раз в сутки в полночь (`checks` — окна, по которым был запрос партий; `skipped` — окна, пропущенные по bulk-статусу). Stats-сервис пишет свои события (`lichess_429`, `lichess_error`) в том же формате в свой контейнерный лог.
+
+Примеры:
+
+```bash
+# Воронка: сколько запустили бота vs сколько добавили игрока
+grep -c "EVT user_start" data/events.log; grep -c "EVT gamer_added" data/events.log
+
+# Что происходило с пользователем 12345
+grep "uid=12345" data/events.log
+
+# Сколько 429 от Lichess за сегодня (лог stats-сервиса)
+docker logs lichess-api --since 24h 2>&1 | grep -c "EVT lichess_429"
+```
+
## 📝 Лицензия
MIT