feat: система модерации (бан/мут/варны) и веб-панель с Telegram-авторизацией
- команды /aban /amute /awarn /aunban /aunmute /aunwarn /awarns
- таблицы warns/punish/mod_log/adm_perms/chats/web_sessions + миграции
- гибкая система прав: владелец чата разграничивает доступ админов (/aperm)
- владелец бота неприкосновенен: попытка ограничить даёт отказ
- веб-панель на aiohttp+Jinja2 в стиле Unfold (Tailwind, Geist, тёмная тема)
- вход через Telegram Login Widget, доступ к чатам где юзер админ и есть бот
- разделы: дашборд, чаты+капча, пользователи, активные капчи, журнал
- автоснятие временных наказаний и уборка просроченных варнов
- модульная структура: cfg/db/util/perms/mod/captcha/cmds/track/web
23 files added
4 files modified
| | |
| | | # Токен бота, полученный от @BotFather. |
| | | BOT_TOKEN=123456789:AA-EXAMPLE-TOKEN |
| | | |
| | | # Telegram ID владельца бота. Владелец имеет админ-права во всех чатах. |
| | | # Telegram ID владельца бота. Владелец имеет полный доступ во всех чатах и панели. |
| | | # Узнать свой ID можно у бота @userinfobot. |
| | | OWNER_ID=123456789 |
| | | |
| | | # Дополнительные ID, которым разрешён вход в веб-панель (права уровня владельца |
| | | # над чатами бота, но без неприкосновенности владельца). Через запятую. |
| | | WEB_ADMINS= |
| | | |
| | | # Веб-панель. |
| | | WEB_HOST=0.0.0.0 |
| | | WEB_PORT=8080 |
| | | # Публичный адрес панели для Telegram Login Widget (например https://panel.example.com). |
| | | # Если пусто, берётся из заголовков запроса (X-Forwarded-*). |
| | | WEB_BASE_URL= |
| New file |
| | |
| | | import asyncio |
| | | import random |
| | | import time |
| | | from typing import Dict, Tuple |
| | | |
| | | from aiogram import F, types |
| | | from aiogram.filters.chat_member_updated import JOIN_TRANSITION, ChatMemberUpdatedFilter |
| | | from aiogram.types import ChatMemberUpdated, InlineKeyboardMarkup |
| | | from aiogram.utils.keyboard import InlineKeyboardBuilder |
| | | |
| | | import db |
| | | from cfg import BAN_DURATION, FULL_PERMS, NO_PERMS, bot, dp, logger |
| | | |
| | | # Активные сессии капчи. Ключ (chat_id, user_id) исключает конфликт состояний. |
| | | CAP_STATE: Dict[Tuple[int, int], Dict] = {} |
| | | |
| | | |
| | | def gen_kbd(seq: list) -> InlineKeyboardMarkup: |
| | | builder = InlineKeyboardBuilder() |
| | | for num in seq: |
| | | builder.button(text=str(num), callback_data=f"cap_{num}") |
| | | builder.adjust(3) |
| | | return builder.as_markup() |
| | | |
| | | |
| | | async def del_msg(chat_id: int, msg_id: int) -> None: |
| | | try: |
| | | await bot.delete_message(chat_id, msg_id) |
| | | except Exception: |
| | | pass |
| | | |
| | | |
| | | async def ban_usr(chat_id: int, user_id: int, reason: str) -> None: |
| | | # Временное ограничение (мут) при исчерпании попыток капчи. |
| | | until = int(time.time()) + BAN_DURATION |
| | | try: |
| | | await bot.restrict_chat_member(chat_id, user_id, permissions=NO_PERMS, until_date=until) |
| | | await bot.send_message(chat_id, f"Пользователь {user_id} ограничен на 30 минут. Причина: {reason}") |
| | | await db.add_punish(chat_id, user_id, "mute", 0, reason, int(time.time()), until) |
| | | await db.add_log(chat_id, 0, user_id, "mute", reason, int(time.time())) |
| | | except Exception as e: |
| | | logger.error("ban_usr failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | |
| | | |
| | | async def kick_usr(chat_id: int, user_id: int) -> None: |
| | | # Кик через ban + unban: пользователь может зайти заново. |
| | | try: |
| | | await bot.ban_chat_member(chat_id, user_id) |
| | | await bot.unban_chat_member(chat_id, user_id, only_if_banned=True) |
| | | except Exception as e: |
| | | logger.error("kick_usr failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | |
| | | |
| | | async def cap_timeout(chat_id: int, user_id: int, timeout: int, msg_id: int) -> None: |
| | | # Фоновая задача: срабатывает, если капча не пройдена за отведённое время. |
| | | key = (chat_id, user_id) |
| | | try: |
| | | await asyncio.sleep(timeout) |
| | | state = CAP_STATE.get(key) |
| | | if state is None or state["msg_id"] != msg_id: |
| | | return |
| | | CAP_STATE.pop(key, None) |
| | | |
| | | await del_msg(chat_id, msg_id) |
| | | await db.inc_fail_cnt(user_id, chat_id) |
| | | fails = await db.get_fail_cnt(user_id, chat_id) |
| | | cfg = await db.get_chat_cfg(chat_id) |
| | | |
| | | if fails >= cfg["max_attempts"]: |
| | | await ban_usr(chat_id, user_id, "Превышено количество попыток капчи") |
| | | else: |
| | | await kick_usr(chat_id, user_id) |
| | | except asyncio.CancelledError: |
| | | pass |
| | | |
| | | |
| | | @dp.chat_member(ChatMemberUpdatedFilter(JOIN_TRANSITION)) |
| | | async def on_join(event: ChatMemberUpdated) -> None: |
| | | user = event.new_chat_member.user |
| | | if user.is_bot: |
| | | return |
| | | |
| | | chat_id = event.chat.id |
| | | user_id = user.id |
| | | cfg = await db.get_chat_cfg(chat_id) |
| | | |
| | | # until_date задаёт запас: при перезапуске бота Telegram сам снимет ограничение. |
| | | until = int(time.time()) + cfg["timeout"] + 60 |
| | | try: |
| | | await bot.restrict_chat_member(chat_id, user_id, permissions=NO_PERMS, until_date=until) |
| | | except Exception as e: |
| | | logger.error("restrict_chat_member failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return |
| | | |
| | | correct_seq = list(range(1, cfg["btn_count"] + 1)) |
| | | shuffled = correct_seq.copy() |
| | | random.shuffle(shuffled) |
| | | |
| | | msg = await bot.send_message( |
| | | chat_id, |
| | | f"Здравствуйте, {user.first_name}.\n" |
| | | f"Для доступа к чату нажмите кнопки от 1 до {cfg['btn_count']} по порядку.\n" |
| | | f"Время на прохождение: {cfg['timeout']} сек.", |
| | | reply_markup=gen_kbd(shuffled), |
| | | ) |
| | | |
| | | task = asyncio.create_task(cap_timeout(chat_id, user_id, cfg["timeout"], msg.message_id)) |
| | | CAP_STATE[(chat_id, user_id)] = { |
| | | "sequence": correct_seq, |
| | | "next_idx": 0, |
| | | "msg_id": msg.message_id, |
| | | "timer_task": task, |
| | | "deadline": int(time.time()) + cfg["timeout"], |
| | | } |
| | | |
| | | |
| | | @dp.callback_query(F.data.startswith("cap_")) |
| | | async def on_cap_click(callback: types.CallbackQuery) -> None: |
| | | if callback.message is None or callback.from_user is None or callback.data is None: |
| | | return |
| | | |
| | | chat_id = callback.message.chat.id |
| | | user_id = callback.from_user.id |
| | | key = (chat_id, user_id) |
| | | |
| | | state = CAP_STATE.get(key) |
| | | if state is None: |
| | | await callback.answer("Эта капча не для вас.", show_alert=True) |
| | | return |
| | | |
| | | clicked = int(callback.data.split("_")[1]) |
| | | expected = state["sequence"][state["next_idx"]] |
| | | |
| | | if clicked != expected: |
| | | state["timer_task"].cancel() |
| | | CAP_STATE.pop(key, None) |
| | | await del_msg(chat_id, state["msg_id"]) |
| | | |
| | | await db.inc_fail_cnt(user_id, chat_id) |
| | | fails = await db.get_fail_cnt(user_id, chat_id) |
| | | cfg = await db.get_chat_cfg(chat_id) |
| | | if fails >= cfg["max_attempts"]: |
| | | await ban_usr(chat_id, user_id, "Неверный ввод капчи, лимит попыток исчерпан") |
| | | else: |
| | | await kick_usr(chat_id, user_id) |
| | | return |
| | | |
| | | state["next_idx"] += 1 |
| | | if state["next_idx"] < len(state["sequence"]): |
| | | await callback.answer(f"Верно. Следующая кнопка: {state['sequence'][state['next_idx']]}") |
| | | return |
| | | |
| | | state["timer_task"].cancel() |
| | | CAP_STATE.pop(key, None) |
| | | await del_msg(chat_id, state["msg_id"]) |
| | | try: |
| | | await bot.restrict_chat_member(chat_id, user_id, permissions=FULL_PERMS) |
| | | except Exception as e: |
| | | logger.error("restore perms failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | await bot.send_message(chat_id, f"{callback.from_user.first_name} прошёл проверку.") |
| | | await db.rst_fail_cnt(user_id, chat_id) |
| New file |
| | |
| | | import logging |
| | | import os |
| | | from typing import Optional, Set |
| | | |
| | | from aiogram import Bot, Dispatcher |
| | | from aiogram.types import ChatPermissions |
| | | from dotenv import load_dotenv |
| | | |
| | | # --- Конфигурация --- |
| | | |
| | | load_dotenv() |
| | | |
| | | TOKEN: Optional[str] = os.getenv("BOT_TOKEN") |
| | | # Владелец бота: полный доступ везде, ограничить его нельзя. |
| | | OWNER_ID: int = int(os.getenv("OWNER_ID") or 0) |
| | | |
| | | # Дополнительные ID, которым разрешён вход в веб-панель (без прав владельца чатов). |
| | | WEB_ADMINS: Set[int] = { |
| | | int(x) for x in (os.getenv("WEB_ADMINS") or "").replace(" ", "").split(",") if x |
| | | } |
| | | |
| | | # Параметры встроенного веб-сервера панели. |
| | | WEB_HOST: str = os.getenv("WEB_HOST", "0.0.0.0") |
| | | WEB_PORT: int = int(os.getenv("WEB_PORT", "8080")) |
| | | # Публичный адрес панели (для редиректа Login Widget). Если пусто — берётся из запроса. |
| | | WEB_BASE_URL: str = (os.getenv("WEB_BASE_URL") or "").rstrip("/") |
| | | |
| | | DB_DIR: str = "data" |
| | | DB_PATH: str = os.path.join(DB_DIR, "bot.db") |
| | | |
| | | # Значения по умолчанию для настроек капчи. |
| | | DEF_BTN_COUNT: int = 3 |
| | | DEF_TIMEOUT: int = 30 |
| | | DEF_MAX_ATTEMPTS: int = 3 |
| | | |
| | | # Значения по умолчанию для системы предупреждений. |
| | | DEF_WARN_LIMIT: int = 3 |
| | | DEF_WARN_ACTION: str = "mute" # mute | ban |
| | | DEF_WARN_DURATION: int = 3600 # наказание при достижении лимита, сек |
| | | DEF_WARN_EXPIRE: int = 2592000 # срок жизни одного варна, сек (30 дней) |
| | | |
| | | # Мут при исчерпании попыток капчи. |
| | | BAN_DURATION: int = 1800 |
| | | |
| | | logging.basicConfig( |
| | | level=logging.INFO, |
| | | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| | | ) |
| | | logger = logging.getLogger("amadeus") |
| | | |
| | | # Проверка токена выполняется до создания Bot, иначе aiogram упадёт при импорте. |
| | | if not TOKEN: |
| | | raise SystemExit("BOT_TOKEN is not set in .env") |
| | | |
| | | bot = Bot(token=TOKEN) |
| | | dp = Dispatcher() |
| | | |
| | | # Имя бота без @ — нужно для Telegram Login Widget. Заполняется на старте из get_me(). |
| | | BOT_USERNAME: str = "" |
| | | |
| | | # Запрет на отправку контента: используется для капчи и мутов. |
| | | NO_PERMS = ChatPermissions( |
| | | can_send_messages=False, |
| | | can_send_audios=False, |
| | | can_send_documents=False, |
| | | can_send_photos=False, |
| | | can_send_videos=False, |
| | | can_send_video_notes=False, |
| | | can_send_voice_notes=False, |
| | | can_send_polls=False, |
| | | can_send_other_messages=False, |
| | | can_add_web_page_previews=False, |
| | | can_change_info=False, |
| | | can_invite_users=False, |
| | | can_pin_messages=False, |
| | | can_manage_topics=False, |
| | | ) |
| | | |
| | | # Полный набор прав для снятия ограничения. restrict_chat_member перезаписывает |
| | | # все флаги, поэтому указываются явно, чтобы не потерять права участника. |
| | | FULL_PERMS = ChatPermissions( |
| | | can_send_messages=True, |
| | | can_send_audios=True, |
| | | can_send_documents=True, |
| | | can_send_photos=True, |
| | | can_send_videos=True, |
| | | can_send_video_notes=True, |
| | | can_send_voice_notes=True, |
| | | can_send_polls=True, |
| | | can_send_other_messages=True, |
| | | can_add_web_page_previews=True, |
| | | can_change_info=True, |
| | | can_invite_users=True, |
| | | can_pin_messages=True, |
| | | can_manage_topics=True, |
| | | ) |
| | | |
| | | |
| | | async def load_bot_username() -> None: |
| | | # Имя бота нужно для отрисовки Login Widget; кэшируется на время работы. |
| | | global BOT_USERNAME |
| | | try: |
| | | me = await bot.get_me() |
| | | BOT_USERNAME = me.username or "" |
| | | except Exception as e: |
| | | logger.error("get_me failed: %s", e) |
| New file |
| | |
| | | from aiogram import F, types |
| | | from aiogram.filters import Command, CommandObject |
| | | |
| | | import db |
| | | import perms as pm |
| | | from cfg import bot, dp |
| | | from perms import P_CFG, P_PERMS, PERM_LABELS, check_perm, member_status |
| | | from util import mention, msg_target, now_ts, resolve_usr |
| | | |
| | | HELP_TEXT = ( |
| | | "Команды бота:\n" |
| | | "/help - этот список и текущие настройки\n" |
| | | "/config - настройки капчи\n" |
| | | "/config <кнопки> <секунды> <попытки> - изменить капчу\n" |
| | | "/warncfg <лимит> <mute|ban> <время> - настроить систему варнов\n" |
| | | "/aperm - права администраторов\n" |
| | | "/aperm @user <право> on|off - изменить право\n" |
| | | "\n" |
| | | "Модерация (ответом на сообщение или @username/ID):\n" |
| | | "/aban [время] [причина] - бан\n" |
| | | "/amute [время] [причина] - мут\n" |
| | | "/awarn [причина] - предупреждение\n" |
| | | "/aunban [причина] - снять бан\n" |
| | | "/aunmute [причина] - снять мут\n" |
| | | "/aunwarn - снять одно предупреждение\n" |
| | | "/awarns - список предупреждений\n" |
| | | "\n" |
| | | "Время: 30s, 10m, 2h, 7d, без времени или '-' - бессрочно." |
| | | ) |
| | | |
| | | |
| | | async def _is_staff(chat_id: int, user_id: int) -> bool: |
| | | st = await member_status(chat_id, user_id) |
| | | return st in ("administrator", "creator") |
| | | |
| | | |
| | | def _cfg_text(cfg: dict) -> str: |
| | | action = "бан" if cfg["warn_action"] == "ban" else "мут" |
| | | return ( |
| | | "Текущие настройки:\n" |
| | | f"Кнопок капчи: {cfg['btn_count']}\n" |
| | | f"Таймаут капчи: {cfg['timeout']} сек.\n" |
| | | f"Попыток до наказания: {cfg['max_attempts']}\n" |
| | | f"Лимит варнов: {cfg['warn_limit']}\n" |
| | | f"Действие при лимите: {action}\n" |
| | | f"Длительность наказания: {cfg['warn_duration']} сек." |
| | | ) |
| | | |
| | | |
| | | @dp.message(Command("help")) |
| | | async def cmd_help(message: types.Message) -> None: |
| | | if message.from_user is None: |
| | | return |
| | | if not await _is_staff(message.chat.id, message.from_user.id): |
| | | return |
| | | cfg = await db.get_chat_cfg(message.chat.id) |
| | | await message.answer(HELP_TEXT + "\n\n" + _cfg_text(cfg)) |
| | | |
| | | |
| | | @dp.message(Command("config")) |
| | | async def cmd_cfg(message: types.Message, command: CommandObject) -> None: |
| | | if message.from_user is None: |
| | | return |
| | | if not await check_perm(message.chat.id, message.from_user.id, P_CFG): |
| | | return |
| | | |
| | | if not command.args: |
| | | cfg = await db.get_chat_cfg(message.chat.id) |
| | | await message.answer(_cfg_text(cfg) + "\n\nИзменение: /config <кнопки> <секунды> <попытки>") |
| | | return |
| | | |
| | | try: |
| | | args = command.args.split() |
| | | if len(args) != 3: |
| | | raise ValueError |
| | | btn_count, timeout, max_attempts = (int(x) for x in args) |
| | | except ValueError: |
| | | await message.answer("Ошибка формата. Использование: /config 4 60 3") |
| | | return |
| | | |
| | | if not (1 <= btn_count <= 9) or not (5 <= timeout <= 300) or not (1 <= max_attempts <= 10): |
| | | await message.answer("Ошибка диапазона: кнопки 1-9, таймаут 5-300, попытки 1-10") |
| | | return |
| | | |
| | | await db.save_chat_cfg( |
| | | message.chat.id, btn_count=btn_count, timeout=timeout, max_attempts=max_attempts |
| | | ) |
| | | await message.answer("Настройки капчи обновлены.") |
| | | |
| | | |
| | | @dp.message(Command("warncfg")) |
| | | async def cmd_warncfg(message: types.Message, command: CommandObject) -> None: |
| | | if message.from_user is None: |
| | | return |
| | | if not await check_perm(message.chat.id, message.from_user.id, P_CFG): |
| | | return |
| | | if not command.args: |
| | | cfg = await db.get_chat_cfg(message.chat.id) |
| | | await message.answer("Использование: /warncfg <лимит> <mute|ban> <секунды>\n\n" + _cfg_text(cfg)) |
| | | return |
| | | try: |
| | | args = command.args.split() |
| | | if len(args) != 3: |
| | | raise ValueError |
| | | limit = int(args[0]) |
| | | action = args[1].lower() |
| | | duration = int(args[2]) |
| | | except ValueError: |
| | | await message.answer("Ошибка формата. Использование: /warncfg 3 mute 3600") |
| | | return |
| | | if action not in ("mute", "ban"): |
| | | await message.answer("Действие должно быть mute или ban.") |
| | | return |
| | | if not (1 <= limit <= 10) or not (0 <= duration <= 2592000): |
| | | await message.answer("Ошибка диапазона: лимит 1-10, длительность 0-2592000 сек.") |
| | | return |
| | | await db.save_chat_cfg( |
| | | message.chat.id, warn_limit=limit, warn_action=action, warn_duration=duration |
| | | ) |
| | | await message.answer("Настройки варнов обновлены.") |
| | | |
| | | |
| | | @dp.message(Command("aperm")) |
| | | async def cmd_aperm(message: types.Message, command: CommandObject) -> None: |
| | | if message.from_user is None: |
| | | return |
| | | chat_id = message.chat.id |
| | | if not await check_perm(chat_id, message.from_user.id, P_PERMS): |
| | | return |
| | | |
| | | args = (command.args or "").split() |
| | | if not args or args[0].lower() in ("list", "ls"): |
| | | rows = await db.list_perm_rows(chat_id) |
| | | if not rows: |
| | | await message.answer( |
| | | "Переопределений прав нет. Админам доступна модерация по умолчанию.\n" |
| | | "Изменение: /aperm @user <право> on|off\n" |
| | | "Права: " + ", ".join(PERM_LABELS) |
| | | ) |
| | | return |
| | | lines = ["Переопределения прав:"] |
| | | for r in rows: |
| | | state = "on" if r["allow"] else "off" |
| | | lines.append(f"- {r['user_id']}: {PERM_LABELS.get(r['perm'], r['perm'])} = {state}") |
| | | await message.answer("\n".join(lines)) |
| | | return |
| | | |
| | | if len(args) != 3: |
| | | await message.answer("Использование: /aperm @user <право> on|off") |
| | | return |
| | | target = await resolve_usr(bot, args[0]) |
| | | if not target: |
| | | await message.answer("Не удалось определить пользователя.") |
| | | return |
| | | perm = args[1].lower() |
| | | if perm not in PERM_LABELS: |
| | | await message.answer("Неизвестное право. Доступно: " + ", ".join(PERM_LABELS)) |
| | | return |
| | | state = args[2].lower() |
| | | if state not in ("on", "off", "1", "0", "вкл", "выкл"): |
| | | await message.answer("Состояние должно быть on или off.") |
| | | return |
| | | allow = state in ("on", "1", "вкл") |
| | | ok, text = await pm.set_perm(chat_id, message.from_user.id, target[0], perm, allow) |
| | | await message.answer(text) |
| | | |
| | | |
| | | @dp.message(F.text) |
| | | async def chk_nullpo(message: types.Message) -> None: |
| | | # Реакция на упоминания Nullpo в любом регистре. |
| | | if not message.text: |
| | | return |
| | | text_lower = message.text.lower() |
| | | variants = ("nullpo", "нулпо", "нуллпо", "nulpo") |
| | | if any(variant in text_lower for variant in variants): |
| | | try: |
| | | await message.reply("Gah!") |
| | | except Exception: |
| | | pass |
| New file |
| | |
| | | import os |
| | | import secrets |
| | | from contextlib import asynccontextmanager |
| | | from typing import AsyncIterator, Dict, List, Optional |
| | | |
| | | import aiosqlite |
| | | |
| | | from cfg import ( |
| | | DB_DIR, |
| | | DB_PATH, |
| | | DEF_BTN_COUNT, |
| | | DEF_MAX_ATTEMPTS, |
| | | DEF_TIMEOUT, |
| | | DEF_WARN_ACTION, |
| | | DEF_WARN_DURATION, |
| | | DEF_WARN_EXPIRE, |
| | | DEF_WARN_LIMIT, |
| | | ) |
| | | |
| | | # Колонки настроек чата, которые можно менять. |
| | | CFG_COLS = ( |
| | | "btn_count", |
| | | "timeout", |
| | | "max_attempts", |
| | | "warn_limit", |
| | | "warn_action", |
| | | "warn_duration", |
| | | ) |
| | | |
| | | SQL_TABLES = ( |
| | | "CREATE TABLE IF NOT EXISTS chat_cfg (" |
| | | "chat_id INTEGER PRIMARY KEY, " |
| | | "btn_count INTEGER DEFAULT 3, " |
| | | "timeout INTEGER DEFAULT 30, " |
| | | "max_attempts INTEGER DEFAULT 3, " |
| | | "warn_limit INTEGER DEFAULT 3, " |
| | | "warn_action TEXT DEFAULT 'mute', " |
| | | "warn_duration INTEGER DEFAULT 3600)", |
| | | "CREATE TABLE IF NOT EXISTS chats (" |
| | | "chat_id INTEGER PRIMARY KEY, " |
| | | "title TEXT, " |
| | | "type TEXT, " |
| | | "added_at INTEGER, " |
| | | "updated_at INTEGER, " |
| | | "active INTEGER DEFAULT 1)", |
| | | "CREATE TABLE IF NOT EXISTS usr_fails (" |
| | | "user_id INTEGER, " |
| | | "chat_id INTEGER, " |
| | | "fail_count INTEGER DEFAULT 0, " |
| | | "PRIMARY KEY (user_id, chat_id))", |
| | | "CREATE TABLE IF NOT EXISTS warns (" |
| | | "id INTEGER PRIMARY KEY AUTOINCREMENT, " |
| | | "chat_id INTEGER, " |
| | | "user_id INTEGER, " |
| | | "admin_id INTEGER, " |
| | | "reason TEXT, " |
| | | "created_at INTEGER, " |
| | | "expires_at INTEGER)", |
| | | "CREATE TABLE IF NOT EXISTS punish (" |
| | | "id INTEGER PRIMARY KEY AUTOINCREMENT, " |
| | | "chat_id INTEGER, " |
| | | "user_id INTEGER, " |
| | | "kind TEXT, " |
| | | "admin_id INTEGER, " |
| | | "reason TEXT, " |
| | | "created_at INTEGER, " |
| | | "until INTEGER, " |
| | | "active INTEGER DEFAULT 1)", |
| | | "CREATE TABLE IF NOT EXISTS mod_log (" |
| | | "id INTEGER PRIMARY KEY AUTOINCREMENT, " |
| | | "chat_id INTEGER, " |
| | | "admin_id INTEGER, " |
| | | "target_id INTEGER, " |
| | | "action TEXT, " |
| | | "reason TEXT, " |
| | | "created_at INTEGER)", |
| | | "CREATE TABLE IF NOT EXISTS adm_perms (" |
| | | "chat_id INTEGER, " |
| | | "user_id INTEGER, " |
| | | "perm TEXT, " |
| | | "allow INTEGER, " |
| | | "PRIMARY KEY (chat_id, user_id, perm))", |
| | | "CREATE TABLE IF NOT EXISTS web_sessions (" |
| | | "token TEXT PRIMARY KEY, " |
| | | "user_id INTEGER, " |
| | | "created_at INTEGER, " |
| | | "expires_at INTEGER)", |
| | | "CREATE TABLE IF NOT EXISTS web_users (" |
| | | "user_id INTEGER PRIMARY KEY, " |
| | | "first_name TEXT, " |
| | | "last_name TEXT, " |
| | | "username TEXT, " |
| | | "photo_url TEXT, " |
| | | "last_login INTEGER)", |
| | | ) |
| | | |
| | | |
| | | @asynccontextmanager |
| | | async def db_conn() -> AsyncIterator[aiosqlite.Connection]: |
| | | # busy_timeout предотвращает ошибку "database is locked" при параллельных апдейтах. |
| | | conn = await aiosqlite.connect(DB_PATH) |
| | | conn.row_factory = aiosqlite.Row |
| | | try: |
| | | await conn.execute("PRAGMA busy_timeout=5000") |
| | | yield conn |
| | | finally: |
| | | await conn.close() |
| | | |
| | | |
| | | async def tbl_exists(db: aiosqlite.Connection, name: str) -> bool: |
| | | async with db.execute( |
| | | "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,) |
| | | ) as cur: |
| | | return await cur.fetchone() is not None |
| | | |
| | | |
| | | async def col_exists(db: aiosqlite.Connection, table: str, col: str) -> bool: |
| | | async with db.execute(f"PRAGMA table_info({table})") as cur: |
| | | cols = [r[1] for r in await cur.fetchall()] |
| | | return col in cols |
| | | |
| | | |
| | | async def migrate_db(db: aiosqlite.Connection) -> None: |
| | | # Обратная совместимость: таблицы переименованы при рефакторинге. |
| | | if await tbl_exists(db, "chat_settings") and not await tbl_exists(db, "chat_cfg"): |
| | | await db.execute("ALTER TABLE chat_settings RENAME TO chat_cfg") |
| | | if await tbl_exists(db, "user_violations") and not await tbl_exists(db, "usr_fails"): |
| | | await db.execute("ALTER TABLE user_violations RENAME TO usr_fails") |
| | | # Дополняем chat_cfg колонками системы предупреждений. |
| | | if await tbl_exists(db, "chat_cfg"): |
| | | if not await col_exists(db, "chat_cfg", "warn_limit"): |
| | | await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_limit INTEGER DEFAULT 3") |
| | | if not await col_exists(db, "chat_cfg", "warn_action"): |
| | | await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_action TEXT DEFAULT 'mute'") |
| | | if not await col_exists(db, "chat_cfg", "warn_duration"): |
| | | await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_duration INTEGER DEFAULT 3600") |
| | | |
| | | |
| | | async def init_db() -> None: |
| | | # Создание каталога обязательно: без него sqlite не откроет файл БД. |
| | | os.makedirs(DB_DIR, exist_ok=True) |
| | | async with aiosqlite.connect(DB_PATH) as db: |
| | | await db.execute("PRAGMA journal_mode=WAL") |
| | | await migrate_db(db) |
| | | for sql in SQL_TABLES: |
| | | await db.execute(sql) |
| | | await db.commit() |
| | | |
| | | |
| | | # --- Чаты --- |
| | | |
| | | async def upsert_chat(chat_id: int, title: Optional[str], ctype: Optional[str], ts: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO chats (chat_id, title, type, added_at, updated_at, active) " |
| | | "VALUES (?, ?, ?, ?, ?, 1) " |
| | | "ON CONFLICT(chat_id) DO UPDATE SET " |
| | | "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, active=1", |
| | | (chat_id, title, ctype, ts, ts), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def set_chat_active(chat_id: int, active: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute("UPDATE chats SET active=? WHERE chat_id=?", (active, chat_id)) |
| | | await db.commit() |
| | | |
| | | |
| | | async def list_chats(active_only: bool = True) -> List[dict]: |
| | | q = "SELECT * FROM chats" |
| | | if active_only: |
| | | q += " WHERE active=1" |
| | | q += " ORDER BY title COLLATE NOCASE" |
| | | async with db_conn() as db: |
| | | async with db.execute(q) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | async def get_chat(chat_id: int) -> Optional[dict]: |
| | | async with db_conn() as db: |
| | | async with db.execute("SELECT * FROM chats WHERE chat_id=?", (chat_id,)) as cur: |
| | | row = await cur.fetchone() |
| | | return dict(row) if row else None |
| | | |
| | | |
| | | # --- Настройки чата --- |
| | | |
| | | def _cfg_defaults() -> Dict: |
| | | return { |
| | | "btn_count": DEF_BTN_COUNT, |
| | | "timeout": DEF_TIMEOUT, |
| | | "max_attempts": DEF_MAX_ATTEMPTS, |
| | | "warn_limit": DEF_WARN_LIMIT, |
| | | "warn_action": DEF_WARN_ACTION, |
| | | "warn_duration": DEF_WARN_DURATION, |
| | | } |
| | | |
| | | |
| | | async def get_chat_cfg(chat_id: int) -> Dict: |
| | | async with db_conn() as db: |
| | | async with db.execute("SELECT * FROM chat_cfg WHERE chat_id=?", (chat_id,)) as cur: |
| | | row = await cur.fetchone() |
| | | cfg = _cfg_defaults() |
| | | if row: |
| | | for key in CFG_COLS: |
| | | if row[key] is not None: |
| | | cfg[key] = row[key] |
| | | return cfg |
| | | |
| | | |
| | | async def save_chat_cfg(chat_id: int, **fields) -> None: |
| | | # Частичный upsert: обновляются только переданные колонки. |
| | | data = {k: v for k, v in fields.items() if k in CFG_COLS} |
| | | if not data: |
| | | return |
| | | cols = ["chat_id"] + list(data) |
| | | marks = ",".join("?" for _ in cols) |
| | | updates = ",".join(f"{k}=excluded.{k}" for k in data) |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | f"INSERT INTO chat_cfg ({','.join(cols)}) VALUES ({marks}) " |
| | | f"ON CONFLICT(chat_id) DO UPDATE SET {updates}", |
| | | [chat_id] + list(data.values()), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | # --- Нарушения капчи --- |
| | | |
| | | async def get_fail_cnt(user_id: int, chat_id: int) -> int: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT fail_count FROM usr_fails WHERE user_id=? AND chat_id=?", |
| | | (user_id, chat_id), |
| | | ) as cur: |
| | | row = await cur.fetchone() |
| | | return row[0] if row else 0 |
| | | |
| | | |
| | | async def inc_fail_cnt(user_id: int, chat_id: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO usr_fails (user_id, chat_id, fail_count) VALUES (?, ?, 1) " |
| | | "ON CONFLICT(user_id, chat_id) DO UPDATE SET fail_count = fail_count + 1", |
| | | (user_id, chat_id), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def rst_fail_cnt(user_id: int, chat_id: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "DELETE FROM usr_fails WHERE user_id=? AND chat_id=?", (user_id, chat_id) |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | # --- Варны --- |
| | | |
| | | async def add_warn(chat_id: int, user_id: int, admin_id: int, reason: str, ts: int, expire: int) -> int: |
| | | async with db_conn() as db: |
| | | cur = await db.execute( |
| | | "INSERT INTO warns (chat_id, user_id, admin_id, reason, created_at, expires_at) " |
| | | "VALUES (?, ?, ?, ?, ?, ?)", |
| | | (chat_id, user_id, admin_id, reason, ts, ts + expire), |
| | | ) |
| | | await db.commit() |
| | | return cur.lastrowid |
| | | |
| | | |
| | | async def cnt_warns(chat_id: int, user_id: int, ts: int) -> int: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT COUNT(*) FROM warns WHERE chat_id=? AND user_id=? AND (expires_at IS NULL OR expires_at > ?)", |
| | | (chat_id, user_id, ts), |
| | | ) as cur: |
| | | return (await cur.fetchone())[0] |
| | | |
| | | |
| | | async def list_warns(chat_id: int, user_id: Optional[int] = None) -> List[dict]: |
| | | q = "SELECT * FROM warns WHERE chat_id=?" |
| | | args: list = [chat_id] |
| | | if user_id is not None: |
| | | q += " AND user_id=?" |
| | | args.append(user_id) |
| | | q += " ORDER BY created_at DESC" |
| | | async with db_conn() as db: |
| | | async with db.execute(q, args) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | async def del_last_warn(chat_id: int, user_id: int) -> bool: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT id FROM warns WHERE chat_id=? AND user_id=? ORDER BY created_at DESC, id DESC LIMIT 1", |
| | | (chat_id, user_id), |
| | | ) as cur: |
| | | row = await cur.fetchone() |
| | | if not row: |
| | | return False |
| | | await db.execute("DELETE FROM warns WHERE id=?", (row["id"],)) |
| | | await db.commit() |
| | | return True |
| | | |
| | | |
| | | async def clr_warns(chat_id: int, user_id: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute("DELETE FROM warns WHERE chat_id=? AND user_id=?", (chat_id, user_id)) |
| | | await db.commit() |
| | | |
| | | |
| | | async def exp_warns(ts: int) -> None: |
| | | # Уборка просроченных варнов. |
| | | async with db_conn() as db: |
| | | await db.execute("DELETE FROM warns WHERE expires_at IS NOT NULL AND expires_at <= ?", (ts,)) |
| | | await db.commit() |
| | | |
| | | |
| | | # --- Наказания (муты/баны) --- |
| | | |
| | | async def add_punish(chat_id: int, user_id: int, kind: str, admin_id: int, reason: str, ts: int, until: Optional[int]) -> int: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "UPDATE punish SET active=0 WHERE chat_id=? AND user_id=? AND kind=? AND active=1", |
| | | (chat_id, user_id, kind), |
| | | ) |
| | | cur = await db.execute( |
| | | "INSERT INTO punish (chat_id, user_id, kind, admin_id, reason, created_at, until, active) " |
| | | "VALUES (?, ?, ?, ?, ?, ?, ?, 1)", |
| | | (chat_id, user_id, kind, admin_id, reason, ts, until), |
| | | ) |
| | | await db.commit() |
| | | return cur.lastrowid |
| | | |
| | | |
| | | async def end_punish(chat_id: int, user_id: int, kind: str) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "UPDATE punish SET active=0 WHERE chat_id=? AND user_id=? AND kind=? AND active=1", |
| | | (chat_id, user_id, kind), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def get_punish(chat_id: int, user_id: int, kind: str) -> Optional[dict]: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT * FROM punish WHERE chat_id=? AND user_id=? AND kind=? AND active=1 " |
| | | "ORDER BY id DESC LIMIT 1", |
| | | (chat_id, user_id, kind), |
| | | ) as cur: |
| | | row = await cur.fetchone() |
| | | return dict(row) if row else None |
| | | |
| | | |
| | | async def list_punish(chat_id: Optional[int] = None, active_only: bool = True) -> List[dict]: |
| | | q = "SELECT * FROM punish WHERE 1=1" |
| | | args: list = [] |
| | | if chat_id is not None: |
| | | q += " AND chat_id=?" |
| | | args.append(chat_id) |
| | | if active_only: |
| | | q += " AND active=1" |
| | | q += " ORDER BY created_at DESC" |
| | | async with db_conn() as db: |
| | | async with db.execute(q, args) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | async def due_unbans(ts: int) -> List[dict]: |
| | | # Активные наказания, срок которых истёк и которые нужно снять. |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT * FROM punish WHERE active=1 AND until IS NOT NULL AND until <= ?", (ts,) |
| | | ) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | async def hist_punish(chat_id: int, user_id: int) -> List[dict]: |
| | | # Полная история мутов/банов пользователя в чате. |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT * FROM punish WHERE chat_id=? AND user_id=? ORDER BY created_at DESC", |
| | | (chat_id, user_id), |
| | | ) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | async def stats(ts: int) -> dict: |
| | | # Сводная статистика для дашборда панели. |
| | | async with db_conn() as db: |
| | | async def one(q: str, args: tuple = ()): |
| | | async with db.execute(q, args) as cur: |
| | | return (await cur.fetchone())[0] |
| | | return { |
| | | "chats": await one("SELECT COUNT(*) FROM chats WHERE active=1"), |
| | | "warns": await one( |
| | | "SELECT COUNT(*) FROM warns WHERE expires_at IS NULL OR expires_at > ?", (ts,) |
| | | ), |
| | | "mutes": await one("SELECT COUNT(*) FROM punish WHERE active=1 AND kind='mute'"), |
| | | "bans": await one("SELECT COUNT(*) FROM punish WHERE active=1 AND kind='ban'"), |
| | | "logs": await one("SELECT COUNT(*) FROM mod_log"), |
| | | "web_users": await one("SELECT COUNT(*) FROM web_users"), |
| | | } |
| | | |
| | | |
| | | async def add_log(chat_id: int, admin_id: int, target_id: int, action: str, reason: str, ts: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO mod_log (chat_id, admin_id, target_id, action, reason, created_at) " |
| | | "VALUES (?, ?, ?, ?, ?, ?)", |
| | | (chat_id, admin_id, target_id, action, reason or "", ts), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def list_log(chat_id: Optional[int] = None, limit: int = 100) -> List[dict]: |
| | | if chat_id is None: |
| | | q = "SELECT * FROM mod_log ORDER BY created_at DESC LIMIT ?" |
| | | args: list = [limit] |
| | | else: |
| | | q = "SELECT * FROM mod_log WHERE chat_id=? ORDER BY created_at DESC LIMIT ?" |
| | | args = [chat_id, limit] |
| | | async with db_conn() as db: |
| | | async with db.execute(q, args) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | # --- Права администраторов --- |
| | | |
| | | async def set_perm(chat_id: int, user_id: int, perm: str, allow: bool) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO adm_perms (chat_id, user_id, perm, allow) VALUES (?, ?, ?, ?) " |
| | | "ON CONFLICT(chat_id, user_id, perm) DO UPDATE SET allow=excluded.allow", |
| | | (chat_id, user_id, perm, 1 if allow else 0), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def get_perm_row(chat_id: int, user_id: int, perm: str) -> Optional[int]: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT allow FROM adm_perms WHERE chat_id=? AND user_id=? AND perm=?", |
| | | (chat_id, user_id, perm), |
| | | ) as cur: |
| | | row = await cur.fetchone() |
| | | return row[0] if row else None |
| | | |
| | | |
| | | async def list_perm_rows(chat_id: int) -> List[dict]: |
| | | async with db_conn() as db: |
| | | async with db.execute("SELECT * FROM adm_perms WHERE chat_id=?", (chat_id,)) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | async def del_user_perms(chat_id: int, user_id: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute("DELETE FROM adm_perms WHERE chat_id=? AND user_id=?", (chat_id, user_id)) |
| | | await db.commit() |
| | | |
| | | |
| | | # --- Веб-сессии и пользователи панели --- |
| | | |
| | | async def create_sess(user_id: int, ts: int, ttl: int) -> str: |
| | | token = secrets.token_urlsafe(32) |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO web_sessions (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)", |
| | | (token, user_id, ts, ts + ttl), |
| | | ) |
| | | await db.commit() |
| | | return token |
| | | |
| | | |
| | | async def get_sess(token: str, ts: int) -> Optional[dict]: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT * FROM web_sessions WHERE token=? AND expires_at > ?", (token, ts) |
| | | ) as cur: |
| | | row = await cur.fetchone() |
| | | return dict(row) if row else None |
| | | |
| | | |
| | | async def del_sess(token: str) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute("DELETE FROM web_sessions WHERE token=?", (token,)) |
| | | await db.commit() |
| | | |
| | | |
| | | async def upsert_web_user(user_id: int, first_name: str, last_name: str, username: str, photo_url: str, ts: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO web_users (user_id, first_name, last_name, username, photo_url, last_login) " |
| | | "VALUES (?, ?, ?, ?, ?, ?) " |
| | | "ON CONFLICT(user_id) DO UPDATE SET " |
| | | "first_name=excluded.first_name, last_name=excluded.last_name, " |
| | | "username=excluded.username, photo_url=excluded.photo_url, last_login=excluded.last_login", |
| | | (user_id, first_name, last_name, username, photo_url, ts), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def get_web_user(user_id: int) -> Optional[dict]: |
| | | async with db_conn() as db: |
| | | async with db.execute("SELECT * FROM web_users WHERE user_id=?", (user_id,)) as cur: |
| | | row = await cur.fetchone() |
| | | return dict(row) if row else None |
| | |
| | | restart: always |
| | | env_file: |
| | | - .env |
| | | ports: |
| | | - "8080:8080" |
| | | volumes: |
| | | - ./data:/app/data |
| | |
| | | import asyncio |
| | | import logging |
| | | import os |
| | | import random |
| | | import time |
| | | from contextlib import asynccontextmanager |
| | | from typing import AsyncIterator, Dict, Optional, Tuple |
| | | |
| | | import aiosqlite |
| | | from aiogram import Bot, Dispatcher, F, types |
| | | from aiogram.filters import Command, CommandObject |
| | | from aiogram.filters.chat_member_updated import ChatMemberUpdatedFilter, JOIN_TRANSITION |
| | | from aiogram.types import ChatPermissions, ChatMemberUpdated, InlineKeyboardMarkup |
| | | from aiogram.utils.keyboard import InlineKeyboardBuilder |
| | | from dotenv import load_dotenv |
| | | import db |
| | | import mod |
| | | from cfg import bot, dp, load_bot_username, logger |
| | | |
| | | # --- Конфигурация --- |
| | | |
| | | load_dotenv() |
| | | |
| | | TOKEN: Optional[str] = os.getenv("BOT_TOKEN") |
| | | # ID владельца бота. Владелец обладает админ-правами во всех чатах. |
| | | OWNER_ID: int = int(os.getenv("OWNER_ID") or 0) |
| | | |
| | | DB_DIR: str = "data" |
| | | DB_PATH: str = os.path.join(DB_DIR, "bot.db") |
| | | |
| | | # Значения по умолчанию для настроек чата. |
| | | DEF_BTN_COUNT: int = 3 |
| | | DEF_TIMEOUT: int = 30 |
| | | DEF_MAX_ATTEMPTS: int = 3 |
| | | |
| | | # Длительность мута (в секундах) при исчерпании попыток капчи. |
| | | BAN_DURATION: int = 1800 |
| | | |
| | | # Активные сессии капчи. Ключ (chat_id, user_id) исключает конфликт |
| | | # состояний, когда один пользователь проходит капчу в нескольких чатах. |
| | | CAP_STATE: Dict[Tuple[int, int], Dict] = {} |
| | | |
| | | logging.basicConfig( |
| | | level=logging.INFO, |
| | | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| | | ) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | # Проверка токена выполняется до создания Bot, иначе aiogram упадёт при импорте. |
| | | if not TOKEN: |
| | | raise SystemExit("BOT_TOKEN is not set in .env") |
| | | |
| | | bot = Bot(token=TOKEN) |
| | | dp = Dispatcher() |
| | | |
| | | # Ограничение прав: запрет на отправку контента, остальные права сняты. |
| | | NO_PERMS = ChatPermissions( |
| | | can_send_messages=False, |
| | | can_send_audios=False, |
| | | can_send_documents=False, |
| | | can_send_photos=False, |
| | | can_send_videos=False, |
| | | can_send_video_notes=False, |
| | | can_send_voice_notes=False, |
| | | can_send_polls=False, |
| | | can_send_other_messages=False, |
| | | can_add_web_page_previews=False, |
| | | can_change_info=False, |
| | | can_invite_users=False, |
| | | can_pin_messages=False, |
| | | can_manage_topics=False, |
| | | ) |
| | | |
| | | # Полный набор прав для снятия ограничения. restrict_chat_member перезаписывает |
| | | # все флаги, поэтому указываются явно, чтобы не потерять права участника. |
| | | FULL_PERMS = ChatPermissions( |
| | | can_send_messages=True, |
| | | can_send_audios=True, |
| | | can_send_documents=True, |
| | | can_send_photos=True, |
| | | can_send_videos=True, |
| | | can_send_video_notes=True, |
| | | can_send_voice_notes=True, |
| | | can_send_polls=True, |
| | | can_send_other_messages=True, |
| | | can_add_web_page_previews=True, |
| | | can_change_info=True, |
| | | can_invite_users=True, |
| | | can_pin_messages=True, |
| | | can_manage_topics=True, |
| | | ) |
| | | |
| | | SQL_CREATE_CFG = ( |
| | | "CREATE TABLE IF NOT EXISTS chat_cfg (" |
| | | "chat_id INTEGER PRIMARY KEY, " |
| | | "btn_count INTEGER DEFAULT 3, " |
| | | "timeout INTEGER DEFAULT 30, " |
| | | "max_attempts INTEGER DEFAULT 3)" |
| | | ) |
| | | |
| | | SQL_CREATE_FAILS = ( |
| | | "CREATE TABLE IF NOT EXISTS usr_fails (" |
| | | "user_id INTEGER, " |
| | | "chat_id INTEGER, " |
| | | "fail_count INTEGER DEFAULT 0, " |
| | | "PRIMARY KEY (user_id, chat_id))" |
| | | ) |
| | | |
| | | |
| | | # --- База данных --- |
| | | |
| | | @asynccontextmanager |
| | | async def db_conn() -> AsyncIterator[aiosqlite.Connection]: |
| | | # busy_timeout предотвращает ошибку "database is locked" при параллельных апдейтах. |
| | | conn = await aiosqlite.connect(DB_PATH) |
| | | try: |
| | | await conn.execute("PRAGMA busy_timeout=5000") |
| | | yield conn |
| | | finally: |
| | | await conn.close() |
| | | |
| | | |
| | | async def tbl_exists(db: aiosqlite.Connection, name: str) -> bool: |
| | | async with db.execute( |
| | | "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,) |
| | | ) as cur: |
| | | return await cur.fetchone() is not None |
| | | |
| | | |
| | | async def migrate_db(db: aiosqlite.Connection) -> None: |
| | | # Обратная совместимость: таблицы переименованы при рефакторинге. |
| | | # Старые имена переименовываются в новые, данные при этом сохраняются. |
| | | if await tbl_exists(db, "chat_settings") and not await tbl_exists(db, "chat_cfg"): |
| | | await db.execute("ALTER TABLE chat_settings RENAME TO chat_cfg") |
| | | if await tbl_exists(db, "user_violations") and not await tbl_exists(db, "usr_fails"): |
| | | await db.execute("ALTER TABLE user_violations RENAME TO usr_fails") |
| | | |
| | | |
| | | async def init_db() -> None: |
| | | # Создание каталога обязательно: без него sqlite не откроет файл БД. |
| | | os.makedirs(DB_DIR, exist_ok=True) |
| | | async with aiosqlite.connect(DB_PATH) as db: |
| | | await db.execute("PRAGMA journal_mode=WAL") |
| | | await migrate_db(db) |
| | | await db.execute(SQL_CREATE_CFG) |
| | | await db.execute(SQL_CREATE_FAILS) |
| | | await db.commit() |
| | | |
| | | |
| | | async def get_chat_cfg(chat_id: int) -> Dict[str, int]: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT btn_count, timeout, max_attempts FROM chat_cfg WHERE chat_id = ?", |
| | | (chat_id,), |
| | | ) as cur: |
| | | row = await cur.fetchone() |
| | | if row: |
| | | return {"btn_count": row[0], "timeout": row[1], "max_attempts": row[2]} |
| | | return { |
| | | "btn_count": DEF_BTN_COUNT, |
| | | "timeout": DEF_TIMEOUT, |
| | | "max_attempts": DEF_MAX_ATTEMPTS, |
| | | } |
| | | |
| | | |
| | | async def set_chat_cfg( |
| | | chat_id: int, btn_count: int, timeout: int, max_attempts: int |
| | | ) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO chat_cfg (chat_id, btn_count, timeout, max_attempts) " |
| | | "VALUES (?, ?, ?, ?) " |
| | | "ON CONFLICT(chat_id) DO UPDATE SET " |
| | | "btn_count=excluded.btn_count, " |
| | | "timeout=excluded.timeout, " |
| | | "max_attempts=excluded.max_attempts", |
| | | (chat_id, btn_count, timeout, max_attempts), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def get_fail_cnt(user_id: int, chat_id: int) -> int: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT fail_count FROM usr_fails WHERE user_id = ? AND chat_id = ?", |
| | | (user_id, chat_id), |
| | | ) as cur: |
| | | row = await cur.fetchone() |
| | | return row[0] if row else 0 |
| | | |
| | | |
| | | async def inc_fail_cnt(user_id: int, chat_id: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO usr_fails (user_id, chat_id, fail_count) VALUES (?, ?, 1) " |
| | | "ON CONFLICT(user_id, chat_id) DO UPDATE SET fail_count = fail_count + 1", |
| | | (user_id, chat_id), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | async def rst_fail_cnt(user_id: int, chat_id: int) -> None: |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "DELETE FROM usr_fails WHERE user_id = ? AND chat_id = ?", |
| | | (user_id, chat_id), |
| | | ) |
| | | await db.commit() |
| | | |
| | | |
| | | # --- Вспомогательные функции --- |
| | | |
| | | def gen_kbd(seq: list) -> InlineKeyboardMarkup: |
| | | builder = InlineKeyboardBuilder() |
| | | for num in seq: |
| | | builder.button(text=str(num), callback_data=f"cap_{num}") |
| | | builder.adjust(3) |
| | | return builder.as_markup() |
| | | |
| | | |
| | | async def is_adm(chat_id: int, user_id: int) -> bool: |
| | | # Владелец бота получает админ-права независимо от статуса в чате. |
| | | if user_id == OWNER_ID: |
| | | return True |
| | | try: |
| | | member = await bot.get_chat_member(chat_id, user_id) |
| | | except Exception as e: |
| | | logger.error("get_chat_member failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return False |
| | | return member.status in ("administrator", "creator") |
| | | |
| | | |
| | | async def del_msg(chat_id: int, msg_id: int) -> None: |
| | | # Удаление сообщения не должно прерывать логику при ошибке. |
| | | try: |
| | | await bot.delete_message(chat_id, msg_id) |
| | | except Exception: |
| | | pass |
| | | |
| | | |
| | | async def ban_usr(chat_id: int, user_id: int, reason: str) -> None: |
| | | # Мут на BAN_DURATION секунд: временное ограничение через restrict. |
| | | until = int(time.time()) + BAN_DURATION |
| | | try: |
| | | await bot.restrict_chat_member( |
| | | chat_id, user_id, permissions=NO_PERMS, until_date=until |
| | | ) |
| | | await bot.send_message( |
| | | chat_id, |
| | | f"Пользователь {user_id} ограничен на 30 минут. Причина: {reason}", |
| | | ) |
| | | except Exception as e: |
| | | logger.error("ban_usr failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | |
| | | |
| | | async def kick_usr(chat_id: int, user_id: int) -> None: |
| | | # Кик реализуется через ban + unban: пользователь может зайти заново. |
| | | try: |
| | | await bot.ban_chat_member(chat_id, user_id) |
| | | await bot.unban_chat_member(chat_id, user_id) |
| | | except Exception as e: |
| | | logger.error("kick_usr failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | |
| | | |
| | | async def cap_timeout(chat_id: int, user_id: int, timeout: int, msg_id: int) -> None: |
| | | # Фоновая задача: срабатывает, если капча не пройдена за отведённое время. |
| | | key = (chat_id, user_id) |
| | | try: |
| | | await asyncio.sleep(timeout) |
| | | |
| | | state = CAP_STATE.get(key) |
| | | if state is None or state["msg_id"] != msg_id: |
| | | return |
| | | CAP_STATE.pop(key, None) |
| | | |
| | | await del_msg(chat_id, msg_id) |
| | | await inc_fail_cnt(user_id, chat_id) |
| | | fails = await get_fail_cnt(user_id, chat_id) |
| | | cfg = await get_chat_cfg(chat_id) |
| | | |
| | | if fails >= cfg["max_attempts"]: |
| | | await ban_usr(chat_id, user_id, "Превышено количество попыток капчи") |
| | | else: |
| | | await kick_usr(chat_id, user_id) |
| | | except asyncio.CancelledError: |
| | | # Отмена означает успешное прохождение либо сброс сессии. |
| | | pass |
| | | |
| | | |
| | | # --- Обработчики --- |
| | | |
| | | @dp.message(Command("help")) |
| | | async def cmd_help(message: types.Message) -> None: |
| | | if message.from_user is None: |
| | | return |
| | | if not await is_adm(message.chat.id, message.from_user.id): |
| | | return |
| | | |
| | | cfg = await get_chat_cfg(message.chat.id) |
| | | await message.answer( |
| | | "Команды бота:\n" |
| | | "/help - список команд и текущие настройки чата\n" |
| | | "/config - просмотр текущих настроек\n" |
| | | "/config <кнопки> <секунды> <попытки> - изменение настроек\n" |
| | | "\n" |
| | | "Текущие настройки чата:\n" |
| | | f"Количество кнопок: {cfg['btn_count']}\n" |
| | | f"Таймаут: {cfg['timeout']} сек.\n" |
| | | f"Попыток до бана: {cfg['max_attempts']}" |
| | | ) |
| | | |
| | | |
| | | @dp.message(Command("config")) |
| | | async def cmd_cfg(message: types.Message, command: CommandObject) -> None: |
| | | if message.from_user is None: |
| | | return |
| | | if not await is_adm(message.chat.id, message.from_user.id): |
| | | return |
| | | |
| | | # Без аргументов команда выводит только текущие настройки. |
| | | if not command.args: |
| | | cfg = await get_chat_cfg(message.chat.id) |
| | | await message.answer( |
| | | "Текущие настройки:\n" |
| | | f"Кнопок: {cfg['btn_count']}\n" |
| | | f"Таймаут: {cfg['timeout']} сек.\n" |
| | | f"Попыток до бана: {cfg['max_attempts']}\n" |
| | | "Изменение: /config <кнопки> <секунды> <попытки>" |
| | | ) |
| | | return |
| | | |
| | | try: |
| | | args = command.args.split() |
| | | if len(args) != 3: |
| | | raise ValueError |
| | | btn_count = int(args[0]) |
| | | timeout = int(args[1]) |
| | | max_attempts = int(args[2]) |
| | | except ValueError: |
| | | await message.answer("Ошибка формата. Использование: /config 4 60 3") |
| | | return |
| | | |
| | | # Границы значений: кнопки 1-9, таймаут 5-300 сек, попытки 1-10. |
| | | if not (1 <= btn_count <= 9) or not (5 <= timeout <= 300) or not (1 <= max_attempts <= 10): |
| | | await message.answer("Ошибка диапазона: кнопки 1-9, таймаут 5-300, попытки 1-10") |
| | | return |
| | | |
| | | await set_chat_cfg(message.chat.id, btn_count, timeout, max_attempts) |
| | | await message.answer("Настройки обновлены.") |
| | | |
| | | |
| | | @dp.chat_member(ChatMemberUpdatedFilter(JOIN_TRANSITION)) |
| | | async def on_join(event: ChatMemberUpdated) -> None: |
| | | user = event.new_chat_member.user |
| | | |
| | | # Боты не проходят капчу. |
| | | if user.is_bot: |
| | | return |
| | | |
| | | chat_id = event.chat.id |
| | | user_id = user.id |
| | | cfg = await get_chat_cfg(chat_id) |
| | | |
| | | # until_date задаёт запас времени: при перезапуске бота Telegram сам снимет |
| | | # ограничение, и пользователь не останется замученным навсегда. |
| | | until = int(time.time()) + cfg["timeout"] + 60 |
| | | try: |
| | | await bot.restrict_chat_member( |
| | | chat_id, user_id, permissions=NO_PERMS, until_date=until |
| | | ) |
| | | except Exception as e: |
| | | logger.error("restrict_chat_member failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return |
| | | |
| | | # Эталонная последовательность 1..N; визуальный порядок кнопок перемешивается. |
| | | correct_seq = list(range(1, cfg["btn_count"] + 1)) |
| | | shuffled = correct_seq.copy() |
| | | random.shuffle(shuffled) |
| | | |
| | | msg = await bot.send_message( |
| | | chat_id, |
| | | f"Здравствуйте, {user.first_name}.\n" |
| | | f"Для доступа к чату нажмите кнопки от 1 до {cfg['btn_count']} по порядку.\n" |
| | | f"Время на прохождение: {cfg['timeout']} сек.", |
| | | reply_markup=gen_kbd(shuffled), |
| | | ) |
| | | |
| | | task = asyncio.create_task( |
| | | cap_timeout(chat_id, user_id, cfg["timeout"], msg.message_id) |
| | | ) |
| | | CAP_STATE[(chat_id, user_id)] = { |
| | | "sequence": correct_seq, |
| | | "next_idx": 0, |
| | | "msg_id": msg.message_id, |
| | | "timer_task": task, |
| | | } |
| | | |
| | | |
| | | @dp.callback_query(F.data.startswith("cap_")) |
| | | async def on_cap_click(callback: types.CallbackQuery) -> None: |
| | | if callback.message is None or callback.from_user is None or callback.data is None: |
| | | return |
| | | |
| | | chat_id = callback.message.chat.id |
| | | user_id = callback.from_user.id |
| | | key = (chat_id, user_id) |
| | | |
| | | state = CAP_STATE.get(key) |
| | | if state is None: |
| | | await callback.answer("Эта капча не для вас.", show_alert=True) |
| | | return |
| | | |
| | | clicked = int(callback.data.split("_")[1]) |
| | | expected = state["sequence"][state["next_idx"]] |
| | | |
| | | # Неверная кнопка: сессия сбрасывается, счётчик нарушений растёт. |
| | | if clicked != expected: |
| | | state["timer_task"].cancel() |
| | | CAP_STATE.pop(key, None) |
| | | await del_msg(chat_id, state["msg_id"]) |
| | | |
| | | await inc_fail_cnt(user_id, chat_id) |
| | | fails = await get_fail_cnt(user_id, chat_id) |
| | | cfg = await get_chat_cfg(chat_id) |
| | | |
| | | if fails >= cfg["max_attempts"]: |
| | | await ban_usr(chat_id, user_id, "Неверный ввод капчи, лимит попыток исчерпан") |
| | | else: |
| | | await kick_usr(chat_id, user_id) |
| | | return |
| | | |
| | | state["next_idx"] += 1 |
| | | |
| | | # Последовательность ещё не завершена. |
| | | if state["next_idx"] < len(state["sequence"]): |
| | | await callback.answer( |
| | | f"Верно. Следующая кнопка: {state['sequence'][state['next_idx']]}" |
| | | ) |
| | | return |
| | | |
| | | # Капча пройдена: снимаем ограничение и сбрасываем счётчик нарушений. |
| | | state["timer_task"].cancel() |
| | | CAP_STATE.pop(key, None) |
| | | await del_msg(chat_id, state["msg_id"]) |
| | | |
| | | try: |
| | | await bot.restrict_chat_member(chat_id, user_id, permissions=FULL_PERMS) |
| | | except Exception as e: |
| | | logger.error("restore perms failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | |
| | | await bot.send_message(chat_id, f"{callback.from_user.first_name} прошёл проверку.") |
| | | await rst_fail_cnt(user_id, chat_id) |
| | | |
| | | |
| | | @dp.message(F.text) |
| | | async def chk_nullpo(message: types.Message) -> None: |
| | | # Реакция на упоминания Nullpo в любом регистре. |
| | | if not message.text: |
| | | return |
| | | text_lower = message.text.lower() |
| | | variants = ("nullpo", "нулпо", "нуллпо", "nulpo") |
| | | if any(variant in text_lower for variant in variants): |
| | | try: |
| | | await message.reply("Gah!") |
| | | except Exception as e: |
| | | logger.error("nullpo reply failed: %s", e) |
| | | # Импорт модулей регистрирует обработчики на dp. |
| | | # Порядок важен: команды модерации (mod) и общие команды (cmds) доходят раньше |
| | | # ловящего все сообщения обработчика nullpo, поэтому cmds импортируется последним |
| | | # среди обработчиков сообщений. |
| | | import captcha # noqa: F401 |
| | | import cmds # noqa: F401 |
| | | import track # noqa: F401 |
| | | from web.app import start_web |
| | | |
| | | |
| | | async def main() -> None: |
| | | await init_db() |
| | | # Сброс вебхуков на случай, если ранее использовался webhook-режим. |
| | | await db.init_db() |
| | | await load_bot_username() |
| | | # Снимаем наказания, срок которых истёк, пока бот был выключен. |
| | | await mod._bg_tick() |
| | | |
| | | bg_task = mod.start_bg() |
| | | runner = await start_web() |
| | | |
| | | await bot.delete_webhook(drop_pending_updates=True) |
| | | logger.info("Bot started") |
| | | await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types()) |
| | | try: |
| | | await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types()) |
| | | finally: |
| | | bg_task.cancel() |
| | | await runner.cleanup() |
| | | |
| | | |
| | | if __name__ == "__main__": |
| New file |
| | |
| | | import asyncio |
| | | import re |
| | | from typing import Optional, Tuple |
| | | |
| | | from aiogram import types |
| | | from aiogram.filters import Command, CommandObject |
| | | |
| | | import db |
| | | from cfg import OWNER_ID, FULL_PERMS, NO_PERMS, DEF_WARN_EXPIRE, bot, dp, logger |
| | | from perms import P_BAN, P_MUTE, P_UNBAN, P_UNMUTE, P_UNWARN, P_WARN, check_perm, member_status |
| | | from util import fmt_dur, mention, msg_target, now_ts, parse_dur, refuse_phrase, resolve_usr |
| | | |
| | | # Шаблон токена длительности: 10m, 2h, 7d, '-' (бессрочно). |
| | | DUR_RE = re.compile(r"^(\d+[smhdwSMHDW]?|-|forever|perm|permanent)$", re.IGNORECASE) |
| | | |
| | | NOT_ENOUGH = "Недостаточно прав." |
| | | OWNER_BLOCK = "Владельца бота наказать нельзя." |
| | | |
| | | |
| | | # --- Ядро действий --- |
| | | |
| | | async def apply_mute(chat_id: int, user_id: int, name: str, until: Optional[int], admin_id: int, reason: str) -> bool: |
| | | ts = now_ts() |
| | | try: |
| | | await bot.restrict_chat_member(chat_id, user_id, permissions=NO_PERMS, until_date=until) |
| | | except Exception as e: |
| | | logger.error("mute failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return False |
| | | await db.add_punish(chat_id, user_id, "mute", admin_id, reason, ts, until) |
| | | await db.add_log(chat_id, admin_id, user_id, "mute", reason, ts) |
| | | await _notice(chat_id, f"Пользователь {mention(user_id, name)} замучен на {fmt_dur(until)}. Причина: {reason or '-'}") |
| | | return True |
| | | |
| | | |
| | | async def apply_ban(chat_id: int, user_id: int, name: str, until: Optional[int], admin_id: int, reason: str) -> bool: |
| | | ts = now_ts() |
| | | try: |
| | | await bot.ban_chat_member(chat_id, user_id) |
| | | except Exception as e: |
| | | logger.error("ban failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return False |
| | | await db.add_punish(chat_id, user_id, "ban", admin_id, reason, ts, until) |
| | | await db.add_log(chat_id, admin_id, user_id, "ban", reason, ts) |
| | | await _notice(chat_id, f"Пользователь {mention(user_id, name)} забанен на {fmt_dur(until)}. Причина: {reason or '-'}") |
| | | return True |
| | | |
| | | |
| | | async def apply_unmute(chat_id: int, user_id: int, name: str, admin_id: int, reason: str) -> bool: |
| | | ts = now_ts() |
| | | try: |
| | | await bot.restrict_chat_member(chat_id, user_id, permissions=FULL_PERMS) |
| | | except Exception as e: |
| | | logger.error("unmute failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return False |
| | | await db.end_punish(chat_id, user_id, "mute") |
| | | await db.add_log(chat_id, admin_id, user_id, "unmute", reason, ts) |
| | | await _notice(chat_id, f"С пользователя {mention(user_id, name)} снят мут.") |
| | | return True |
| | | |
| | | |
| | | async def apply_unban(chat_id: int, user_id: int, name: str, admin_id: int, reason: str) -> bool: |
| | | ts = now_ts() |
| | | try: |
| | | await bot.unban_chat_member(chat_id, user_id, only_if_banned=True) |
| | | except Exception as e: |
| | | logger.error("unban failed chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return False |
| | | await db.end_punish(chat_id, user_id, "ban") |
| | | await db.add_log(chat_id, admin_id, user_id, "unban", reason, ts) |
| | | await _notice(chat_id, f"Пользователь {mention(user_id, name)} разбанен.") |
| | | return True |
| | | |
| | | |
| | | async def apply_warn(chat_id: int, user_id: int, name: str, admin_id: int, reason: str) -> Tuple[int, int, bool]: |
| | | # Возвращает (текущее число варнов, лимит, сработало ли наказание). |
| | | ts = now_ts() |
| | | cfg = await db.get_chat_cfg(chat_id) |
| | | await db.add_warn(chat_id, user_id, admin_id, reason, ts, DEF_WARN_EXPIRE) |
| | | count = await db.cnt_warns(chat_id, user_id, ts) |
| | | await db.add_log(chat_id, admin_id, user_id, "warn", reason, ts) |
| | | |
| | | if count >= cfg["warn_limit"]: |
| | | # Достигнут лимит: применяем настроенное наказание и обнуляем варны. |
| | | dur = cfg["warn_duration"] or None |
| | | if cfg["warn_action"] == "ban": |
| | | await apply_ban(chat_id, user_id, name, dur, admin_id, f"Лимит варнов ({count})") |
| | | else: |
| | | await apply_mute(chat_id, user_id, name, dur, admin_id, f"Лимит варнов ({count})") |
| | | await db.clr_warns(chat_id, user_id) |
| | | return count, cfg["warn_limit"], True |
| | | |
| | | await _notice(chat_id, f"{mention(user_id, name)} получил предупреждение ({count}/{cfg['warn_limit']}). Причина: {reason or '-'}") |
| | | return count, cfg["warn_limit"], False |
| | | |
| | | |
| | | async def apply_unwarn(chat_id: int, user_id: int, name: str, admin_id: int) -> bool: |
| | | ok = await db.del_last_warn(chat_id, user_id) |
| | | ts = now_ts() |
| | | await db.add_log(chat_id, admin_id, user_id, "unwarn", "", ts) |
| | | if ok: |
| | | await _notice(chat_id, f"С {mention(user_id, name)} снято одно предупреждение.") |
| | | return ok |
| | | |
| | | |
| | | async def _notice(chat_id: int, text: str) -> None: |
| | | try: |
| | | await bot.send_message(chat_id, text, parse_mode="HTML") |
| | | except Exception as e: |
| | | logger.warning("notice failed chat=%s: %s", chat_id, e) |
| | | |
| | | |
| | | # --- Разбор аргументов --- |
| | | |
| | | async def _target(message: types.Message, command: CommandObject): |
| | | # Возвращает (user_id, name, rest_args) либо (None, text_ошибки, None). |
| | | args = list((command.args or "").split()) |
| | | rep = msg_target(message) |
| | | if rep: |
| | | return rep[0], rep[1], args |
| | | if not args: |
| | | return None, "Укажите цель: ответом на сообщение или @username/ID.", None |
| | | res = await resolve_usr(bot, args[0]) |
| | | if not res: |
| | | return None, "Не удалось определить пользователя.", None |
| | | return res[0], res[1], args[1:] |
| | | |
| | | |
| | | def _dur_reason(rest, default: Optional[int] = None) -> Tuple[Optional[int], str]: |
| | | if rest and DUR_RE.match(rest[0]): |
| | | try: |
| | | dur = parse_dur(rest[0]) |
| | | except ValueError: |
| | | dur = default |
| | | return dur, " ".join(rest[1:]) |
| | | return default, " ".join(rest) |
| | | |
| | | |
| | | async def _guard(message: types.Message, perm: str, target_id: int) -> bool: |
| | | if message.from_user is None: |
| | | return False |
| | | chat_id = message.chat.id |
| | | actor = message.from_user.id |
| | | if target_id == OWNER_ID: |
| | | await message.reply(f"{OWNER_BLOCK} {refuse_phrase()}") |
| | | return False |
| | | if target_id == actor: |
| | | await message.reply("Нельзя применить это к себе.") |
| | | return False |
| | | if await member_status(chat_id, target_id) == "creator": |
| | | await message.reply("Создателя чата трогать нельзя.") |
| | | return False |
| | | if not await check_perm(chat_id, actor, perm): |
| | | await message.reply(NOT_ENOUGH) |
| | | return False |
| | | return True |
| | | |
| | | |
| | | async def _delete_cmd(message: types.Message) -> None: |
| | | try: |
| | | await message.delete() |
| | | except Exception: |
| | | pass |
| | | |
| | | |
| | | # --- Команды --- |
| | | |
| | | @dp.message(Command("aban")) |
| | | async def cmd_aban(message: types.Message, command: CommandObject) -> None: |
| | | target_id, name, rest = await _target(message, command) |
| | | if target_id is None: |
| | | await message.reply(name) |
| | | return |
| | | if not await _guard(message, P_BAN, target_id): |
| | | return |
| | | dur, reason = _dur_reason(rest) |
| | | ok = await apply_ban(message.chat.id, target_id, name, dur, message.from_user.id, reason) |
| | | if not ok: |
| | | await message.reply("Не удалось забанить (проверьте права бота).") |
| | | |
| | | |
| | | @dp.message(Command("amute")) |
| | | async def cmd_amute(message: types.Message, command: CommandObject) -> None: |
| | | target_id, name, rest = await _target(message, command) |
| | | if target_id is None: |
| | | await message.reply(name) |
| | | return |
| | | if not await _guard(message, P_MUTE, target_id): |
| | | return |
| | | dur, reason = _dur_reason(rest) |
| | | ok = await apply_mute(message.chat.id, target_id, name, dur, message.from_user.id, reason) |
| | | if not ok: |
| | | await message.reply("Не удалось замутить (проверьте права бота).") |
| | | |
| | | |
| | | @dp.message(Command("awarn")) |
| | | async def cmd_awarn(message: types.Message, command: CommandObject) -> None: |
| | | target_id, name, rest = await _target(message, command) |
| | | if target_id is None: |
| | | await message.reply(name) |
| | | return |
| | | if not await _guard(message, P_WARN, target_id): |
| | | return |
| | | reason = " ".join(rest) |
| | | await apply_warn(message.chat.id, target_id, name, message.from_user.id, reason) |
| | | |
| | | |
| | | @dp.message(Command("aunban")) |
| | | async def cmd_aunban(message: types.Message, command: CommandObject) -> None: |
| | | target_id, name, rest = await _target(message, command) |
| | | if target_id is None: |
| | | await message.reply(name) |
| | | return |
| | | if not await check_perm(message.chat.id, message.from_user.id, P_UNBAN): |
| | | await message.reply(NOT_ENOUGH) |
| | | return |
| | | if not await apply_unban(message.chat.id, target_id, name, message.from_user.id, " ".join(rest)): |
| | | await message.reply("Не удалось разбанить.") |
| | | |
| | | |
| | | @dp.message(Command("aunmute")) |
| | | async def cmd_aunmute(message: types.Message, command: CommandObject) -> None: |
| | | target_id, name, rest = await _target(message, command) |
| | | if target_id is None: |
| | | await message.reply(name) |
| | | return |
| | | if not await check_perm(message.chat.id, message.from_user.id, P_UNMUTE): |
| | | await message.reply(NOT_ENOUGH) |
| | | return |
| | | if not await apply_unmute(message.chat.id, target_id, name, message.from_user.id, " ".join(rest)): |
| | | await message.reply("Не удалось снять мут.") |
| | | |
| | | |
| | | @dp.message(Command("aunwarn")) |
| | | async def cmd_aunwarn(message: types.Message, command: CommandObject) -> None: |
| | | target_id, name, rest = await _target(message, command) |
| | | if target_id is None: |
| | | await message.reply(name) |
| | | return |
| | | if not await check_perm(message.chat.id, message.from_user.id, P_UNWARN): |
| | | await message.reply(NOT_ENOUGH) |
| | | return |
| | | await apply_unwarn(message.chat.id, target_id, name, message.from_user.id) |
| | | |
| | | |
| | | @dp.message(Command("awarns")) |
| | | async def cmd_awarns(message: types.Message, command: CommandObject) -> None: |
| | | target_id, name, rest = await _target(message, command) |
| | | if target_id is None: |
| | | await message.reply(name) |
| | | return |
| | | rows = await db.list_warns(message.chat.id, target_id) |
| | | ts = now_ts() |
| | | active = [w for w in rows if not w["expires_at"] or w["expires_at"] > ts] |
| | | if not active: |
| | | await message.reply(f"У {mention(target_id, name)} нет активных предупреждений.", parse_mode="HTML") |
| | | return |
| | | lines = [f"Предупреждения {mention(target_id, name)}: {len(active)}"] |
| | | for w in active: |
| | | lines.append(f"- {w['reason'] or 'без причины'}") |
| | | await message.reply("\n".join(lines), parse_mode="HTML") |
| | | |
| | | |
| | | # --- Фоновые задачи: уборка варнов и автоснятие временных наказаний --- |
| | | |
| | | async def _bg_tick() -> None: |
| | | ts = now_ts() |
| | | await db.exp_warns(ts) |
| | | for row in await db.due_unbans(ts): |
| | | chat_id = row["chat_id"] |
| | | user_id = row["user_id"] |
| | | try: |
| | | if row["kind"] == "ban": |
| | | await bot.unban_chat_member(chat_id, user_id, only_if_banned=True) |
| | | else: |
| | | await bot.restrict_chat_member(chat_id, user_id, permissions=FULL_PERMS) |
| | | except Exception as e: |
| | | logger.warning("auto-release %s chat=%s user=%s: %s", row["kind"], chat_id, user_id, e) |
| | | await db.end_punish(chat_id, user_id, row["kind"]) |
| | | await db.add_log(chat_id, 0, user_id, "auto-" + row["kind"], "истёк срок", ts) |
| | | |
| | | |
| | | async def bg_loop() -> None: |
| | | while True: |
| | | try: |
| | | await _bg_tick() |
| | | except Exception as e: |
| | | logger.error("bg_loop: %s", e) |
| | | await asyncio.sleep(60) |
| | | |
| | | |
| | | def start_bg() -> asyncio.Task: |
| | | return asyncio.create_task(bg_loop()) |
| New file |
| | |
| | | from typing import Dict, List, Optional |
| | | |
| | | from aiogram import Bot |
| | | |
| | | import db |
| | | from cfg import OWNER_ID, logger |
| | | from util import refuse_phrase |
| | | |
| | | # Ключи прав. Владелец бота и создатель чата имеют все права без исключений. |
| | | P_BAN = "ban" |
| | | P_MUTE = "mute" |
| | | P_WARN = "warn" |
| | | P_UNBAN = "unban" |
| | | P_UNMUTE = "unmute" |
| | | P_UNWARN = "unwarn" |
| | | P_CFG = "config" |
| | | P_PERMS = "perms" |
| | | |
| | | # Человекочитаемые названия прав для панели и команд. |
| | | PERM_LABELS: Dict[str, str] = { |
| | | P_BAN: "Бан", |
| | | P_MUTE: "Мут", |
| | | P_WARN: "Варн", |
| | | P_UNBAN: "Разбан", |
| | | P_UNMUTE: "Размут", |
| | | P_UNWARN: "Снятие варна", |
| | | P_CFG: "Настройки капчи", |
| | | P_PERMS: "Управление правами", |
| | | } |
| | | |
| | | # Права, разрешённые администратору по умолчанию (создатель может отключить). |
| | | DEF_ADM_PERMS: Dict[str, bool] = { |
| | | P_BAN: True, |
| | | P_MUTE: True, |
| | | P_WARN: True, |
| | | P_UNBAN: True, |
| | | P_UNMUTE: True, |
| | | P_UNWARN: True, |
| | | P_CFG: True, |
| | | P_PERMS: False, |
| | | } |
| | | |
| | | |
| | | async def member_status(chat_id: int, user_id: int) -> Optional[str]: |
| | | try: |
| | | member = await bot.get_chat_member(chat_id, user_id) |
| | | return member.status |
| | | except Exception as e: |
| | | logger.warning("get_chat_member chat=%s user=%s: %s", chat_id, user_id, e) |
| | | return None |
| | | |
| | | |
| | | async def is_owner(user_id: int) -> bool: |
| | | return user_id == OWNER_ID |
| | | |
| | | |
| | | async def is_creator(chat_id: int, user_id: int) -> bool: |
| | | if user_id == OWNER_ID: |
| | | return True |
| | | return (await member_status(chat_id, user_id)) == "creator" |
| | | |
| | | |
| | | async def check_perm(chat_id: int, user_id: int, perm: str) -> bool: |
| | | # Владелец бота неприкосновенен: у него всегда полный доступ. |
| | | if user_id == OWNER_ID: |
| | | return True |
| | | status = await member_status(chat_id, user_id) |
| | | if status == "creator": |
| | | return True |
| | | if status != "administrator": |
| | | return False |
| | | override = await db.get_perm_row(chat_id, user_id, perm) |
| | | if override is not None: |
| | | return bool(override) |
| | | return DEF_ADM_PERMS.get(perm, False) |
| | | |
| | | |
| | | async def set_perm(chat_id: int, actor_id: int, target_id: int, perm: str, allow: bool): |
| | | # Возвращает (ok, message). Попытка ограничить владельца бота отклоняется. |
| | | if target_id == OWNER_ID and not allow: |
| | | return False, refuse_phrase() |
| | | if not await is_creator(chat_id, actor_id): |
| | | return False, "Управлять правами может только создатель чата." |
| | | await db.set_perm(chat_id, target_id, perm, allow) |
| | | state = "разрешено" if allow else "запрещено" |
| | | return True, f"Право «{PERM_LABELS.get(perm, perm)}» {state}." |
| | | |
| | | |
| | | async def perms_of(chat_id: int, user_id: int) -> Dict[str, bool]: |
| | | # Итоговый набор прав пользователя в чате (с учётом значения по умолчанию). |
| | | if user_id == OWNER_ID or await is_creator(chat_id, user_id): |
| | | return {k: True for k in PERM_LABELS} |
| | | status = await member_status(chat_id, user_id) |
| | | if status != "administrator": |
| | | return {k: False for k in PERM_LABELS} |
| | | result = dict(DEF_ADM_PERMS) |
| | | for row in await db.list_perm_rows(chat_id): |
| | | if row["user_id"] == user_id and row["perm"] in result: |
| | | result[row["perm"]] = bool(row["allow"]) |
| | | return result |
| | | |
| | | |
| | | async def adm_chats(bot: Bot, user_id: int) -> List[dict]: |
| | | # Чаты, где стоит бот И пользователь админ (для владельца — все чаты). |
| | | chats = await db.list_chats(active_only=True) |
| | | if user_id == OWNER_ID: |
| | | return chats |
| | | result = [] |
| | | for chat in chats: |
| | | status = await member_status(chat["chat_id"], user_id) |
| | | if status in ("administrator", "creator"): |
| | | result.append(chat) |
| | | return result |
| | |
| | | aiogram~=3.13.1 |
| | | aiosqlite~=0.20.0 |
| | | aiohttp>=3.9,<4 |
| | | jinja2~=3.1 |
| | | python-dotenv~=1.0.1 |
| New file |
| | |
| | | from aiogram import types |
| | | |
| | | import db |
| | | from cfg import OWNER_ID, dp, logger |
| | | from util import now_ts |
| | | |
| | | |
| | | @dp.message.middleware() |
| | | async def track_msg(handler, event: types.Message, data: dict): |
| | | # Фиксируем чаты, где присутствует бот, для веб-панели. |
| | | chat = event.chat |
| | | if chat and chat.type in ("group", "supergroup", "channel"): |
| | | try: |
| | | await db.upsert_chat(chat.id, chat.title, chat.type, now_ts()) |
| | | except Exception as e: |
| | | logger.warning("upsert_chat failed chat=%s: %s", chat.id, e) |
| | | return await handler(event, data) |
| | | |
| | | |
| | | @dp.my_chat_member() |
| | | async def on_my_member(event: types.ChatMemberUpdated) -> None: |
| | | # Обновление статуса пребывания бота в чате. |
| | | chat = event.chat |
| | | status = event.new_chat_member.status |
| | | try: |
| | | if status in ("left", "kicked"): |
| | | await db.set_chat_active(chat.id, 0) |
| | | else: |
| | | await db.upsert_chat(chat.id, chat.title, chat.type, now_ts()) |
| | | except Exception as e: |
| | | logger.warning("my_chat_member failed chat=%s: %s", chat.id, e) |
| New file |
| | |
| | | import random |
| | | import time |
| | | from html import escape |
| | | from typing import List, Optional, Tuple |
| | | |
| | | from aiogram import Bot |
| | | from aiogram.types import Message |
| | | |
| | | # Фразы, которые бот выдаёт при попытке ограничить владельца бота. |
| | | REFUSE_PHRASES: List[str] = [ |
| | | "Я не пойду против хозяина.", |
| | | "Простите, но против хозяина я не пойду.", |
| | | "Хозяин превыше всего. Отказано.", |
| | | "Тут распоряжается мой хозяин, а не вы. Отклонено.", |
| | | "Даже не просите. Хозяин неприкосновенен.", |
| | | ] |
| | | |
| | | |
| | | def refuse_phrase() -> str: |
| | | return random.choice(REFUSE_PHRASES) |
| | | |
| | | |
| | | def now_ts() -> int: |
| | | return int(time.time()) |
| | | |
| | | |
| | | def parse_dur(text: str) -> Optional[int]: |
| | | # Разбор длительности: 30s, 10m, 2h, 7d, 3w. Без суффикса — минуты. |
| | | # '-' / 'forever' / 'perm' / '0' означают бессрочно (None). |
| | | if text is None: |
| | | return None |
| | | raw = text.strip().lower() |
| | | if raw in ("-", "forever", "perm", "permanent", "0"): |
| | | return None |
| | | mult = 60 |
| | | if raw[-1] in ("s", "m", "h", "d", "w"): |
| | | unit = raw[-1] |
| | | raw = raw[:-1] |
| | | mult = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}[unit] |
| | | value = int(raw) |
| | | if value < 0: |
| | | raise ValueError |
| | | if value == 0: |
| | | return None |
| | | return value * mult |
| | | |
| | | |
| | | def fmt_dur(seconds: Optional[int]) -> str: |
| | | if seconds is None: |
| | | return "бессрочно" |
| | | parts = [] |
| | | for name, size in (("д", 86400), ("ч", 3600), ("м", 60), ("с", 1)): |
| | | if seconds >= size: |
| | | parts.append(f"{seconds // size}{name}") |
| | | seconds %= size |
| | | return " ".join(parts) or "0с" |
| | | |
| | | |
| | | def fmt_dt(ts: Optional[int]) -> str: |
| | | if not ts: |
| | | return "-" |
| | | return time.strftime("%d.%m.%Y %H:%M", time.localtime(ts)) |
| | | |
| | | |
| | | def mention(user_id: int, name: Optional[str] = None) -> str: |
| | | label = escape(name or str(user_id)) |
| | | return f'<a href="tg://user?id={user_id}">{label}</a>' |
| | | |
| | | |
| | | async def resolve_usr(bot: Bot, token: str) -> Optional[Tuple[int, str]]: |
| | | # Разрешение цели: числовой ID или @username. |
| | | token = token.strip() |
| | | if not token: |
| | | return None |
| | | if token.lstrip("-").isdigit(): |
| | | try: |
| | | chat = await bot.get_chat(int(token)) |
| | | return chat.id, chat.full_name or str(chat.id) |
| | | except Exception: |
| | | return int(token), token |
| | | if token.startswith("@"): |
| | | try: |
| | | chat = await bot.get_chat(token) |
| | | return chat.id, chat.full_name or token |
| | | except Exception: |
| | | return None |
| | | return None |
| | | |
| | | |
| | | def msg_target(message: Message) -> Optional[Tuple[int, str]]: |
| | | # Цель из reply: id и отображаемое имя. |
| | | if message.reply_to_message and message.reply_to_message.from_user: |
| | | u = message.reply_to_message.from_user |
| | | return u.id, u.full_name |
| | | return None |
| New file |
| | |
| | | import pathlib |
| | | |
| | | from aiohttp import web |
| | | |
| | | from cfg import WEB_HOST, WEB_PORT, logger |
| | | from web import auth, views |
| | | |
| | | BASE = pathlib.Path(__file__).resolve().parent |
| | | |
| | | |
| | | def create_app() -> web.Application: |
| | | app = web.Application(middlewares=[auth.session_mw]) |
| | | app.router.add_get("/", views.dashboard) |
| | | app.router.add_get("/login", auth.login_page) |
| | | app.router.add_get("/auth/telegram", auth.auth_telegram) |
| | | app.router.add_get("/logout", auth.logout) |
| | | app.router.add_get("/chats", views.chats_page) |
| | | app.router.add_get("/chats/{chat_id}", views.chat_page) |
| | | app.router.add_post("/chats/cfg", views.chat_cfg) |
| | | app.router.add_post("/chats/perm", views.chat_perm) |
| | | app.router.add_get("/users", views.users_page) |
| | | app.router.add_get("/users/{chat_id}/{user_id}", views.user_page) |
| | | app.router.add_post("/action", views.action) |
| | | app.router.add_get("/captcha", views.captcha_page) |
| | | app.router.add_get("/log", views.log_page) |
| | | app.router.add_static("/static", BASE / "static") |
| | | return app |
| | | |
| | | |
| | | async def start_web() -> web.AppRunner: |
| | | runner = web.AppRunner(create_app()) |
| | | await runner.setup() |
| | | site = web.TCPSite(runner, WEB_HOST, WEB_PORT) |
| | | await site.start() |
| | | logger.info("Web panel started on %s:%s", WEB_HOST, WEB_PORT) |
| | | return runner |
| New file |
| | |
| | | import hashlib |
| | | import hmac |
| | | |
| | | from aiohttp import web |
| | | |
| | | import db |
| | | from cfg import BOT_USERNAME, OWNER_ID, WEB_ADMINS, WEB_BASE_URL, bot |
| | | from util import now_ts |
| | | from web.render import render |
| | | |
| | | SESS_TTL = 7 * 86400 |
| | | COOKIE = "amd_sess" |
| | | |
| | | |
| | | def base_url(request) -> str: |
| | | if WEB_BASE_URL: |
| | | return WEB_BASE_URL |
| | | proto = request.headers.get("X-Forwarded-Proto", request.scheme) |
| | | host = request.headers.get("X-Forwarded-Host", request.host) |
| | | return f"{proto}://{host}" |
| | | |
| | | |
| | | def is_staff(user_id: int) -> bool: |
| | | return user_id == OWNER_ID or user_id in WEB_ADMINS |
| | | |
| | | |
| | | def verify_login(data: dict) -> bool: |
| | | # Проверка подписи Telegram Login Widget: HMAC-SHA256 на секрете из токена бота. |
| | | check = data.get("hash") |
| | | if not check: |
| | | return False |
| | | pairs = sorted(f"{k}={v}" for k, v in data.items() if k != "hash") |
| | | secret = hashlib.sha256(bot.token.encode()).digest() |
| | | calc = hmac.new(secret, "\n".join(pairs).encode(), hashlib.sha256).hexdigest() |
| | | if not hmac.compare_digest(calc, check): |
| | | return False |
| | | try: |
| | | auth_date = int(data.get("auth_date", "0")) |
| | | except ValueError: |
| | | return False |
| | | return now_ts() - auth_date <= 86400 |
| | | |
| | | |
| | | @web.middleware |
| | | async def session_mw(request, handler): |
| | | request["user"] = None |
| | | token = request.cookies.get(COOKIE) |
| | | if token: |
| | | sess = await db.get_sess(token, now_ts()) |
| | | if sess: |
| | | request["user"] = await db.get_web_user(sess["user_id"]) or {"user_id": sess["user_id"], "first_name": ""} |
| | | public = request.path in ("/login", "/auth/telegram") or request.path.startswith("/static") |
| | | if request["user"] is None and not public: |
| | | raise web.HTTPFound("/login") |
| | | return await handler(request) |
| | | |
| | | |
| | | async def login_page(request) -> web.Response: |
| | | return render( |
| | | request, |
| | | "login.html", |
| | | bot_username=BOT_USERNAME, |
| | | auth_url=base_url(request) + "/auth/telegram", |
| | | ) |
| | | |
| | | |
| | | async def auth_telegram(request) -> web.Response: |
| | | q = dict(request.query) |
| | | if not verify_login(q): |
| | | raise web.HTTPFound("/login?err=1") |
| | | try: |
| | | user_id = int(q["id"]) |
| | | except (KeyError, ValueError): |
| | | raise web.HTTPFound("/login?err=1") |
| | | |
| | | ts = now_ts() |
| | | await db.upsert_web_user( |
| | | user_id, |
| | | q.get("first_name", ""), |
| | | q.get("last_name", ""), |
| | | q.get("username", ""), |
| | | q.get("photo_url", ""), |
| | | ts, |
| | | ) |
| | | token = await db.create_sess(user_id, ts, SESS_TTL) |
| | | resp = web.HTTPFound("/") |
| | | resp.set_cookie( |
| | | COOKIE, |
| | | token, |
| | | max_age=SESS_TTL, |
| | | httponly=True, |
| | | samesite="Lax", |
| | | secure=base_url(request).startswith("https"), |
| | | ) |
| | | return resp |
| | | |
| | | |
| | | async def logout(request) -> web.Response: |
| | | token = request.cookies.get(COOKIE) |
| | | if token: |
| | | await db.del_sess(token) |
| | | resp = web.HTTPFound("/login") |
| | | resp.del_cookie(COOKIE) |
| | | return resp |
| New file |
| | |
| | | import pathlib |
| | | |
| | | import jinja2 |
| | | from aiohttp import web |
| | | |
| | | BASE = pathlib.Path(__file__).resolve().parent |
| | | |
| | | ENV = jinja2.Environment( |
| | | loader=jinja2.FileSystemLoader(str(BASE / "templates")), |
| | | autoescape=jinja2.select_autoescape(["html"]), |
| | | trim_blocks=True, |
| | | lstrip_blocks=True, |
| | | ) |
| | | |
| | | |
| | | def render(request, name: str, active: str = "", **ctx) -> web.Response: |
| | | ctx.update(request=request, user=request.get("user"), active=active) |
| | | html = ENV.get_template(name).render(**ctx) |
| | | return web.Response(text=html, content_type="text/html") |
| New file |
| | |
| | | /* Небольшие доработки поверх Tailwind: шрифт и аккуратные скроллбары. */ |
| | | * { |
| | | font-family: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; |
| | | } |
| | | |
| | | ::-webkit-scrollbar { |
| | | width: 10px; |
| | | height: 10px; |
| | | } |
| | | |
| | | ::-webkit-scrollbar-thumb { |
| | | background: rgba(120, 120, 130, 0.4); |
| | | border-radius: 9999px; |
| | | } |
| | | |
| | | ::-webkit-scrollbar-track { |
| | | background: transparent; |
| | | } |
| New file |
| | |
| | | <!doctype html> |
| | | <html lang="ru" class="dark"> |
| | | <head> |
| | | <meta charset="utf-8"> |
| | | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| | | <title>{% block title %}Amadeus{% endblock %}</title> |
| | | <script> |
| | | // Применяем сохранённую тему до отрисовки, чтобы не мигало. |
| | | try { if (localStorage.getItem("amd-theme") === "light") document.documentElement.classList.remove("dark"); } catch (e) {} |
| | | </script> |
| | | <script src="https://cdn.tailwindcss.com"></script> |
| | | <script> |
| | | tailwind.config = { |
| | | darkMode: "class", |
| | | theme: { |
| | | extend: { |
| | | fontFamily: { sans: ["Geist", "ui-sans-serif", "system-ui", "sans-serif"] }, |
| | | colors: { |
| | | brand: { |
| | | 50: "#eef2ff", 100: "#e0e7ff", 200: "#c7d2fe", 300: "#a5b4fc", |
| | | 400: "#818cf8", 500: "#6366f1", 600: "#4f46e5", 700: "#4338ca", |
| | | 800: "#3730a3", 900: "#312e81" |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } |
| | | </script> |
| | | <link rel="preconnect" href="https://fonts.googleapis.com"> |
| | | <link href="https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700&display=swap" rel="stylesheet"> |
| | | <link rel="stylesheet" href="/static/style.css"> |
| | | </head> |
| | | <body class="min-h-screen bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100 font-sans antialiased"> |
| | | <div class="flex min-h-screen"> |
| | | <aside class="hidden md:flex w-64 shrink-0 flex-col border-r border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900"> |
| | | <div class="h-16 flex items-center gap-2 px-5 border-b border-gray-200 dark:border-gray-800"> |
| | | <span class="inline-flex h-8 w-8 items-center justify-center rounded-lg bg-brand-600 text-white font-bold">A</span> |
| | | <span class="text-lg font-semibold">Amadeus</span> |
| | | </div> |
| | | <nav class="flex-1 p-3 space-y-1 text-sm"> |
| | | {% set items = [ |
| | | ("dash", "/", "Дашборд"), |
| | | ("chats", "/chats", "Чаты"), |
| | | ("users", "/users", "Пользователи"), |
| | | ("captcha", "/captcha", "Активные капчи"), |
| | | ("log", "/log", "Журнал") |
| | | ] %} |
| | | {% for key, href, label in items %} |
| | | <a href="{{ href }}" |
| | | class="flex items-center rounded-lg px-3 py-2 transition |
| | | {% if active == key %}bg-brand-600 text-white shadow{% else %}text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800{% endif %}"> |
| | | {{ label }} |
| | | </a> |
| | | {% endfor %} |
| | | </nav> |
| | | <div class="p-3 border-t border-gray-200 dark:border-gray-800"> |
| | | <div class="flex items-center gap-3"> |
| | | {% if user and user.photo_url %} |
| | | <img src="{{ user.photo_url }}" class="h-9 w-9 rounded-full object-cover" alt=""> |
| | | {% else %} |
| | | <span class="inline-flex h-9 w-9 items-center justify-center rounded-full bg-gray-200 dark:bg-gray-700 text-sm font-medium"> |
| | | {{ (user.first_name or "?")[:1] }} |
| | | </span> |
| | | {% endif %} |
| | | <div class="min-w-0"> |
| | | <div class="truncate text-sm font-medium">{{ user.first_name or "Гость" }}</div> |
| | | <div class="truncate text-xs text-gray-500">{% if user.username %}@{{ user.username }}{% else %}id {{ user.user_id }}{% endif %}</div> |
| | | </div> |
| | | </div> |
| | | <a href="/logout" class="mt-3 block text-center rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 text-sm hover:bg-gray-100 dark:hover:bg-gray-800">Выйти</a> |
| | | </div> |
| | | </aside> |
| | | |
| | | <div class="flex-1 flex flex-col min-w-0"> |
| | | <header class="h-16 flex items-center justify-between gap-4 px-6 border-b border-gray-200 dark:border-gray-800 bg-white/70 dark:bg-gray-900/70 backdrop-blur"> |
| | | <h1 class="text-lg font-semibold truncate">{% block header %}{% endblock %}</h1> |
| | | <div class="flex items-center gap-2"> |
| | | <button id="theme-toggle" class="rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 text-sm hover:bg-gray-100 dark:hover:bg-gray-800">Тема</button> |
| | | <a href="/logout" class="md:hidden rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 text-sm">Выйти</a> |
| | | </div> |
| | | </header> |
| | | <main class="p-6 space-y-6"> |
| | | {% block content %}{% endblock %} |
| | | </main> |
| | | </div> |
| | | </div> |
| | | |
| | | <script> |
| | | // Переключатель тёмной/светлой темы. |
| | | document.getElementById("theme-toggle").addEventListener("click", function () { |
| | | const root = document.documentElement; |
| | | root.classList.toggle("dark"); |
| | | try { localStorage.setItem("amd-theme", root.classList.contains("dark") ? "dark" : "light"); } catch (e) {} |
| | | }); |
| | | </script> |
| | | </body> |
| | | </html> |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}Капчи - Amadeus{% endblock %} |
| | | {% block header %}Активные капчи{% endblock %} |
| | | {% block content %} |
| | | |
| | | <div class="overflow-hidden rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <table class="w-full text-sm"> |
| | | <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400"> |
| | | <tr> |
| | | <th class="px-5 py-3 text-left font-medium">Чат</th> |
| | | <th class="px-5 py-3 text-left font-medium">Пользователь</th> |
| | | <th class="px-5 py-3 text-left font-medium">Осталось</th> |
| | | </tr> |
| | | </thead> |
| | | <tbody class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for r in rows %} |
| | | <tr> |
| | | <td class="px-5 py-3">{{ names.get(r.chat_id, r.chat_id) }}</td> |
| | | <td class="px-5 py-3">{{ r.user_id }}</td> |
| | | <td class="px-5 py-3 text-gray-500">{{ r.left }} с</td> |
| | | </tr> |
| | | {% else %} |
| | | <tr><td colspan="3" class="px-5 py-8 text-center text-gray-500">Сейчас никто не проходит капчу.</td></tr> |
| | | {% endfor %} |
| | | </tbody> |
| | | </table> |
| | | </div> |
| | | |
| | | {% endblock %} |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}{{ chat.title or chat.chat_id }} - Amadeus{% endblock %} |
| | | {% block header %}{{ chat.title or chat.chat_id }}{% endblock %} |
| | | {% block content %} |
| | | |
| | | <div class="text-sm text-gray-500">id {{ chat.chat_id }} · {{ chat.type }}</div> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm"> |
| | | <h2 class="font-semibold mb-4">Настройки</h2> |
| | | <form method="post" action="/chats/cfg" class="grid md:grid-cols-3 gap-4"> |
| | | <input type="hidden" name="chat_id" value="{{ chat.chat_id }}"> |
| | | <label class="text-sm">Кнопок капчи |
| | | <input name="btn_count" type="number" min="1" max="9" value="{{ cfg.btn_count }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Таймаут, сек |
| | | <input name="timeout" type="number" min="5" max="300" value="{{ cfg.timeout }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Попыток до наказания |
| | | <input name="max_attempts" type="number" min="1" max="10" value="{{ cfg.max_attempts }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Лимит варнов |
| | | <input name="warn_limit" type="number" min="1" max="10" value="{{ cfg.warn_limit }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Действие при лимите |
| | | <select name="warn_action" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | <option value="mute" {% if cfg.warn_action == "mute" %}selected{% endif %}>мут</option> |
| | | <option value="ban" {% if cfg.warn_action == "ban" %}selected{% endif %}>бан</option> |
| | | </select> |
| | | </label> |
| | | <label class="text-sm">Длительность наказания, сек |
| | | <input name="warn_duration" type="number" min="0" max="2592000" value="{{ cfg.warn_duration }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <div class="md:col-span-3"> |
| | | <button class="rounded-lg bg-brand-600 hover:bg-brand-700 px-4 py-2 text-sm font-medium text-white">Сохранить</button> |
| | | </div> |
| | | </form> |
| | | </section> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Права администраторов</div> |
| | | <div class="overflow-x-auto"> |
| | | <table class="w-full text-sm whitespace-nowrap"> |
| | | <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400"> |
| | | <tr> |
| | | <th class="px-4 py-3 text-left font-medium">Администратор</th> |
| | | {% for key, label in labels.items() %} |
| | | <th class="px-4 py-3 text-left font-medium">{{ label }}</th> |
| | | {% endfor %} |
| | | </tr> |
| | | </thead> |
| | | <tbody class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for a in admins %} |
| | | <tr> |
| | | <td class="px-4 py-3"> |
| | | <div class="font-medium">{{ a.name }}</div> |
| | | <div class="text-xs text-gray-500">id {{ a.id }}{% if a.username %} · @{{ a.username }}{% endif %}</div> |
| | | </td> |
| | | {% for key, label in labels.items() %} |
| | | <td class="px-4 py-3"> |
| | | <form method="post" action="/chats/perm" class="inline"> |
| | | <input type="hidden" name="chat_id" value="{{ chat.chat_id }}"> |
| | | <input type="hidden" name="user_id" value="{{ a.id }}"> |
| | | <input type="hidden" name="perm" value="{{ key }}"> |
| | | <input type="hidden" name="allow" value="{{ 0 if a.perms[key] else 1 }}"> |
| | | <button class="rounded-md px-2 py-1 text-xs font-medium border |
| | | {% if a.perms[key] %}border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300{% else %}border-gray-300 bg-gray-50 text-gray-500 dark:border-gray-700 dark:bg-gray-800{% endif %}"> |
| | | {% if a.perms[key] %}вкл{% else %}выкл{% endif %} |
| | | </button> |
| | | </form> |
| | | </td> |
| | | {% endfor %} |
| | | </tr> |
| | | {% else %} |
| | | <tr><td class="px-4 py-6 text-gray-500" colspan="9">Не удалось получить список администраторов.</td></tr> |
| | | {% endfor %} |
| | | </tbody> |
| | | </table> |
| | | </div> |
| | | </section> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm"> |
| | | <h2 class="font-semibold mb-4">Применить действие</h2> |
| | | <form method="post" action="/action" class="grid md:grid-cols-5 gap-4 items-end"> |
| | | <input type="hidden" name="chat_id" value="{{ chat.chat_id }}"> |
| | | <input type="hidden" name="back" value="/chats/{{ chat.chat_id }}"> |
| | | <label class="text-sm">ID пользователя |
| | | <input name="user_id" type="number" required class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Имя (необязательно) |
| | | <input name="name" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Действие |
| | | <select name="kind" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | <option value="warn">варн</option> |
| | | <option value="mute">мут</option> |
| | | <option value="ban">бан</option> |
| | | <option value="unmute">размут</option> |
| | | <option value="unban">разбан</option> |
| | | <option value="unwarn">снять варн</option> |
| | | </select> |
| | | </label> |
| | | <label class="text-sm">Время (10m, 1h, -, пусто) |
| | | <input name="dur" placeholder="-" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Причина |
| | | <input name="reason" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <div class="md:col-span-5"> |
| | | <button class="rounded-lg bg-brand-600 hover:bg-brand-700 px-4 py-2 text-sm font-medium text-white">Выполнить</button> |
| | | </div> |
| | | </form> |
| | | </section> |
| | | |
| | | <div class="grid lg:grid-cols-2 gap-6"> |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Предупреждения</div> |
| | | <div class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for w in warns %} |
| | | <div class="px-5 py-3 text-sm flex items-center justify-between"> |
| | | <span><a class="text-brand-500 hover:underline" href="/users/{{ chat.chat_id }}/{{ w.user_id }}">{{ w.user_id }}</a> · {{ w.reason or "без причины" }}</span> |
| | | <span class="text-gray-500">{{ fmt_dt(w.created_at) }}</span> |
| | | </div> |
| | | {% else %} |
| | | <div class="px-5 py-6 text-sm text-gray-500">Нет предупреждений.</div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">История наказаний</div> |
| | | <div class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for p in punish %} |
| | | <div class="px-5 py-3 text-sm flex items-center justify-between"> |
| | | <span> |
| | | {{ "мут" if p.kind == "mute" else "бан" }} · |
| | | <a class="text-brand-500 hover:underline" href="/users/{{ chat.chat_id }}/{{ p.user_id }}">{{ p.user_id }}</a> |
| | | · {{ fmt_dur(p.until) if p.until else "бессрочно" }} |
| | | {% if not p.active %}<span class="text-xs text-gray-400">(снято)</span>{% endif %} |
| | | </span> |
| | | <span class="text-gray-500">{{ fmt_dt(p.created_at) }}</span> |
| | | </div> |
| | | {% else %} |
| | | <div class="px-5 py-6 text-sm text-gray-500">Наказаний нет.</div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | </div> |
| | | |
| | | {% endblock %} |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}Чаты - Amadeus{% endblock %} |
| | | {% block header %}Чаты{% endblock %} |
| | | {% block content %} |
| | | |
| | | <div class="overflow-hidden rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <table class="w-full text-sm"> |
| | | <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400"> |
| | | <tr> |
| | | <th class="px-5 py-3 text-left font-medium">Чат</th> |
| | | <th class="px-5 py-3 text-left font-medium">Капча</th> |
| | | <th class="px-5 py-3 text-left font-medium">Варны</th> |
| | | <th class="px-5 py-3 text-right font-medium"></th> |
| | | </tr> |
| | | </thead> |
| | | <tbody class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for c in chats %} |
| | | {% set cfg = cfgs.get(c.chat_id) %} |
| | | <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50"> |
| | | <td class="px-5 py-3"> |
| | | <div class="font-medium">{{ c.title or c.chat_id }}</div> |
| | | <div class="text-xs text-gray-500">id {{ c.chat_id }} · {{ c.type }}</div> |
| | | </td> |
| | | <td class="px-5 py-3 text-gray-500">{{ cfg.btn_count }} кнопки · {{ cfg.timeout }} с · {{ cfg.max_attempts }} попытки</td> |
| | | <td class="px-5 py-3 text-gray-500">{{ cfg.warn_limit }} · {{ "бан" if cfg.warn_action == "ban" else "мут" }}</td> |
| | | <td class="px-5 py-3 text-right"> |
| | | <a href="/chats/{{ c.chat_id }}" class="rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 hover:bg-gray-100 dark:hover:bg-gray-800">Открыть</a> |
| | | </td> |
| | | </tr> |
| | | {% else %} |
| | | <tr><td colspan="4" class="px-5 py-8 text-center text-gray-500">Нет доступных чатов.</td></tr> |
| | | {% endfor %} |
| | | </tbody> |
| | | </table> |
| | | </div> |
| | | |
| | | {% endblock %} |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}Дашборд - Amadeus{% endblock %} |
| | | {% block header %}Дашборд{% endblock %} |
| | | {% block content %} |
| | | |
| | | <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4"> |
| | | {% set cards = [ |
| | | ("Чатов", st.chats, "text-brand-500"), |
| | | ("Варнов", st.warns, "text-amber-500"), |
| | | ("Мутов", st.mutes, "text-orange-500"), |
| | | ("Банов", st.bans, "text-red-500"), |
| | | ("Капч сейчас", captchas|length, "text-emerald-500"), |
| | | ("Записей в журнале", st.logs, "text-gray-500") |
| | | ] %} |
| | | {% for label, value, color in cards %} |
| | | <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4 shadow-sm"> |
| | | <div class="text-sm text-gray-500 dark:text-gray-400">{{ label }}</div> |
| | | <div class="mt-1 text-2xl font-bold {{ color }}">{{ value }}</div> |
| | | </div> |
| | | {% endfor %} |
| | | </div> |
| | | |
| | | <div class="grid lg:grid-cols-2 gap-6"> |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Активные капчи</div> |
| | | <div class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for c in captchas %} |
| | | <div class="px-5 py-3 flex items-center justify-between text-sm"> |
| | | <span>Чат {{ names.get(c.chat_id, c.chat_id) }} · пользователь {{ c.user_id }}</span> |
| | | <span class="text-gray-500">осталось {{ c.left }} с</span> |
| | | </div> |
| | | {% else %} |
| | | <div class="px-5 py-6 text-sm text-gray-500">Нет активных капч.</div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Последние действия</div> |
| | | <div class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for r in logs %} |
| | | <div class="px-5 py-3 text-sm flex items-center justify-between"> |
| | | <span>{{ r.action }} · {{ names.get(r.chat_id, r.chat_id) }}</span> |
| | | <span class="text-gray-500">{{ r.target_id }}</span> |
| | | </div> |
| | | {% else %} |
| | | <div class="px-5 py-6 text-sm text-gray-500">Журнал пуст.</div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | </div> |
| | | |
| | | {% endblock %} |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}Журнал - Amadeus{% endblock %} |
| | | {% block header %}Журнал модерации{% endblock %} |
| | | {% block content %} |
| | | |
| | | <div class="overflow-hidden rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <table class="w-full text-sm"> |
| | | <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400"> |
| | | <tr> |
| | | <th class="px-5 py-3 text-left font-medium">Время</th> |
| | | <th class="px-5 py-3 text-left font-medium">Чат</th> |
| | | <th class="px-5 py-3 text-left font-medium">Действие</th> |
| | | <th class="px-5 py-3 text-left font-medium">Админ</th> |
| | | <th class="px-5 py-3 text-left font-medium">Цель</th> |
| | | <th class="px-5 py-3 text-left font-medium">Причина</th> |
| | | </tr> |
| | | </thead> |
| | | <tbody class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for r in rows %} |
| | | <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50"> |
| | | <td class="px-5 py-3 text-gray-500">{{ fmt_dt(r.created_at) }}</td> |
| | | <td class="px-5 py-3">{{ names.get(r.chat_id, r.chat_id) }}</td> |
| | | <td class="px-5 py-3">{{ r.action }}</td> |
| | | <td class="px-5 py-3">{{ r.admin_id }}</td> |
| | | <td class="px-5 py-3">{{ r.target_id }}</td> |
| | | <td class="px-5 py-3">{{ r.reason or "-" }}</td> |
| | | </tr> |
| | | {% else %} |
| | | <tr><td colspan="6" class="px-5 py-8 text-center text-gray-500">Журнал пуст.</td></tr> |
| | | {% endfor %} |
| | | </tbody> |
| | | </table> |
| | | </div> |
| | | |
| | | {% endblock %} |
| New file |
| | |
| | | <!doctype html> |
| | | <html lang="ru" class="dark"> |
| | | <head> |
| | | <meta charset="utf-8"> |
| | | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| | | <title>Вход - Amadeus</title> |
| | | <script src="https://cdn.tailwindcss.com"></script> |
| | | <script> |
| | | tailwind.config = { darkMode: "class", theme: { extend: { fontFamily: { sans: ["Geist", "system-ui", "sans-serif"] }, colors: { brand: { 500: "#6366f1", 600: "#4f46e5", 700: "#4338ca" } } } } } |
| | | </script> |
| | | <link href="https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700&display=swap" rel="stylesheet"> |
| | | </head> |
| | | <body class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950 font-sans text-gray-900 dark:text-gray-100"> |
| | | <div class="relative w-full max-w-sm overflow-hidden rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-8 shadow-lg"> |
| | | <div class="pointer-events-none absolute -top-20 -right-20 h-48 w-48 rounded-full bg-brand-500/20 blur-3xl"></div> |
| | | <div class="relative"> |
| | | <span class="inline-flex h-12 w-12 items-center justify-center rounded-xl bg-brand-600 text-xl font-bold text-white">A</span> |
| | | <h1 class="mt-4 text-xl font-semibold">Панель Amadeus</h1> |
| | | <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Войдите через Telegram, чтобы управлять чатами.</p> |
| | | |
| | | {% if request.query.get("err") %} |
| | | <div class="mt-4 rounded-lg border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-800 dark:bg-red-950/50 dark:text-red-300"> |
| | | Не удалось войти. Попробуйте ещё раз. |
| | | </div> |
| | | {% endif %} |
| | | |
| | | <div class="mt-6 flex justify-center"> |
| | | <script async src="https://telegram.org/js/telegram-widget.js?22" |
| | | data-telegram-login="{{ bot_username }}" |
| | | data-size="large" |
| | | data-radius="10" |
| | | data-auth-url="{{ auth_url }}" |
| | | data-request-access="write"></script> |
| | | </div> |
| | | |
| | | {% if not bot_username %} |
| | | <p class="mt-4 text-center text-xs text-amber-500">Имя бота не загружено. Проверьте соединение с Telegram.</p> |
| | | {% endif %} |
| | | </div> |
| | | </div> |
| | | </body> |
| | | </html> |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}Пользователь {{ target_id }} - Amadeus{% endblock %} |
| | | {% block header %}Пользователь {{ target_id }}{% endblock %} |
| | | {% block content %} |
| | | |
| | | <div class="text-sm text-gray-500">{{ chat.title or chat.chat_id }} (id {{ chat.chat_id }})</div> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm"> |
| | | <h2 class="font-semibold mb-4">Действие</h2> |
| | | <form method="post" action="/action" class="grid md:grid-cols-4 gap-4 items-end"> |
| | | <input type="hidden" name="chat_id" value="{{ chat.chat_id }}"> |
| | | <input type="hidden" name="user_id" value="{{ target_id }}"> |
| | | <input type="hidden" name="back" value="/users/{{ chat.chat_id }}/{{ target_id }}"> |
| | | <label class="text-sm">Действие |
| | | <select name="kind" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | <option value="warn">варн</option> |
| | | <option value="mute">мут</option> |
| | | <option value="ban">бан</option> |
| | | <option value="unmute">размут</option> |
| | | <option value="unban">разбан</option> |
| | | <option value="unwarn">снять варн</option> |
| | | </select> |
| | | </label> |
| | | <label class="text-sm">Время (10m, 1h, -) |
| | | <input name="dur" placeholder="-" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <label class="text-sm">Причина |
| | | <input name="reason" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2"> |
| | | </label> |
| | | <button class="rounded-lg bg-brand-600 hover:bg-brand-700 px-4 py-2 text-sm font-medium text-white">Выполнить</button> |
| | | </form> |
| | | </section> |
| | | |
| | | <div class="grid lg:grid-cols-2 gap-6"> |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Предупреждения</div> |
| | | <div class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for w in warns %} |
| | | <div class="px-5 py-3 text-sm flex items-center justify-between"> |
| | | <span>{{ w.reason or "без причины" }}</span> |
| | | <span class="text-gray-500">{{ fmt_dt(w.created_at) }}</span> |
| | | </div> |
| | | {% else %} |
| | | <div class="px-5 py-6 text-sm text-gray-500">Нет предупреждений.</div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">История наказаний</div> |
| | | <div class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for p in hist %} |
| | | <div class="px-5 py-3 text-sm flex items-center justify-between"> |
| | | <span>{{ "мут" if p.kind == "mute" else "бан" }} · {{ fmt_dur(p.until) if p.until else "бессрочно" }} {% if not p.active %}<span class="text-xs text-gray-400">(снято)</span>{% endif %}</span> |
| | | <span class="text-gray-500">{{ fmt_dt(p.created_at) }}</span> |
| | | </div> |
| | | {% else %} |
| | | <div class="px-5 py-6 text-sm text-gray-500">История пуста.</div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | </div> |
| | | |
| | | {% endblock %} |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}Пользователи - Amadeus{% endblock %} |
| | | {% block header %}Пользователи{% endblock %} |
| | | {% block content %} |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Активные наказания</div> |
| | | <div class="overflow-x-auto"> |
| | | <table class="w-full text-sm"> |
| | | <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400"> |
| | | <tr> |
| | | <th class="px-5 py-3 text-left font-medium">Пользователь</th> |
| | | <th class="px-5 py-3 text-left font-medium">Чат</th> |
| | | <th class="px-5 py-3 text-left font-medium">Тип</th> |
| | | <th class="px-5 py-3 text-left font-medium">Срок</th> |
| | | <th class="px-5 py-3 text-left font-medium">Выдан</th> |
| | | </tr> |
| | | </thead> |
| | | <tbody class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for p in rows %} |
| | | <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50"> |
| | | <td class="px-5 py-3"> |
| | | <a class="text-brand-500 hover:underline" href="/users/{{ p.chat_id }}/{{ p.user_id }}">{{ p.user_id }}</a> |
| | | <div class="text-xs text-gray-500">{{ p.reason or "-" }}</div> |
| | | </td> |
| | | <td class="px-5 py-3">{{ names.get(p.chat_id, p.chat_id) }}</td> |
| | | <td class="px-5 py-3">{{ "мут" if p.kind == "mute" else "бан" }}</td> |
| | | <td class="px-5 py-3">{{ fmt_dur(p.until) if p.until else "бессрочно" }}</td> |
| | | <td class="px-5 py-3 text-gray-500">{{ fmt_dt(p.created_at) }}</td> |
| | | </tr> |
| | | {% else %} |
| | | <tr><td colspan="5" class="px-5 py-8 text-center text-gray-500">Активных наказаний нет.</td></tr> |
| | | {% endfor %} |
| | | </tbody> |
| | | </table> |
| | | </div> |
| | | </section> |
| | | |
| | | <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm"> |
| | | <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Предупреждения</div> |
| | | <div class="overflow-x-auto"> |
| | | <table class="w-full text-sm"> |
| | | <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400"> |
| | | <tr> |
| | | <th class="px-5 py-3 text-left font-medium">Пользователь</th> |
| | | <th class="px-5 py-3 text-left font-medium">Чат</th> |
| | | <th class="px-5 py-3 text-left font-medium">Причина</th> |
| | | <th class="px-5 py-3 text-left font-medium">Добавлен</th> |
| | | </tr> |
| | | </thead> |
| | | <tbody class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for w in warns %} |
| | | <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50"> |
| | | <td class="px-5 py-3"><a class="text-brand-500 hover:underline" href="/users/{{ w.chat_id }}/{{ w.user_id }}">{{ w.user_id }}</a></td> |
| | | <td class="px-5 py-3">{{ names.get(w.chat_id, w.chat_id) }}</td> |
| | | <td class="px-5 py-3">{{ w.reason or "-" }}</td> |
| | | <td class="px-5 py-3 text-gray-500">{{ fmt_dt(w.created_at) }}</td> |
| | | </tr> |
| | | {% else %} |
| | | <tr><td colspan="4" class="px-5 py-8 text-center text-gray-500">Предупреждений нет.</td></tr> |
| | | {% endfor %} |
| | | </tbody> |
| | | </table> |
| | | </div> |
| | | </section> |
| | | |
| | | {% endblock %} |
| New file |
| | |
| | | from aiohttp import web |
| | | |
| | | import db |
| | | import mod |
| | | import perms as pm |
| | | from captcha import CAP_STATE |
| | | from cfg import bot |
| | | from perms import P_BAN, P_CFG, P_MUTE, P_PERMS, P_UNBAN, P_UNMUTE, P_UNWARN, P_WARN, PERM_LABELS |
| | | from util import fmt_dt, fmt_dur, now_ts, parse_dur |
| | | from web.auth import is_staff |
| | | from web.render import render |
| | | |
| | | # Соответствие действия и требуемого права. |
| | | ACTION_PERM = { |
| | | "warn": P_WARN, |
| | | "mute": P_MUTE, |
| | | "ban": P_BAN, |
| | | "unmute": P_UNMUTE, |
| | | "unban": P_UNBAN, |
| | | "unwarn": P_UNWARN, |
| | | } |
| | | |
| | | |
| | | async def allowed_chats(user_id: int): |
| | | if is_staff(user_id): |
| | | return await db.list_chats(active_only=True) |
| | | return await pm.adm_chats(bot, user_id) |
| | | |
| | | |
| | | async def _allowed_ids(user_id: int) -> set: |
| | | return {c["chat_id"] for c in await allowed_chats(user_id)} |
| | | |
| | | |
| | | async def _user(request) -> dict: |
| | | return request["user"] |
| | | |
| | | |
| | | async def dashboard(request) -> web.Response: |
| | | user = await _user(request) |
| | | chats = await allowed_chats(user["user_id"]) |
| | | ids = {c["chat_id"] for c in chats} |
| | | names = {c["chat_id"]: c["title"] for c in chats} |
| | | st = await db.stats(now_ts()) |
| | | captchas = [ |
| | | {"chat_id": k[0], "user_id": k[1], "left": max(0, v.get("deadline", 0) - now_ts())} |
| | | for k, v in CAP_STATE.items() |
| | | if k[0] in ids |
| | | ] |
| | | logs = [row for row in await db.list_log(limit=300) if row["chat_id"] in ids][:10] |
| | | return render( |
| | | request, "dashboard.html", active="dash", st=st, captchas=captchas, logs=logs, names=names |
| | | ) |
| | | |
| | | |
| | | async def chats_page(request) -> web.Response: |
| | | user = await _user(request) |
| | | chats = await allowed_chats(user["user_id"]) |
| | | cfgs = {c["chat_id"]: await db.get_chat_cfg(c["chat_id"]) for c in chats} |
| | | return render(request, "chats.html", active="chats", chats=chats, cfgs=cfgs) |
| | | |
| | | |
| | | async def chat_page(request) -> web.Response: |
| | | user = await _user(request) |
| | | chat_id = int(request.match_info["chat_id"]) |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | raise web.HTTPForbidden() |
| | | chat = await db.get_chat(chat_id) or {"chat_id": chat_id, "title": str(chat_id)} |
| | | cfg = await db.get_chat_cfg(chat_id) |
| | | |
| | | admins = [] |
| | | try: |
| | | for m in await bot.get_chat_administrators(chat_id): |
| | | u = m.user |
| | | admins.append( |
| | | { |
| | | "id": u.id, |
| | | "name": u.full_name, |
| | | "username": u.username or "", |
| | | "perms": await pm.perms_of(chat_id, u.id), |
| | | } |
| | | ) |
| | | except Exception: |
| | | pass |
| | | |
| | | warns = await db.list_warns(chat_id) |
| | | punish = await db.list_punish(chat_id, active_only=False) |
| | | return render( |
| | | request, |
| | | "chat.html", |
| | | active="chats", |
| | | chat=chat, |
| | | cfg=cfg, |
| | | admins=admins, |
| | | warns=warns, |
| | | punish=punish, |
| | | labels=PERM_LABELS, |
| | | fmt_dt=fmt_dt, |
| | | fmt_dur=fmt_dur, |
| | | ) |
| | | |
| | | |
| | | async def chat_cfg(request) -> web.Response: |
| | | user = await _user(request) |
| | | data = await request.post() |
| | | chat_id = int(data["chat_id"]) |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | raise web.HTTPForbidden() |
| | | if not await pm.check_perm(chat_id, user["user_id"], P_CFG): |
| | | raise web.HTTPForbidden() |
| | | try: |
| | | fields = { |
| | | "btn_count": int(data["btn_count"]), |
| | | "timeout": int(data["timeout"]), |
| | | "max_attempts": int(data["max_attempts"]), |
| | | "warn_limit": int(data["warn_limit"]), |
| | | "warn_action": data["warn_action"], |
| | | "warn_duration": int(data["warn_duration"]), |
| | | } |
| | | except (KeyError, ValueError): |
| | | raise web.HTTPFound(f"/chats/{chat_id}?err=cfg") |
| | | if fields["warn_action"] not in ("mute", "ban"): |
| | | fields["warn_action"] = "mute" |
| | | await db.save_chat_cfg(chat_id, **fields) |
| | | raise web.HTTPFound(f"/chats/{chat_id}") |
| | | |
| | | |
| | | async def chat_perm(request) -> web.Response: |
| | | user = await _user(request) |
| | | data = await request.post() |
| | | chat_id = int(data["chat_id"]) |
| | | target_id = int(data["user_id"]) |
| | | perm = data["perm"] |
| | | allow = data.get("allow") == "1" |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | raise web.HTTPForbidden() |
| | | if perm not in PERM_LABELS: |
| | | raise web.HTTPFound(f"/chats/{chat_id}") |
| | | await pm.set_perm(chat_id, user["user_id"], target_id, perm, allow) |
| | | raise web.HTTPFound(f"/chats/{chat_id}") |
| | | |
| | | |
| | | async def users_page(request) -> web.Response: |
| | | user = await _user(request) |
| | | chats = await allowed_chats(user["user_id"]) |
| | | names = {c["chat_id"]: c["title"] for c in chats} |
| | | rows = [] |
| | | for c in chats: |
| | | for p in await db.list_punish(c["chat_id"], active_only=True): |
| | | rows.append(p) |
| | | warns = [] |
| | | for c in chats: |
| | | warns.extend(await db.list_warns(c["chat_id"])) |
| | | return render( |
| | | request, "users.html", active="users", rows=rows, warns=warns, names=names, fmt_dt=fmt_dt, fmt_dur=fmt_dur |
| | | ) |
| | | |
| | | |
| | | async def user_page(request) -> web.Response: |
| | | user = await _user(request) |
| | | chat_id = int(request.match_info["chat_id"]) |
| | | target_id = int(request.match_info["user_id"]) |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | raise web.HTTPForbidden() |
| | | chat = await db.get_chat(chat_id) or {"chat_id": chat_id, "title": str(chat_id)} |
| | | warns = await db.list_warns(chat_id, target_id) |
| | | hist = await db.hist_punish(chat_id, target_id) |
| | | return render( |
| | | request, |
| | | "user.html", |
| | | active="users", |
| | | chat=chat, |
| | | target_id=target_id, |
| | | warns=warns, |
| | | hist=hist, |
| | | fmt_dt=fmt_dt, |
| | | fmt_dur=fmt_dur, |
| | | ) |
| | | |
| | | |
| | | async def action(request) -> web.Response: |
| | | user = await _user(request) |
| | | data = await request.post() |
| | | chat_id = int(data["chat_id"]) |
| | | target_id = int(data["user_id"]) |
| | | kind = data.get("kind", "") |
| | | reason = (data.get("reason") or "").strip() |
| | | name = (data.get("name") or str(target_id)).strip() |
| | | back = data.get("back") or f"/chats/{chat_id}" |
| | | |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | raise web.HTTPForbidden() |
| | | if kind not in ACTION_PERM: |
| | | raise web.HTTPFound(back) |
| | | if not await pm.check_perm(chat_id, user["user_id"], ACTION_PERM[kind]): |
| | | raise web.HTTPForbidden() |
| | | |
| | | if kind in ("mute", "ban"): |
| | | try: |
| | | dur = parse_dur(data.get("dur") or "-") |
| | | except ValueError: |
| | | dur = None |
| | | else: |
| | | dur = None |
| | | |
| | | actor = user["user_id"] |
| | | if kind == "warn": |
| | | await mod.apply_warn(chat_id, target_id, name, actor, reason) |
| | | elif kind == "mute": |
| | | await mod.apply_mute(chat_id, target_id, name, dur, actor, reason) |
| | | elif kind == "ban": |
| | | await mod.apply_ban(chat_id, target_id, name, dur, actor, reason) |
| | | elif kind == "unmute": |
| | | await mod.apply_unmute(chat_id, target_id, name, actor, reason) |
| | | elif kind == "unban": |
| | | await mod.apply_unban(chat_id, target_id, name, actor, reason) |
| | | elif kind == "unwarn": |
| | | await mod.apply_unwarn(chat_id, target_id, name, actor) |
| | | raise web.HTTPFound(back) |
| | | |
| | | |
| | | async def captcha_page(request) -> web.Response: |
| | | user = await _user(request) |
| | | chats = await allowed_chats(user["user_id"]) |
| | | names = {c["chat_id"]: c["title"] for c in chats} |
| | | ids = set(names) |
| | | rows = [ |
| | | {"chat_id": k[0], "user_id": k[1], "left": max(0, v.get("deadline", 0) - now_ts())} |
| | | for k, v in CAP_STATE.items() |
| | | if k[0] in ids |
| | | ] |
| | | return render(request, "captcha.html", active="captcha", rows=rows, names=names) |
| | | |
| | | |
| | | async def log_page(request) -> web.Response: |
| | | user = await _user(request) |
| | | chats = await allowed_chats(user["user_id"]) |
| | | names = {c["chat_id"]: c["title"] for c in chats} |
| | | ids = set(names) |
| | | rows = [r for r in await db.list_log(limit=500) if r["chat_id"] in ids][:200] |
| | | return render(request, "log.html", active="log", rows=rows, names=names, fmt_dt=fmt_dt) |