admin bot: /events [N] [filter] and /events_file to read events.log from Telegram
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 26s
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 26s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
d24cc1a2bd
commit
30aaa34a33
3 changed files with 74 additions and 3 deletions
|
|
@ -20,7 +20,7 @@ from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, DATABASE_PATH, TELEGRAM_BOT_TO
|
||||||
from database import Database
|
from database import Database
|
||||||
from message_counters import MessageCounters
|
from message_counters import MessageCounters
|
||||||
from notifications import AdminNotifier
|
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,
|
# 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
|
# 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("❌ Отправка сообщения отменена.")
|
await update.message.reply_text("❌ Отправка сообщения отменена.")
|
||||||
return ConversationHandler.END
|
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 + "<pre>" + html.escape("\n".join(chunk)) + "</pre>", parse_mode='HTML')
|
||||||
|
header, chunk, size = "", [], 0
|
||||||
|
chunk.append(l); size += len(l) + 1
|
||||||
|
if chunk:
|
||||||
|
await update.message.reply_text(header + "<pre>" + html.escape("\n".join(chunk)) + "</pre>", 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):
|
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
"""Start command - register admin chat"""
|
"""Start command - register admin chat"""
|
||||||
try:
|
try:
|
||||||
|
|
@ -334,7 +378,10 @@ class AdminBot:
|
||||||
"✅ Админ-панель активирована!\n\n"
|
"✅ Админ-панель активирована!\n\n"
|
||||||
"Доступные команды:\n"
|
"Доступные команды:\n"
|
||||||
"/status - Показать статистику\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:
|
except Exception as e:
|
||||||
logger.error(f"Error in start command: {e}")
|
logger.error(f"Error in start command: {e}")
|
||||||
|
|
@ -381,6 +428,10 @@ class AdminBot:
|
||||||
# Add status command handler
|
# Add status command handler
|
||||||
application.add_handler(CommandHandler("status", self.status))
|
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():
|
def main():
|
||||||
"""Main function"""
|
"""Main function"""
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ called it. The first failure is reported once to the normal logger.
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
from typing import Optional
|
||||||
import time
|
import time
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
|
|
@ -108,6 +109,25 @@ def summary(**fields) -> None:
|
||||||
_write("SUMMARY", "", fields)
|
_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:
|
def last_summary_line() -> str:
|
||||||
"""The last SUMMARY line of events.log (used by the admin bot's /status), or '' if none / no file."""
|
"""The last SUMMARY line of events.log (used by the admin bot's /status), or '' if none / no file."""
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -219,7 +219,7 @@ docker logs lichess-telegram-bot -f
|
||||||
|
|
||||||
### Журнал событий (`events.log`)
|
### Журнал событий (`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` в фиксированном порядке (`-` = нет значения, строки с пробелами в кавычках):
|
Формат — одна строка на событие, UTC-время, имя события, поля `key=value` в фиксированном порядке (`-` = нет значения, строки с пробелами в кавычках):
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue