From 30aaa34a33cac6f87418e7861c31c889f98ccae5 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 22:53:51 +0000 Subject: [PATCH] admin bot: /events [N] [filter] and /events_file to read events.log from Telegram Co-Authored-By: Claude Fable 5.1 --- LichessClientTG_bot/admin_bot.py | 55 ++++++++++++++++++++++++++++++-- LichessClientTG_bot/events.py | 20 ++++++++++++ README.md | 2 +- 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/LichessClientTG_bot/admin_bot.py b/LichessClientTG_bot/admin_bot.py index f8a2b97..e58cbac 100644 --- a/LichessClientTG_bot/admin_bot.py +++ b/LichessClientTG_bot/admin_bot.py @@ -20,7 +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 +from events import last_summary_line, tail_events, EVENTS_LOG_PATH # 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 @@ -324,6 +324,50 @@ class AdminBot: await update.message.reply_text("❌ Отправка сообщения отменена.") return ConversationHandler.END + async def events(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + """/events [N] [фильтр] — последние N строк events.log (по умолчанию 30, максимум 200), + при фильтре — только строки, содержащие его (например `/events 50 uid=12345`, + `/events 100 addgamer_result`, `/events 20 check_error`).""" + args = list(context.args or []) + limit = 30 + if args and args[0].isdigit(): + limit = max(1, min(200, int(args[0]))) + args = args[1:] + needle = " ".join(args).strip() or None + lines = tail_events(limit, needle) + if not lines: + await update.message.reply_text( + "📭 Журнал событий пуст" + (f" (фильтр: {needle})" if needle else "") + + f"\nФайл: {EVENTS_LOG_PATH}" + ) + return + # Короче: дата целиком не нужна на каждой строке, оставляем ЧЧ:ММ:СС, убираем " EVT " + shown = [] + for l in lines: + if len(l) > 20 and l[10] == "T" and l[19] == "Z": + l = l[11:19] + l[20:] + shown.append(l.replace(" EVT ", " ", 1)) + header = f"📜 Последние {len(shown)} событий" + (f" по фильтру «{needle}»" if needle else "") + ":\n" + chunk, size = [], 0 + for l in shown: + if size + len(l) + 1 > 3500: + await update.message.reply_text(header + "
" + html.escape("\n".join(chunk)) + "
", parse_mode='HTML') + header, chunk, size = "", [], 0 + chunk.append(l); size += len(l) + 1 + if chunk: + await update.message.reply_text(header + "
" + html.escape("\n".join(chunk)) + "
", parse_mode='HTML') + + async def events_file(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + """/events_file — прислать events.log целиком как документ.""" + try: + with open(EVENTS_LOG_PATH, "rb") as f: + await update.message.reply_document(document=f, filename="events.log") + except FileNotFoundError: + await update.message.reply_text(f"📭 Файл {EVENTS_LOG_PATH} ещё не создан") + except Exception as e: + logger.error(f"/events_file failed: {e!r}") + await update.message.reply_text(f"❌ Не удалось отправить файл: {e}") + async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Start command - register admin chat""" try: @@ -334,7 +378,10 @@ class AdminBot: "✅ Админ-панель активирована!\n\n" "Доступные команды:\n" "/status - Показать статистику\n" - "/system_mes - Отправить сообщение всем пользователям" + "/events [N] [фильтр] - Последние события из журнала (например /events 50 uid=123)\n" + "/events_file - Прислать events.log файлом\n" + "/system_mes - Отправить сообщение всем пользователям\n" + "/sendusers0 - Сообщение пользователям без игроков" ) except Exception as e: logger.error(f"Error in start command: {e}") @@ -381,6 +428,10 @@ class AdminBot: # Add status command handler application.add_handler(CommandHandler("status", self.status)) + # Event log viewers (see events.py) + application.add_handler(CommandHandler("events", self.events)) + application.add_handler(CommandHandler("events_file", self.events_file)) + def main(): """Main function""" diff --git a/LichessClientTG_bot/events.py b/LichessClientTG_bot/events.py index 799d590..f4ca365 100644 --- a/LichessClientTG_bot/events.py +++ b/LichessClientTG_bot/events.py @@ -25,6 +25,7 @@ called it. The first failure is reported once to the normal logger. """ import logging import os +from typing import Optional import time from logging.handlers import RotatingFileHandler @@ -108,6 +109,25 @@ def summary(**fields) -> None: _write("SUMMARY", "", fields) +def tail_events(limit: int = 30, needle: Optional[str] = None) -> list: + """Last `limit` lines of events.log (optionally only those containing `needle`, + case-insensitive), oldest first. Used by the admin bot's /events. Reads the + rotated backup too (events.log.1) so a filter still finds older lines.""" + try: + lines = [] + for path in (EVENTS_LOG_PATH + ".1", EVENTS_LOG_PATH): + if os.path.exists(path): + with open(path, "r", encoding="utf-8", errors="replace") as f: + lines.extend(l.rstrip("\n") for l in f) + if needle: + low = needle.lower() + lines = [l for l in lines if low in l.lower()] + return lines[-limit:] if limit > 0 else [] + except Exception as e: + logger.warning(f"Could not read {EVENTS_LOG_PATH}: {e!r}") + return [] + + 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: diff --git a/README.md b/README.md index 77181a1..c5f6e3c 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ docker logs lichess-telegram-bot -f ### Журнал событий (`events.log`) -Помимо контейнерного лога бот пишет компактный структурированный журнал событий — что сделали пользователи и система. Файл лежит рядом с базой: `LichessClientTG_bot/data/events.log` (на проде — в volume `data`, переживает пересоздание контейнера; ротация 10 МБ × 5). Пишут в него оба процесса (бот и админ-бот), модуль `LichessClientTG_bot/events.py`. +Помимо контейнерного лога бот пишет компактный структурированный журнал событий — что сделали пользователи и система. Файл лежит рядом с базой: `LichessClientTG_bot/data/events.log` (на проде — в volume `data`, переживает пересоздание контейнера; ротация 10 МБ × 5). Пишут в него оба процесса (бот и админ-бот), модуль `LichessClientTG_bot/events.py`. Смотреть журнал можно прямо из админ-бота: `/events [N] [фильтр]` показывает последние N строк (по умолчанию 30, максимум 200), например `/events 50 uid=12345` или `/events 100 addgamer_result`; `/events_file` присылает файл целиком. Формат — одна строка на событие, UTC-время, имя события, поля `key=value` в фиксированном порядке (`-` = нет значения, строки с пробелами в кавычках):