LichessStatTgWeb/LichessClientTG_bot/admin_bot.py

590 lines
29 KiB
Python
Raw Normal View History

2025-11-13 01:00:48 +03:00
"""
Admin Panel Telegram Bot
Sends notifications about new users and new tracked players
"""
import html
2025-11-13 01:00:48 +03:00
import logging
2025-11-13 15:07:53 +03:00
import sqlite3
import aiohttp
import asyncio
from datetime import datetime, timedelta, timezone
2025-11-13 01:00:48 +03:00
from typing import Optional
from telegram import Update
2025-11-13 15:07:53 +03:00
from telegram.ext import (
Application, CommandHandler, ContextTypes,
ConversationHandler, MessageHandler, filters
)
2025-11-13 01:00:48 +03:00
import config
from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, DATABASE_PATH, TELEGRAM_BOT_TOKEN, LOG_LEVEL
2025-11-13 01:00:48 +03:00
from database import Database
from lichess_api import LichessAPI
2025-11-13 13:32:46 +03:00
from message_counters import MessageCounters
from notifications import AdminNotifier
from events import last_summary, last_summary_line, summarize_days, tail_events, EVENTS_LOG_PATH
2025-11-13 01:00:48 +03:00
# 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
# forcing its level. Each process configures logging in its main().
2025-11-13 01:00:48 +03:00
logger = logging.getLogger(__name__)
2025-11-13 15:07:53 +03:00
# Conversation states for system message
WAITING_FOR_SYSTEM_MESSAGE = range(1)
2025-11-28 18:28:51 +03:00
WAITING_FOR_USERS0_MESSAGE = range(1, 2)
2025-11-13 15:07:53 +03:00
# /status flags (docs/design/admin_status.md, 2.4). Errors today (check_error +
# tg_error) from this number on raise the ⚠️; a bulk player status older than
# two refresh intervals means the refresh is failing (periodic_check then falls
# back to a games request on every window, see config.PLAYER_STATUS_REFRESH_MINUTES).
ERRORS_WARN = 10
STATUS_STALE_SECONDS = 2 * config.PLAYER_STATUS_REFRESH_MINUTES * 60
STATUS_FOOTER = "Ещё: /counters · /events 30 _error"
def fmt_int(n) -> str:
"""Integer with a space as thousands separator ("1 024"); "—" for None (unknown, never 0)."""
if n is None:
return "—"
return f"{int(n):,}".replace(",", " ")
def fmt_age(seconds) -> str:
"""Age for the status line: "<1 мин", "N мин" (under 3 h), "N ч" (under 48 h), "N дн."."""
seconds = max(0, int(seconds))
if seconds < 60:
return "<1 мин"
minutes = seconds // 60
if minutes < 180:
return f"{minutes} мин"
hours = minutes // 60
if hours < 48:
return f"{hours} ч"
return f"{hours // 24} дн."
def fmt_pair(today, yesterday) -> str:
""""X (вчера Y)" — every daily figure of /status is shown against yesterday's."""
return f"{fmt_int(today)} (вчера {fmt_int(yesterday)})"
def build_status_text(overview: dict, days: Optional[dict], health: Optional[dict],
summary_fields: Optional[dict], now: datetime) -> str:
"""
Render the /status message (HTML) from already collected data, so it can be
unit-tested without Telegram. Layout and rules: docs/design/admin_status.md
section 2 — a verdict line, then Здоровье / Рост / Активность, every line
≤ 34 characters (phone width) except the "stats service down" one.
overview Database.get_admin_overview(...) for `now`'s UTC day
days events.summarize_days(<7 UTC days ending today>) or None
when there is no journal (every event figure becomes "—")
health stats service GET /health body or None (did not answer)
summary_fields events.last_summary() — the last SUMMARY line's fields
now timezone-aware UTC datetime the dates were derived from
"""
today = now.date()
today_iso = today.isoformat()
yesterday_iso = (today - timedelta(days=1)).isoformat()
week = [(today - timedelta(days=i)).isoformat() for i in range(7)]
flags = []
def day(date_iso: str) -> Optional[dict]:
"""A day's event totals, or None when nothing was logged that day (shown as "—")."""
if days is None:
return None
totals = days.get(date_iso)
return totals if totals and totals['lines'] > 0 else None
def figure(date_iso: str, key: str):
totals = day(date_iso)
return totals[key] if totals else None
# --- Здоровье
health_lines = []
if days is None:
flags.append("journal")
health_lines.append("⚠️ Журнал событий ещё пуст")
else:
errors_today = figure(today_iso, 'errors')
warn = errors_today is not None and errors_today >= ERRORS_WARN
if warn:
flags.append("errors")
health_lines.append(("⚠️ " if warn else "") + "Ошибок сегодня: "
+ fmt_pair(errors_today, figure(yesterday_iso, 'errors')))
lichess_429 = health.get('lichess_429_24h') if isinstance(health, dict) else None
if not isinstance(lichess_429, int):
flags.append("stats_service")
health_lines.append("⚠️ 429 от Lichess за 24 ч: — (stats-сервис не отвечает)")
else:
if lichess_429 >= 1:
flags.append("429")
health_lines.append(("⚠️ " if lichess_429 >= 1 else "") + f"429 от Lichess за 24 ч: {fmt_int(lichess_429)}")
last_checked_at = overview['status'].get('last_checked_at')
if last_checked_at is None:
flags.append("status")
health_lines.append("⚠️ Статус игроков: нет данных")
else:
age = int(now.timestamp()) - int(last_checked_at)
stale = age > STATUS_STALE_SECONDS
if stale:
flags.append("status")
health_lines.append(("⚠️ " if stale else "") + f"Статус игроков: {fmt_age(age)} назад")
health_lines.append(f"Игроков закрыто {fmt_int(overview['status']['closed'])}, "
f"не найдено {fmt_int(overview['status']['not_found'])}")
blocked_week = sum(days[d]['blocked'] for d in week if d in days) if days is not None else None
health_lines.append(f"Заблокировали бота: {fmt_int(blocked_week)} за 7 дн.")
# The midnight SUMMARY is the proof the bot was alive at midnight; only
# meaningful when there is a journal at all (otherwise the line above says it).
if days is not None and (not summary_fields or summary_fields.get('date') != yesterday_iso):
flags.append("summary")
health_lines.append("⚠️ Нет сводки за вчера")
# --- Рост (the only aligned table: label 12 + 6 + 5 + 4 + 4 = 31 columns)
def growth_row(label: str, total, t, y, w) -> str:
return f"{label:<12}{fmt_int(total):>6}{fmt_int(t):>5}{fmt_int(y):>4}{fmt_int(w):>4}"
users, gamers, pairs = overview['users'], overview['gamers'], overview['pairs']
growth = "\n".join([
f"{'всего':>18}{'+сег':>5}{'+вч':>4}{'+7д':>4}",
growth_row("Пользователи", users['total'], users['today'], users['yesterday'], users['week']),
growth_row("Игроки", gamers['total'], gamers['today'], gamers['yesterday'], gamers['week']),
growth_row("Подписки", pairs['active'], pairs['today'], pairs['yesterday'], pairs['week']),
])
without = overview['users_without_gamers']
percent = f"{round(without / users['total'] * 100)}%" if users['total'] else "—"
without_line = f"Без игроков: {fmt_int(without)} из {fmt_int(users['total'])} ({percent})"
# --- Активность
activity_lines = [
"Команд: " + fmt_pair(figure(today_iso, 'commands'), figure(yesterday_iso, 'commands')),
"Активных людей: " + fmt_pair(figure(today_iso, 'active_users'), figure(yesterday_iso, 'active_users')),
"Уведомлений: " + fmt_pair(figure(today_iso, 'notifications'), figure(yesterday_iso, 'notifications')),
"Играли игроков: " + fmt_pair(figure(today_iso, 'players_played'), figure(yesterday_iso, 'players_played')),
"Проверок: " + fmt_pair(figure(today_iso, 'checks'), figure(yesterday_iso, 'checks')),
]
verdict = "⚠️ Есть проблемы" if flags else "✅ Всё в порядке"
return (
f"<b>{verdict} · {now.strftime('%H:%M')} UTC</b>\n\n"
f"<b>🩺 Здоровье</b>\n" + "\n".join(health_lines) + "\n\n"
f"<b>📈 Рост</b>\n<pre>{growth}</pre>\n{without_line}\n\n"
f"<b>⚡ Активность</b>\n" + "\n".join(activity_lines) + "\n\n"
+ STATUS_FOOTER
)
def build_counters_text(by_command: dict, summary_line: str) -> str:
"""
Render /counters (HTML): every raw message counter (start/lang/resetlang
included), sorted by all-time total descending, as a <pre> table of
name (21) + total (7) + today (5) = 33 columns, then the last SUMMARY line
verbatim. Empty states: "Счётчиков пока нет" / "Сводок пока нет".
"""
text = "<b>🔢 Счётчики: всего / сегодня</b>\n"
if by_command:
rows = sorted(by_command.items(), key=lambda item: (-item[1]['total'], item[0]))
text += "<pre>" + "\n".join(
f"{html.escape(name):<21}{fmt_int(data['total']):>7}{fmt_int(data['today']):>5}" for name, data in rows
) + "</pre>"
else:
text += "Счётчиков пока нет"
text += "\n\nПоследняя сводка (SUMMARY):\n"
if summary_line and " SUMMARY " in summary_line:
text += html.escape(summary_line.split(" SUMMARY ", 1)[1])
else:
text += "Сводок пока нет"
return text
2025-11-13 01:00:48 +03:00
class AdminBot:
def __init__(self):
self.db = Database()
self.application = None
2025-11-13 13:32:46 +03:00
self.counters = MessageCounters()
# Same notifier the bot process uses (notifications.py): posts to the admin
# chat through the Bot API, so it works whether or not this Application runs.
self.notifier = AdminNotifier(self.db)
# Only for GET /health of the stats service in /status (stats_base_url from config)
self.lichess_api = LichessAPI()
2025-11-13 01:00:48 +03:00
def get_admin_chat_id(self) -> Optional[int]:
"""Get admin chat ID from database"""
return self.db.get_admin_chat_id()
def set_admin_chat_id(self, chat_id: int):
"""Set admin chat ID in database"""
self.db.set_admin_chat_id(chat_id)
async def notify_new_user(self, user_id: int, username: Optional[str], first_name: Optional[str]):
"""Send notification about new Telegram user"""
await self.notifier.notify_new_user(user_id, username, first_name)
2025-11-13 01:00:48 +03:00
2025-11-18 19:39:52 +03:00
async def notify_new_player(self, player_username: str, added_by_user_id: int, added_by_username: Optional[str], is_new_gamer: bool = False):
2025-11-13 01:00:48 +03:00
"""Send notification about new tracked player"""
await self.notifier.notify_new_player(player_username, added_by_user_id, added_by_username, is_new_gamer)
2025-11-13 01:00:48 +03:00
async def status(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""/status — is the system alive, is it growing, did something break
(docs/design/admin_status.md). Everything is per UTC day, like events.log,
and the same `now` feeds the DB and the journal. Collected block-wise: a
stats service that does not answer or a missing journal only turns their
own lines into "—" / ⚠️; only the DB failing gives the ❌ reply."""
2025-11-13 01:00:48 +03:00
try:
now = datetime.now(timezone.utc)
today = now.date()
week = [(today - timedelta(days=i)).isoformat() for i in range(7)]
overview = self.db.get_admin_overview(week[0], week[1], week[6])
try:
days = summarize_days(week) # None when there is no journal (never raises)
except Exception as e:
logger.warning(f"/status: events.log unavailable: {e!r}")
days = None
try:
health = await self.lichess_api.get_service_health(timeout=3)
except Exception as e: # defensive: get_service_health itself does not raise
logger.warning(f"/status: stats service health unavailable: {e!r}")
health = None
try:
summary_fields = last_summary()
except Exception as e:
logger.warning(f"/status: last SUMMARY unavailable: {e!r}")
summary_fields = None
await update.message.reply_text(
build_status_text(overview, days, health, summary_fields, now), parse_mode='HTML'
2025-11-13 01:00:48 +03:00
)
except Exception as e:
logger.error(f"Error getting status: {e}")
await update.message.reply_text(f"❌ Ошибка получения статистики: {e}")
async def counters_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""/counters — the raw message_counters table and the last SUMMARY line, for the developer."""
try:
by_command = self.counters.get_stats_summary()['by_command']
await update.message.reply_text(build_counters_text(by_command, last_summary_line()), parse_mode='HTML')
except Exception as e:
logger.error(f"Error getting counters: {e}")
await update.message.reply_text(f"❌ Ошибка получения счётчиков: {e}")
2025-11-13 15:07:53 +03:00
async def system_mes_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start system message command - ask for message text"""
await update.message.reply_text(
"📨 Пришлите текст или фото с подписью для отправки всем пользователям:\n\n"
2025-11-13 15:07:53 +03:00
"Используйте /cancel для отмены."
)
return WAITING_FOR_SYSTEM_MESSAGE
async def handle_system_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""/system_mes: send the admin's next message (text, or photo with caption) to every user."""
return await self._broadcast(
update, "SELECT user_id FROM telegram_users",
audience="пользователям", retry_state=WAITING_FOR_SYSTEM_MESSAGE, log_name="System message")
2025-11-13 15:07:53 +03:00
async def cancel_system_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Cancel system message command"""
await update.message.reply_text("❌ Отправка сообщения отменена.")
return ConversationHandler.END
2025-11-28 18:28:51 +03:00
async def sendusers0_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start sendusers0 command - ask for message text"""
await update.message.reply_text(
"📨 Пришлите текст или фото с подписью для пользователей без игроков:\n\n"
2025-11-28 18:28:51 +03:00
"Используйте /cancel для отмены."
)
return WAITING_FOR_USERS0_MESSAGE
async def handle_users0_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""/sendusers0: the same broadcast, only to users without any player."""
return await self._broadcast(
update,
"""
2025-11-28 18:28:51 +03:00
SELECT DISTINCT tu.user_id
FROM telegram_users tu
LEFT JOIN user_gamers ug ON tu.user_id = ug.user_id
WHERE ug.id IS NULL
""",
audience="пользователям без игроков", retry_state=WAITING_FOR_USERS0_MESSAGE, log_name="Users0 message")
# Telegram limit for a photo caption, counted after entity parsing.
CAPTION_LIMIT = 1024
async def _broadcast(self, update: Update, users_sql: str, audience: str, retry_state, log_name: str):
"""
Send the admin's message to the users selected by users_sql through the
MAIN bot (TELEGRAM_BOT_TOKEN, raw Bot API calls — this process runs the
admin bot). Accepts plain text or a photo with a caption (it used to
accept text only, so a photo was silently ignored and nothing was sent).
The admin's formatting is kept: text_html / caption_html, not the plain
text. A file_id belongs to the bot that received the file, so the photo
is downloaded here, uploaded once by the main bot, and the file_id from
that first successful send is reused for everybody else.
"""
message = update.message
photo_bytes = None
if message.photo:
body = message.caption_html or ""
if len(message.caption or "") > self.CAPTION_LIMIT:
await message.reply_text(
f"❌ Подпись к фото длиннее {self.CAPTION_LIMIT} символов (Telegram не примет). "
"Сократите текст или пришлите его отдельно от картинки. /cancel — отмена.")
return retry_state
photo_file = await message.photo[-1].get_file()
photo_bytes = bytes(await photo_file.download_as_bytearray())
elif message.text and message.text.strip():
body = message.text_html
else:
await message.reply_text("❌ Нужен текст или фото с подписью. Попробуйте снова или используйте /cancel для отмены.")
return retry_state
try:
conn = sqlite3.connect(self.db.db_path)
users = [row[0] for row in conn.execute(users_sql).fetchall()]
2025-11-28 18:28:51 +03:00
conn.close()
except Exception as e:
logger.error(f"{log_name}: could not read users: {e}")
await message.reply_text(f"❌ Ошибка при чтении пользователей: {e}")
return ConversationHandler.END
if not users:
await message.reply_text(f"❌ В базе нет получателей ({audience}).")
return ConversationHandler.END
kind = "фото с подписью" if photo_bytes is not None else "текст"
status_msg = await message.reply_text(f"📤 Отправка ({kind}) {len(users)} {audience}…")
# Sent exactly as the admin wrote it, no header (owner decision 2026-10-24)
text = body
api = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}"
photo_id = None # main bot's file_id after the first successful upload
success = failed = 0
errors = {}
async with aiohttp.ClientSession() as session:
for i, user_id in enumerate(users):
2025-11-28 18:28:51 +03:00
try:
if photo_bytes is None:
request = session.post(f"{api}/sendMessage", json={
"chat_id": user_id, "text": text, "parse_mode": "HTML",
"disable_web_page_preview": False})
elif photo_id:
request = session.post(f"{api}/sendPhoto", json={
"chat_id": user_id, "photo": photo_id, "caption": text, "parse_mode": "HTML"})
else:
form = aiohttp.FormData()
form.add_field("chat_id", str(user_id))
form.add_field("caption", text)
form.add_field("parse_mode", "HTML")
form.add_field("photo", photo_bytes, filename="broadcast.jpg", content_type="image/jpeg")
request = session.post(f"{api}/sendPhoto", data=form)
async with request as response:
answer = await response.json(content_type=None)
if answer.get("ok"):
success += 1
if photo_bytes is not None and photo_id is None:
photo_id = answer["result"]["photo"][-1]["file_id"]
else:
failed += 1
reason = answer.get("description", f"HTTP {response.status}")
errors[reason] = errors.get(reason, 0) + 1
logger.warning(f"{log_name}: failed to send to user {user_id}: {reason}")
retry_after = (answer.get("parameters") or {}).get("retry_after")
if retry_after:
await asyncio.sleep(retry_after)
2025-11-28 18:28:51 +03:00
except Exception as e:
failed += 1
errors[type(e).__name__] = errors.get(type(e).__name__, 0) + 1
logger.error(f"{log_name}: error sending to user {user_id}: {e!r}")
# ~20 messages/s, under Telegram's ~30/s broadcast limit
2025-11-28 18:28:51 +03:00
if i < len(users) - 1:
await asyncio.sleep(0.05)
if (i + 1) % 100 == 0:
try:
await status_msg.edit_text(f"📤 Отправка ({kind}): {i + 1} из {len(users)}…")
except Exception:
pass
error_lines = "".join(f"\n• {html.escape(reason)}: {count}" for reason, count in
sorted(errors.items(), key=lambda item: -item[1])[:5])
await status_msg.edit_text(
f"✅ <b>Рассылка завершена</b> ({kind})\n\n"
f"• Получателей: {len(users)}\n"
f"• Отправлено: {success}\n"
f"• Ошибок: {failed}" + error_lines,
parse_mode='HTML')
logger.info(f"{log_name} sent ({kind}): {success} successful, {failed} failed out of {len(users)} users")
2025-11-28 18:28:51 +03:00
return ConversationHandler.END
2025-11-28 18:28:51 +03:00
async def cancel_users0_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Cancel users0 message command"""
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 + "<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}")
2025-11-13 01:00:48 +03:00
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start command - register admin chat"""
try:
chat_id = update.effective_chat.id
self.set_admin_chat_id(chat_id)
await update.message.reply_text(
"✅ Админ-панель активирована!\n\n"
"Доступные команды:\n"
"/status - Здоровье, рост и активность за сегодня (UTC)\n"
"/counters - Сырые счётчики команд и последняя сводка SUMMARY\n"
"/events [N] [фильтр] - Последние события из журнала (например /events 50 uid=123)\n"
"/events_file - Прислать events.log файлом\n"
"/system_mes - Отправить сообщение всем пользователям\n"
"/sendusers0 - Сообщение пользователям без игроков"
2025-11-13 01:00:48 +03:00
)
except Exception as e:
logger.error(f"Error in start command: {e}")
import traceback
logger.error(traceback.format_exc())
try:
await update.message.reply_text(f"Ошибка: {e}")
except:
pass
def setup_handlers(self, application: Application):
"""Setup all handlers"""
self.application = application # Store application reference
2025-11-13 15:07:53 +03:00
# Conversation handler for system message
system_mes_conv = ConversationHandler(
entry_points=[CommandHandler("system_mes", self.system_mes_start)],
states={
WAITING_FOR_SYSTEM_MESSAGE: [
MessageHandler((filters.TEXT | filters.PHOTO) & ~filters.COMMAND, self.handle_system_message)
2025-11-13 15:07:53 +03:00
],
},
fallbacks=[CommandHandler("cancel", self.cancel_system_message)]
)
2025-11-28 18:28:51 +03:00
# Conversation handler for sendusers0 message
sendusers0_conv = ConversationHandler(
entry_points=[CommandHandler("sendusers0", self.sendusers0_start)],
states={
WAITING_FOR_USERS0_MESSAGE: [
MessageHandler((filters.TEXT | filters.PHOTO) & ~filters.COMMAND, self.handle_users0_message)
2025-11-28 18:28:51 +03:00
],
},
fallbacks=[CommandHandler("cancel", self.cancel_users0_message)]
)
# Add conversation handlers
2025-11-13 15:07:53 +03:00
application.add_handler(system_mes_conv)
2025-11-28 18:28:51 +03:00
application.add_handler(sendusers0_conv)
2025-11-13 15:07:53 +03:00
2025-11-13 01:00:48 +03:00
# Add start command handler
application.add_handler(CommandHandler("start", self.start))
# Add status / counters command handlers
2025-11-13 01:00:48 +03:00
application.add_handler(CommandHandler("status", self.status))
application.add_handler(CommandHandler("counters", self.counters_cmd))
2025-11-13 01:00:48 +03:00
# Event log viewers (see events.py)
application.add_handler(CommandHandler("events", self.events))
application.add_handler(CommandHandler("events_file", self.events_file))
2025-11-13 01:00:48 +03:00
def main():
"""Main function"""
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=getattr(logging, LOG_LEVEL, logging.INFO)
)
# httpx logs every Telegram API call at INFO, including the full URL with the
# bot token in it: one line per getUpdates every 30s, token in plain text.
logging.getLogger("httpx").setLevel(logging.WARNING)
admin_bot = AdminBot()
2025-11-13 01:00:48 +03:00
# Create application with Long Polling configuration
application = Application.builder().token(ADMINPANEL_TELEGRAM_BOT_TOKEN).build()
# Setup handlers
admin_bot.setup_handlers(application)
# Set application reference
admin_bot.application = application
# Add error handler
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Log the error and send a telegram message to notify the developer."""
logger.error("Exception while handling an update: %r", context.error, exc_info=context.error)
2025-11-13 01:00:48 +03:00
application.add_error_handler(error_handler)
# Add post_init hook to log bot info
async def post_init(app: Application) -> None:
bot_info = await app.bot.get_me()
logger.info(f"Admin bot initialized: @{bot_info.username} (ID: {bot_info.id})")
application.post_init = post_init
# Start the bot with Long Polling
logger.info("Starting Admin Panel Bot with Long Polling...")
try:
application.run_polling(
poll_interval=1.0,
timeout=30,
drop_pending_updates=True,
allowed_updates=["message", "callback_query"]
)
except Exception as e:
logger.error(f"Fatal error in run_polling: {e}")
import traceback
logger.error(traceback.format_exc())
raise
if __name__ == '__main__':
main()