Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1717 lines
68 KiB
Python
1717 lines
68 KiB
Python
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import inspect
|
||
import json
|
||
import logging
|
||
from datetime import datetime, timezone
|
||
import os
|
||
import re
|
||
import sqlite3
|
||
import threading
|
||
import time
|
||
from pathlib import Path
|
||
from typing import Any, NamedTuple
|
||
|
||
import aiohttp
|
||
from aiogram.types import ChatPermissions, InlineKeyboardButton, InlineKeyboardMarkup
|
||
|
||
import account_admin
|
||
|
||
log = logging.getLogger("moderation-bridge")
|
||
|
||
TOKEN_ENV = "IISHKO_MODERATION_TOKEN"
|
||
URL_ENV = "IISHKO_MODERATION_URL"
|
||
AUTH_HEADER = "X-Moderation-Token"
|
||
DEFAULT_PLAN_URL = "http://127.0.0.1:48003/v1/plan"
|
||
|
||
HTTP_TIMEOUT = 2.0
|
||
MAX_BODY_BYTES = 65536
|
||
MAX_REQUEST_BYTES = 65536
|
||
MAX_CANDIDATES = 50
|
||
|
||
DEFAULT_MUTE_SECONDS = 3600
|
||
MIN_MUTE_SECONDS = 30
|
||
MAX_MUTE_SECONDS = 365 * 24 * 3600
|
||
# Telegram treats a restriction shorter than 30s as "forever"; stay above it.
|
||
SAFE_MUTE_MIN_SECONDS = 31
|
||
|
||
SEEN_RETENTION_SECONDS = 30 * 24 * 3600
|
||
SEEN_MAX_ROWS_PER_CHAT = 5000
|
||
SEEN_PRUNE_INTERVAL_SECONDS = 600
|
||
|
||
DB_TIMEOUT = 2.0
|
||
|
||
MODERATION_COMMANDS = ("ban", "unban", "mute", "unmute", "kick")
|
||
ALL_COMMANDS = MODERATION_COMMANDS + ("setup", "chatmode")
|
||
|
||
CHAT_MODES = ("addressed", "quiet", "normal")
|
||
DEFAULT_CHAT_MODE = "addressed"
|
||
# User-facing mode -> token accepted by the Go policy service.
|
||
MODE_TO_GO = {
|
||
"addressed": "mentions",
|
||
"mentions": "mentions",
|
||
"quiet": "quiet",
|
||
"normal": "replies",
|
||
"replies": "replies",
|
||
}
|
||
MODE_FROM_GO = {"mentions": "addressed", "quiet": "quiet", "replies": "normal"}
|
||
|
||
MANAGE_FIELDS = frozenset(
|
||
("can_change_info", "can_invite_users", "can_pin_messages", "can_manage_topics")
|
||
)
|
||
PERMISSION_FIELDS = tuple(ChatPermissions.model_fields)
|
||
|
||
MSG_UNAVAILABLE = (
|
||
"Модерация недоступна: сервис политики не отвечает. Действие не выполнено."
|
||
)
|
||
MSG_NO_DB = "Модерация недоступна: не настроены пути к базе бота и шлюза."
|
||
MSG_ADMIN_ONLY = "Команда доступна только администраторам чата."
|
||
MSG_OWNER_ONLY = "Команда доступна только владельцу бота."
|
||
MSG_BOT_RIGHTS = "Бот должен быть администратором чата."
|
||
MSG_BOT_RESTRICT = "Дайте боту право «Ограничивать участников»."
|
||
|
||
# Private /ban|/unban targets: explicit ID/@username or the replied author.
|
||
MSG_ACCOUNT_USAGE = "Укажите пользователя: ID, @username или ответом на его сообщение."
|
||
MSG_ACCOUNT_ID = "ID должен быть положительным 64-битным числом: 1…9223372036854775807."
|
||
MSG_ACCOUNT_AMBIGUOUS = (
|
||
"Несколько аккаунтов с @%s — укажи ID: по имени нельзя выбрать одного."
|
||
)
|
||
MSG_ACCOUNT_NOT_FOUND = "Пользователь @%s не найден в базе бота."
|
||
MSG_ACCOUNT_REPLY_ANON = "Ответь на сообщение самого пользователя (не канала и не анонима)."
|
||
MSG_ACCOUNT_REPLY_FORWARDED = "Ответь на сообщение пользователя, а не на пересланное."
|
||
MSG_ACCOUNT_REPLY_BOT = "Ответь на сообщение пользователя, а не бота."
|
||
MSG_ACCOUNT_UNREADABLE = "Не удалось прочитать аккаунты бота. Действие не выполнено."
|
||
TG_ID_MAX = 9223372036854775807
|
||
|
||
|
||
class PlannerError(Exception):
|
||
"""Base class for fail-closed planner failures."""
|
||
|
||
|
||
class PlannerRejected(PlannerError):
|
||
"""The policy service rejected the request; the message is user-facing."""
|
||
|
||
|
||
class PlannerUnavailable(PlannerError):
|
||
"""The policy service is not configured, unreachable or malformed."""
|
||
|
||
|
||
class TargetResolution(NamedTuple):
|
||
uid: int
|
||
label: str
|
||
error: str
|
||
|
||
|
||
_COMMAND_RE = re.compile(
|
||
r"^/(?P<name>[A-Za-z0-9_]{1,64})(?:@(?P<mention>[A-Za-z0-9_]{1,64}))?"
|
||
r"(?:\s+(?P<rest>.*))?$",
|
||
re.DOTALL,
|
||
)
|
||
_USERNAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]{2,31}$")
|
||
|
||
|
||
def _ascii_lower(value: Any) -> str:
|
||
text = "" if value is None else str(value)
|
||
return text.translate(str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"))
|
||
|
||
|
||
def _norm_username(value: Any) -> str:
|
||
text = _ascii_lower(value).strip()
|
||
if text.startswith("@"):
|
||
text = text[1:]
|
||
if not text or len(text) > 64:
|
||
return ""
|
||
if any(ch not in "abcdefghijklmnopqrstuvwxyz0123456789_" for ch in text):
|
||
return ""
|
||
return text
|
||
|
||
|
||
def _display_name(user: Any) -> str:
|
||
parts = [getattr(user, "first_name", None), getattr(user, "last_name", None)]
|
||
name = " ".join(str(p).strip() for p in parts if p)
|
||
name = " ".join(name.split())
|
||
return name[:128]
|
||
|
||
|
||
def _status(member: Any) -> str:
|
||
value = getattr(member, "status", "")
|
||
return str(getattr(value, "value", value) or "")
|
||
|
||
|
||
def _chat_type(chat: Any) -> str:
|
||
value = getattr(chat, "type", "")
|
||
return str(getattr(value, "value", value) or "")
|
||
|
||
|
||
def _bits_from_permissions(perms: Any, missing: bool) -> dict:
|
||
if perms is None:
|
||
return {field: missing for field in PERMISSION_FIELDS}
|
||
out = {}
|
||
for field in PERMISSION_FIELDS:
|
||
value = getattr(perms, field, None)
|
||
out[field] = missing if value is None else bool(value)
|
||
return out
|
||
|
||
|
||
def _as_timestamp(value: Any) -> int:
|
||
"""aiogram exposes until_date as datetime; tolerate int/str/None."""
|
||
if value is None:
|
||
return 0
|
||
if isinstance(value, datetime):
|
||
if value.tzinfo is None:
|
||
value = value.replace(tzinfo=timezone.utc)
|
||
try:
|
||
return int(value.timestamp())
|
||
except (OverflowError, OSError, ValueError):
|
||
return 0
|
||
try:
|
||
return int(value)
|
||
except (TypeError, ValueError):
|
||
return 0
|
||
|
||
|
||
def _member_bits(member: Any):
|
||
"""Permission bits of a ChatMemberRestricted (flat fields, no .permissions)."""
|
||
if member is None:
|
||
return None
|
||
nested = getattr(member, "permissions", None)
|
||
if nested is not None:
|
||
return _bits_from_permissions(nested, False)
|
||
if _status(member) != "restricted":
|
||
return None
|
||
return {field: bool(getattr(member, field, False)) for field in PERMISSION_FIELDS}
|
||
|
||
|
||
def _human_duration(seconds: int) -> str:
|
||
seconds = max(0, int(seconds))
|
||
for suffix, size in (("д", 86400), ("ч", 3600), ("м", 60)):
|
||
if seconds >= size:
|
||
whole, rest = divmod(seconds, size)
|
||
text = "%d%s" % (whole, suffix)
|
||
if rest and suffix == "д" and rest >= 3600:
|
||
text += " %dч" % (rest // 3600)
|
||
elif rest and suffix == "ч" and rest >= 60:
|
||
text += " %dм" % (rest // 60)
|
||
return text
|
||
return "%dс" % seconds
|
||
|
||
|
||
def _short_error(exc: BaseException) -> str:
|
||
text = str(exc).strip().replace("\n", " ")
|
||
if not text:
|
||
text = type(exc).__name__
|
||
return text[:120]
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# SQLite helpers. Every call runs in a worker thread (asyncio.to_thread) and
|
||
# uses a short busy timeout so a locked legacy database never stalls polling.
|
||
# --------------------------------------------------------------------------
|
||
|
||
_SCHEMA_LOCK = threading.Lock()
|
||
_SCHEMA_READY: set[str] = set()
|
||
_USERS_COLUMNS: dict[str, bool] = {}
|
||
|
||
SCHEMA_STATEMENTS = (
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS mod_seen_members (
|
||
chat_id INTEGER NOT NULL,
|
||
uid INTEGER NOT NULL,
|
||
username TEXT NOT NULL DEFAULT '',
|
||
display TEXT NOT NULL DEFAULT '',
|
||
last_seen INTEGER NOT NULL,
|
||
PRIMARY KEY (chat_id, uid)
|
||
)
|
||
""",
|
||
"""
|
||
CREATE INDEX IF NOT EXISTS mod_seen_members_username
|
||
ON mod_seen_members (chat_id, username)
|
||
""",
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS mod_chat_settings (
|
||
chat_id INTEGER PRIMARY KEY,
|
||
mode TEXT NOT NULL,
|
||
updated_by INTEGER NOT NULL,
|
||
updated_at INTEGER NOT NULL
|
||
)
|
||
""",
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS mod_restrictions (
|
||
chat_id INTEGER NOT NULL,
|
||
uid INTEGER NOT NULL,
|
||
actor INTEGER NOT NULL,
|
||
preimage TEXT NOT NULL,
|
||
preimage_kind TEXT NOT NULL,
|
||
preimage_until INTEGER NOT NULL DEFAULT 0,
|
||
applied TEXT NOT NULL,
|
||
applied_until INTEGER NOT NULL,
|
||
created_at INTEGER NOT NULL,
|
||
updated_at INTEGER NOT NULL,
|
||
PRIMARY KEY (chat_id, uid)
|
||
)
|
||
""",
|
||
)
|
||
|
||
|
||
def _path_key(path: str) -> str:
|
||
try:
|
||
return str(Path(path).resolve())
|
||
except OSError:
|
||
return str(path)
|
||
|
||
|
||
def _ensure_schema(con: sqlite3.Connection, key: str) -> None:
|
||
if key in _SCHEMA_READY:
|
||
return
|
||
with _SCHEMA_LOCK:
|
||
if key in _SCHEMA_READY:
|
||
return
|
||
for statement in SCHEMA_STATEMENTS:
|
||
con.execute(statement)
|
||
con.commit()
|
||
_SCHEMA_READY.add(key)
|
||
|
||
|
||
def _open(path: str) -> sqlite3.Connection:
|
||
con = sqlite3.connect(path, timeout=DB_TIMEOUT, isolation_level=None)
|
||
con.row_factory = sqlite3.Row
|
||
con.execute("PRAGMA busy_timeout=%d" % int(DB_TIMEOUT * 1000))
|
||
_ensure_schema(con, _path_key(path))
|
||
return con
|
||
|
||
|
||
def _record_seen(path: str, chat_id: int, users: list, prune: bool, now: int) -> None:
|
||
if not path or not users:
|
||
return
|
||
con = _open(path)
|
||
try:
|
||
con.execute("BEGIN IMMEDIATE")
|
||
con.executemany(
|
||
"INSERT INTO mod_seen_members (chat_id, uid, username, display, last_seen)"
|
||
" VALUES (?, ?, ?, ?, ?)"
|
||
" ON CONFLICT(chat_id, uid) DO UPDATE SET"
|
||
" username = excluded.username,"
|
||
" display = excluded.display,"
|
||
" last_seen = excluded.last_seen",
|
||
[(chat_id, uid, username, display, now) for uid, username, display in users],
|
||
)
|
||
if prune:
|
||
con.execute(
|
||
"DELETE FROM mod_seen_members WHERE chat_id = ? AND last_seen < ?",
|
||
(chat_id, now - SEEN_RETENTION_SECONDS),
|
||
)
|
||
con.execute(
|
||
"DELETE FROM mod_seen_members WHERE chat_id = ? AND uid NOT IN ("
|
||
" SELECT uid FROM mod_seen_members WHERE chat_id = ?"
|
||
" ORDER BY last_seen DESC, uid DESC LIMIT ?)",
|
||
(chat_id, chat_id, SEEN_MAX_ROWS_PER_CHAT),
|
||
)
|
||
con.execute("COMMIT")
|
||
except Exception:
|
||
try:
|
||
con.execute("ROLLBACK")
|
||
except Exception:
|
||
pass
|
||
raise
|
||
finally:
|
||
con.close()
|
||
|
||
|
||
def _users_has_username(con: sqlite3.Connection, key: str) -> bool:
|
||
cached = _USERS_COLUMNS.get(key)
|
||
if cached is not None:
|
||
return cached
|
||
has_users = con.execute(
|
||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'users'"
|
||
).fetchone()
|
||
if not has_users:
|
||
_USERS_COLUMNS[key] = False
|
||
return False
|
||
columns = {row["name"] for row in con.execute("PRAGMA table_info(users)")}
|
||
found = {"username", "tg_id"}.issubset(columns)
|
||
_USERS_COLUMNS[key] = found
|
||
return found
|
||
|
||
|
||
def _lookup_candidates(path: str, chat_id: int, username: str) -> list[dict]:
|
||
needle = _norm_username(username)
|
||
if not path or not needle:
|
||
return []
|
||
con = _open(path)
|
||
key = _path_key(path)
|
||
found: dict[int, str] = {}
|
||
try:
|
||
rows = con.execute(
|
||
"SELECT uid, username FROM mod_seen_members"
|
||
" WHERE chat_id = ? AND username = ?"
|
||
" ORDER BY last_seen DESC LIMIT ?",
|
||
(chat_id, needle, MAX_CANDIDATES),
|
||
)
|
||
for row in rows:
|
||
uid = int(row["uid"])
|
||
if uid > 0 and uid not in found:
|
||
found[uid] = needle
|
||
if _users_has_username(con, key):
|
||
rows = con.execute(
|
||
"SELECT tg_id AS uid, username FROM users"
|
||
" WHERE lower(ltrim(username, '@')) IN (?, ?) LIMIT ?",
|
||
(needle, "@" + needle, MAX_CANDIDATES),
|
||
)
|
||
for row in rows:
|
||
uid = int(row["uid"] or 0)
|
||
name = _norm_username(row["username"])
|
||
if uid > 0 and name and uid not in found:
|
||
found[uid] = name
|
||
finally:
|
||
con.close()
|
||
return [{"uid": uid, "username": name} for uid, name in found.items()][:MAX_CANDIDATES]
|
||
|
||
|
||
_FORWARD_MARKERS = ("forward_origin", "forward_from", "forward_from_chat", "forward_sender_name")
|
||
|
||
|
||
def _account_target_from_reply(reply: Any) -> TargetResolution:
|
||
if reply is None:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_USAGE)
|
||
if getattr(reply, "sender_chat", None) is not None:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_REPLY_ANON)
|
||
for marker in _FORWARD_MARKERS:
|
||
if getattr(reply, marker, None) is not None:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_REPLY_FORWARDED)
|
||
user = getattr(reply, "from_user", None)
|
||
uid = int(getattr(user, "id", 0) or 0)
|
||
if uid <= 0:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_REPLY_ANON)
|
||
if uid > TG_ID_MAX:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_ID)
|
||
if getattr(user, "is_bot", False):
|
||
return TargetResolution(0, "", MSG_ACCOUNT_REPLY_BOT)
|
||
return TargetResolution(uid, _display_name(user) or str(uid), "")
|
||
|
||
|
||
def _lookup_account_target(path: str, username: str) -> TargetResolution:
|
||
"""``@username`` -> uid from the bot ``users`` table only.
|
||
|
||
Case-insensitive, tolerates a stored ``@`` prefix, and never guesses:
|
||
two matching rows are reported as ambiguous instead of picking one.
|
||
"""
|
||
needle = _norm_username(username)
|
||
if not needle:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_USAGE)
|
||
if not path:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_UNREADABLE)
|
||
uri = Path(path).resolve().as_uri() + "?mode=ro"
|
||
con = sqlite3.connect(uri, uri=True, timeout=DB_TIMEOUT)
|
||
con.row_factory = sqlite3.Row
|
||
try:
|
||
rows = con.execute(
|
||
"SELECT tg_id FROM users WHERE lower(ltrim(username, '@')) = ? LIMIT 2",
|
||
(needle,),
|
||
).fetchall()
|
||
finally:
|
||
con.close()
|
||
if not rows:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_NOT_FOUND % needle)
|
||
if len(rows) > 1:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_AMBIGUOUS % needle)
|
||
try:
|
||
uid = int(rows[0]["tg_id"] or 0)
|
||
except (TypeError, ValueError, OverflowError):
|
||
return TargetResolution(0, "", MSG_ACCOUNT_UNREADABLE)
|
||
if not 0 < uid <= TG_ID_MAX:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_UNREADABLE)
|
||
return TargetResolution(uid, "@" + needle, "")
|
||
|
||
|
||
def _read_mode(path: str, chat_id: int) -> str:
|
||
if not path:
|
||
return DEFAULT_CHAT_MODE
|
||
con = _open(path)
|
||
try:
|
||
row = con.execute(
|
||
"SELECT mode FROM mod_chat_settings WHERE chat_id = ?", (chat_id,)
|
||
).fetchone()
|
||
finally:
|
||
con.close()
|
||
if row is None:
|
||
return DEFAULT_CHAT_MODE
|
||
mode = str(row["mode"])
|
||
return mode if mode in CHAT_MODES else DEFAULT_CHAT_MODE
|
||
|
||
|
||
def _write_mode(path: str, chat_id: int, mode: str, actor: int, now: int) -> None:
|
||
if not path or mode not in CHAT_MODES:
|
||
raise ValueError("unsupported chat mode")
|
||
con = _open(path)
|
||
try:
|
||
con.execute("BEGIN IMMEDIATE")
|
||
con.execute(
|
||
"INSERT INTO mod_chat_settings (chat_id, mode, updated_by, updated_at)"
|
||
" VALUES (?, ?, ?, ?)"
|
||
" ON CONFLICT(chat_id) DO UPDATE SET"
|
||
" mode = excluded.mode,"
|
||
" updated_by = excluded.updated_by,"
|
||
" updated_at = excluded.updated_at",
|
||
(chat_id, mode, actor, now),
|
||
)
|
||
con.execute("COMMIT")
|
||
except Exception:
|
||
try:
|
||
con.execute("ROLLBACK")
|
||
except Exception:
|
||
pass
|
||
raise
|
||
finally:
|
||
con.close()
|
||
|
||
|
||
def _write_mute_receipt(
|
||
path: str,
|
||
chat_id: int,
|
||
uid: int,
|
||
actor: int,
|
||
preimage: dict,
|
||
preimage_kind: str,
|
||
preimage_until: int,
|
||
applied: dict,
|
||
applied_until: int,
|
||
now: int,
|
||
) -> None:
|
||
con = _open(path)
|
||
try:
|
||
con.execute("BEGIN IMMEDIATE")
|
||
con.execute(
|
||
"INSERT INTO mod_restrictions ("
|
||
" chat_id, uid, actor, preimage, preimage_kind, preimage_until,"
|
||
" applied, applied_until, created_at, updated_at)"
|
||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||
" ON CONFLICT(chat_id, uid) DO UPDATE SET"
|
||
" actor = excluded.actor,"
|
||
" applied = excluded.applied,"
|
||
" applied_until = excluded.applied_until,"
|
||
" updated_at = excluded.updated_at",
|
||
(
|
||
chat_id,
|
||
uid,
|
||
actor,
|
||
json.dumps(preimage, sort_keys=True),
|
||
preimage_kind,
|
||
int(preimage_until or 0),
|
||
json.dumps(applied, sort_keys=True),
|
||
int(applied_until or 0),
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
con.execute("COMMIT")
|
||
except Exception:
|
||
try:
|
||
con.execute("ROLLBACK")
|
||
except Exception:
|
||
pass
|
||
raise
|
||
finally:
|
||
con.close()
|
||
|
||
|
||
def _read_mute_receipt(path: str, chat_id: int, uid: int):
|
||
if not path:
|
||
return None
|
||
con = _open(path)
|
||
try:
|
||
row = con.execute(
|
||
"SELECT * FROM mod_restrictions WHERE chat_id = ? AND uid = ?",
|
||
(chat_id, uid),
|
||
).fetchone()
|
||
finally:
|
||
con.close()
|
||
return dict(row) if row is not None else None
|
||
|
||
|
||
def _delete_mute_receipt(path: str, chat_id: int, uid: int) -> None:
|
||
if not path:
|
||
return
|
||
con = _open(path)
|
||
try:
|
||
con.execute("BEGIN IMMEDIATE")
|
||
con.execute(
|
||
"DELETE FROM mod_restrictions WHERE chat_id = ? AND uid = ?",
|
||
(chat_id, uid),
|
||
)
|
||
con.execute("COMMIT")
|
||
except Exception:
|
||
try:
|
||
con.execute("ROLLBACK")
|
||
except Exception:
|
||
pass
|
||
raise
|
||
finally:
|
||
con.close()
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# Planner client. One bounded POST per command; no retries (a Telegram
|
||
# mutation is never replayed automatically).
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
class PlanResult(NamedTuple):
|
||
action: str
|
||
target_uid: int
|
||
duration_seconds: int
|
||
mode: str
|
||
reason: str
|
||
|
||
|
||
_REJECT_STATUSES = frozenset((400, 403, 409, 422))
|
||
_NAME_TRIGGER = re.compile(r"^иишко\s*[:,]?(?=\s|$)", re.IGNORECASE | re.UNICODE)
|
||
|
||
|
||
def _plan_int(payload: dict, field: str) -> int:
|
||
value = payload.get(field, 0)
|
||
if isinstance(value, bool) or not isinstance(value, int):
|
||
raise PlannerUnavailable("planner returned a malformed %s" % field)
|
||
return int(value)
|
||
|
||
|
||
def _plan_str(payload: dict, field: str) -> str:
|
||
value = payload.get(field, "")
|
||
if value is None:
|
||
return ""
|
||
if not isinstance(value, str):
|
||
raise PlannerUnavailable("planner returned a malformed %s" % field)
|
||
return value
|
||
|
||
|
||
def parse_plan_response(payload: Any) -> PlanResult:
|
||
if not isinstance(payload, dict):
|
||
raise PlannerUnavailable("planner returned a non-object response")
|
||
result = PlanResult(
|
||
action=_plan_str(payload, "action"),
|
||
target_uid=_plan_int(payload, "target_uid"),
|
||
duration_seconds=_plan_int(payload, "duration_seconds"),
|
||
mode=_plan_str(payload, "mode"),
|
||
reason=_plan_str(payload, "reason"),
|
||
)
|
||
if result.target_uid < 0:
|
||
raise PlannerUnavailable("planner returned a negative target_uid")
|
||
if result.duration_seconds < 0:
|
||
raise PlannerUnavailable("planner returned a negative duration")
|
||
return result
|
||
|
||
|
||
class HttpPlanner:
|
||
"""Minimal fail-closed client for ``POST /v1/plan``."""
|
||
|
||
def __init__(
|
||
self,
|
||
url: str | None = None,
|
||
token: str | None = None,
|
||
timeout: float = HTTP_TIMEOUT,
|
||
) -> None:
|
||
self.url = (url or os.environ.get(URL_ENV) or DEFAULT_PLAN_URL).strip()
|
||
self.token = token if token is not None else os.environ.get(TOKEN_ENV, "")
|
||
self.timeout = max(0.2, float(timeout))
|
||
|
||
@property
|
||
def configured(self) -> bool:
|
||
return bool(self.token and self.url)
|
||
|
||
async def plan(self, payload: dict) -> PlanResult:
|
||
token = self.token or os.environ.get(TOKEN_ENV, "")
|
||
if not token:
|
||
raise PlannerUnavailable("moderation token is not configured")
|
||
if not self.url:
|
||
raise PlannerUnavailable("moderation planner URL is not configured")
|
||
try:
|
||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||
except (TypeError, ValueError) as exc:
|
||
raise PlannerUnavailable("request is not serialisable: %s" % _short_error(exc))
|
||
if len(body) > MAX_REQUEST_BYTES:
|
||
raise PlannerUnavailable("request body is too large")
|
||
headers = {"Content-Type": "application/json", AUTH_HEADER: token}
|
||
kwargs = {"headers": headers}
|
||
signature = None
|
||
try:
|
||
signature = inspect.signature(aiohttp.ClientSession)
|
||
if "timeout" in signature.parameters:
|
||
kwargs["timeout"] = aiohttp.ClientTimeout(total=self.timeout)
|
||
except (TypeError, ValueError):
|
||
signature = None
|
||
if signature is None or "timeout" not in kwargs:
|
||
kwargs["timeout"] = aiohttp.ClientTimeout(total=self.timeout)
|
||
try:
|
||
async with aiohttp.ClientSession(**kwargs) as session:
|
||
async with session.post(self.url, data=body) as response:
|
||
raw = await response.content.read(MAX_BODY_BYTES + 1)
|
||
status = response.status
|
||
except PlannerError:
|
||
raise
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
raise PlannerUnavailable("planner request failed: %s" % _short_error(exc))
|
||
if len(raw) > MAX_BODY_BYTES:
|
||
raise PlannerUnavailable("planner response is too large")
|
||
try:
|
||
decoded = json.loads(raw.decode("utf-8", "replace"))
|
||
except (ValueError, UnicodeDecodeError):
|
||
raise PlannerUnavailable("planner returned invalid JSON")
|
||
if status == 200:
|
||
return parse_plan_response(decoded)
|
||
message = ""
|
||
if isinstance(decoded, dict):
|
||
candidate = decoded.get("error")
|
||
if isinstance(candidate, str):
|
||
message = candidate.strip()[:400]
|
||
if status in _REJECT_STATUSES:
|
||
raise PlannerRejected(message or "Запрос модерации отклонён.")
|
||
raise PlannerUnavailable("planner status %d" % status)
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# Bridge
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def _callable_or_none(value):
|
||
return value if callable(value) else None
|
||
|
||
|
||
class _ModerationBase:
|
||
"""Shared state and identity helpers for the moderation bridge."""
|
||
|
||
def __init__(self, namespace=None, *, planner=None, clock=None) -> None:
|
||
self.ns = namespace if isinstance(namespace, dict) else {}
|
||
self.clock = clock or (lambda: int(time.time()))
|
||
self.planner = planner or HttpPlanner()
|
||
self._bot_id = 0
|
||
self._bot_username = ""
|
||
self._identity_ready = False
|
||
self._modes: dict[int, str] = {}
|
||
self._last_prune: dict[int, int] = {}
|
||
self._chat_defaults: dict[int, dict] = {}
|
||
|
||
# -- namespace wiring ------------------------------------------------
|
||
@property
|
||
def bot(self):
|
||
bot = self.ns.get("bot")
|
||
if bot is None:
|
||
dp = self.ns.get("dp")
|
||
bot = getattr(dp, "bot", None)
|
||
return bot
|
||
|
||
@property
|
||
def bot_db(self) -> str:
|
||
raw = self.ns.get("BOT_DB")
|
||
if not raw:
|
||
schema = self.ns.get("bot_schema")
|
||
raw = getattr(schema, "BOT_DB", "")
|
||
raw = str(raw or "")
|
||
return "" if raw == ":memory:" else raw
|
||
|
||
@property
|
||
def newapi_db(self) -> str:
|
||
cfg = self.ns.get("CFG")
|
||
raw = ""
|
||
if isinstance(cfg, dict):
|
||
raw = str(cfg.get("newapi_db") or cfg.get("NEWAPI_DB") or "")
|
||
if not raw:
|
||
schema = self.ns.get("bot_schema")
|
||
raw = str(getattr(schema, "NEWAPI_DB", "") or "")
|
||
return raw
|
||
|
||
@property
|
||
def admin_ids(self) -> tuple:
|
||
raw = self.ns.get("ADMIN_IDS") or ()
|
||
out = []
|
||
for item in raw:
|
||
try:
|
||
uid = int(item)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if uid > 0:
|
||
out.append(uid)
|
||
return tuple(sorted(set(out)))
|
||
|
||
@property
|
||
def pause_path(self) -> str:
|
||
value = self.ns.get("PAUSE_PATH") or self.ns.get("UNBAN_PAUSE_PATH")
|
||
if value:
|
||
return str(value)
|
||
cfg = self.ns.get("CFG")
|
||
if isinstance(cfg, dict):
|
||
value = cfg.get("unban_pause_path") or cfg.get("pause_path")
|
||
return str(value or "")
|
||
|
||
# -- identity --------------------------------------------------------
|
||
async def identity(self):
|
||
if self._identity_ready:
|
||
return self._bot_id, self._bot_username
|
||
bot = self.bot
|
||
me = None
|
||
candidate = getattr(bot, "me", None) if bot is not None else None
|
||
if candidate is not None:
|
||
if callable(candidate):
|
||
try:
|
||
candidate = candidate()
|
||
if inspect.isawaitable(candidate):
|
||
candidate = await candidate
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.warning(
|
||
"moderation: bot identity check failed: %s", _short_error(exc)
|
||
)
|
||
candidate = None
|
||
me = candidate
|
||
if me is None:
|
||
method = getattr(bot, "get_me", None) if bot is not None else None
|
||
if callable(method):
|
||
try:
|
||
me = method()
|
||
if inspect.isawaitable(me):
|
||
me = await me
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.warning(
|
||
"moderation: bot identity check failed: %s", _short_error(exc)
|
||
)
|
||
me = None
|
||
uid = int(getattr(me, "id", 0) or 0)
|
||
username = _norm_username(getattr(me, "username", ""))
|
||
if uid > 0:
|
||
self._bot_id = uid
|
||
if username:
|
||
self._bot_username = username
|
||
self._identity_ready = uid > 0 and bool(username)
|
||
return self._bot_id, self._bot_username
|
||
|
||
async def bot_username(self) -> str:
|
||
_, username = await self.identity()
|
||
return username
|
||
|
||
# -- seen members ----------------------------------------------------
|
||
async def _remember(self, chat, users, force_prune=False) -> None:
|
||
path = self.bot_db
|
||
chat_id = int(getattr(chat, "id", 0) or 0)
|
||
if not path or chat_id == 0 or not users:
|
||
return
|
||
now = self.clock()
|
||
last = self._last_prune.get(chat_id, 0)
|
||
prune = force_prune or (now - last) >= SEEN_PRUNE_INTERVAL_SECONDS
|
||
if prune:
|
||
self._last_prune[chat_id] = now
|
||
try:
|
||
await asyncio.to_thread(_record_seen, path, chat_id, users, prune, now)
|
||
except Exception as exc:
|
||
log.warning("moderation: seen index write failed: %s", _short_error(exc))
|
||
|
||
@staticmethod
|
||
def _seen_row(user):
|
||
uid = int(getattr(user, "id", 0) or 0)
|
||
if uid <= 0 or getattr(user, "is_bot", False):
|
||
return None
|
||
return (uid, _norm_username(getattr(user, "username", "")), _display_name(user))
|
||
|
||
async def observe_message(self, message) -> None:
|
||
"""Record the message author (group/supergroup only)."""
|
||
chat_type = _chat_type(getattr(message, "chat", None))
|
||
if chat_type not in ("group", "supergroup"):
|
||
return
|
||
row = self._seen_row(getattr(message, "from_user", None))
|
||
if row is not None:
|
||
await self._remember(message.chat, [row])
|
||
|
||
async def on_new_chat_members(self, message) -> None:
|
||
rows = []
|
||
for user in getattr(message, "new_chat_members", None) or ():
|
||
row = self._seen_row(user)
|
||
if row is not None:
|
||
rows.append(row)
|
||
if rows:
|
||
await self._remember(message.chat, rows, force_prune=True)
|
||
|
||
async def on_chat_member(self, update) -> None:
|
||
member = getattr(update, "new_chat_member", None)
|
||
user = getattr(member, "user", None)
|
||
chat = getattr(update, "chat", None)
|
||
if _chat_type(chat) not in ("group", "supergroup"):
|
||
return
|
||
if _status(member) in ("left", "kicked"):
|
||
return
|
||
row = self._seen_row(user)
|
||
if row is not None:
|
||
await self._remember(chat, [row], force_prune=True)
|
||
|
||
async def candidates_for(self, chat_id: int, args) -> list:
|
||
path = self.bot_db
|
||
if not path:
|
||
return []
|
||
for token in args or ():
|
||
name = _norm_username(token)
|
||
if not name:
|
||
continue
|
||
try:
|
||
return await asyncio.to_thread(_lookup_candidates, path, int(chat_id), name)
|
||
except Exception as exc:
|
||
log.warning("moderation: username lookup failed: %s", _short_error(exc))
|
||
return []
|
||
return []
|
||
|
||
# -- target resolution ----------------------------------------------
|
||
async def resolve_target(self, message, args=None) -> TargetResolution:
|
||
"""Resolve an explicit token or the replied author to a uid.
|
||
|
||
Usernames are resolved only from local tables; ``getChat`` is never
|
||
used for an arbitrary username.
|
||
"""
|
||
if args is None:
|
||
text = (getattr(message, "text", None) or "").strip()
|
||
parts = text.split()
|
||
args = parts[1:] if parts else []
|
||
args = [str(a) for a in args if str(a).strip()]
|
||
reply = getattr(message, "reply_to_message", None)
|
||
reply_user = getattr(reply, "from_user", None) if reply is not None else None
|
||
reply_uid = int(getattr(reply_user, "id", 0) or 0)
|
||
if len(args) > 1:
|
||
return TargetResolution(0, "", "Укажите одного пользователя.")
|
||
if not args:
|
||
if reply_uid <= 0:
|
||
return TargetResolution(
|
||
0, "", "Укажите пользователя: ответом на сообщение, @username или ID."
|
||
)
|
||
label = _display_name(reply_user) or str(reply_uid)
|
||
return TargetResolution(reply_uid, label, "")
|
||
token = args[0].strip()
|
||
if token.isdigit():
|
||
uid = int(token)
|
||
if uid <= 0:
|
||
return TargetResolution(0, "", "ID пользователя должен быть положительным.")
|
||
return TargetResolution(uid, str(uid), "")
|
||
name = _norm_username(token)
|
||
if not name:
|
||
return TargetResolution(0, "", "Некорректный @username или ID.")
|
||
try:
|
||
plan = await self._plan(
|
||
"resolve", message, [token], actor_allowed=True, bot_allowed=True
|
||
)
|
||
except PlannerRejected as exc:
|
||
return TargetResolution(0, "", str(exc) or "Не удалось определить пользователя.")
|
||
uid = int(getattr(plan, "target_uid", 0) or 0)
|
||
if uid <= 0:
|
||
return TargetResolution(0, "", "Пользователь @%s не найден в этом чате." % name)
|
||
return TargetResolution(uid, "@" + name, "")
|
||
|
||
async def resolve_account_target(self, message, args=None) -> TargetResolution:
|
||
"""Private /ban|/unban target: ID, local @username or replied author.
|
||
|
||
Unlike :meth:`resolve_target` this never asks the planner and never
|
||
looks at per-chat membership: a global account is identified by the
|
||
bot ``users`` table, so the command keeps working when the policy
|
||
service is down.
|
||
"""
|
||
if args is None:
|
||
text = (getattr(message, "text", None) or "").strip()
|
||
parts = text.split()
|
||
args = parts[1:] if parts else []
|
||
args = [str(a) for a in args if str(a).strip()]
|
||
if len(args) > 1:
|
||
return TargetResolution(0, "", "Укажите одного пользователя.")
|
||
if not args:
|
||
return _account_target_from_reply(getattr(message, "reply_to_message", None))
|
||
token = args[0].strip()
|
||
if re.fullmatch(r"[0-9]+", token):
|
||
digits = token.lstrip("0") or "0"
|
||
if len(digits) > 19:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_ID)
|
||
uid = int(digits)
|
||
if not 0 < uid <= TG_ID_MAX:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_ID)
|
||
return TargetResolution(uid, str(uid), "")
|
||
name = _norm_username(token)
|
||
if not name:
|
||
return TargetResolution(0, "", MSG_ACCOUNT_USAGE)
|
||
try:
|
||
return await asyncio.to_thread(_lookup_account_target, self.bot_db, name)
|
||
except Exception as exc:
|
||
log.warning("moderation: account lookup failed: %s", _short_error(exc))
|
||
return TargetResolution(0, "", MSG_ACCOUNT_UNREADABLE)
|
||
|
||
# -- reply-mode gate -------------------------------------------------
|
||
async def chat_mode(self, chat_id: int) -> str:
|
||
chat_id = int(chat_id or 0)
|
||
cached = self._modes.get(chat_id)
|
||
if cached is not None:
|
||
return cached
|
||
path = self.bot_db
|
||
if not path:
|
||
return DEFAULT_CHAT_MODE
|
||
try:
|
||
mode = await asyncio.to_thread(_read_mode, path, chat_id)
|
||
except Exception as exc:
|
||
log.warning("moderation: chat mode read failed: %s", _short_error(exc))
|
||
return DEFAULT_CHAT_MODE
|
||
self._modes[chat_id] = mode
|
||
return mode
|
||
|
||
def cached_mode(self, chat_id: int) -> str:
|
||
return self._modes.get(int(chat_id or 0), DEFAULT_CHAT_MODE)
|
||
|
||
def should_reply(self, chat_id: int) -> bool:
|
||
return self.cached_mode(chat_id) != "quiet"
|
||
|
||
async def set_chat_mode(self, chat_id: int, mode: str, actor: int = 0) -> bool:
|
||
mode = str(mode or "").strip().lower()
|
||
if mode not in CHAT_MODES:
|
||
return False
|
||
path = self.bot_db
|
||
if path:
|
||
await asyncio.to_thread(
|
||
_write_mode, path, int(chat_id), mode, int(actor or 0), self.clock()
|
||
)
|
||
self._modes[int(chat_id)] = mode
|
||
return True
|
||
|
||
def allow_group_message(self, message) -> bool:
|
||
"""Whether the parent group-reply layer may answer ``message``.
|
||
|
||
``quiet`` -- never answer.
|
||
``addressed`` -- only when the bot is mentioned or the bot is replied to.
|
||
``normal`` -- answer as before.
|
||
"""
|
||
chat_id = int(getattr(getattr(message, "chat", None), "id", 0) or 0)
|
||
mode = self.cached_mode(chat_id)
|
||
if mode == "normal":
|
||
return True
|
||
if mode == "quiet":
|
||
return False
|
||
return self._addresses_bot(message)
|
||
|
||
def _addresses_bot(self, message) -> bool:
|
||
reply = getattr(message, "reply_to_message", None)
|
||
reply_user = getattr(reply, "from_user", None) if reply is not None else None
|
||
if self._bot_id and int(getattr(reply_user, "id", 0) or 0) == self._bot_id:
|
||
return True
|
||
text = getattr(message, "text", None) or getattr(message, "caption", None) or ""
|
||
entities = list(getattr(message, "entities", None) or ())
|
||
entities += list(getattr(message, "caption_entities", None) or ())
|
||
for entity in entities:
|
||
kind = str(getattr(entity, "type", ""))
|
||
if kind == "text_mention":
|
||
user = getattr(entity, "user", None)
|
||
if self._bot_id and int(getattr(user, "id", 0) or 0) == self._bot_id:
|
||
return True
|
||
elif kind == "mention" and self._bot_username:
|
||
offset = int(getattr(entity, "offset", 0) or 0)
|
||
length = int(getattr(entity, "length", 0) or 0)
|
||
token = text[offset : offset + length]
|
||
if _norm_username(token) == self._bot_username:
|
||
return True
|
||
if _NAME_TRIGGER.match(text.strip()):
|
||
return True
|
||
return bool(self._bot_username) and ("@" + self._bot_username) in _ascii_lower(text)
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# Command execution
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
class _Refusal(Exception):
|
||
"""A user-facing refusal; the text is sent verbatim."""
|
||
|
||
|
||
def _all_bits(value: bool) -> dict:
|
||
return {field: value for field in PERMISSION_FIELDS}
|
||
|
||
|
||
def _mute_bits(preimage: dict) -> dict:
|
||
bits = dict(preimage)
|
||
for field in PERMISSION_FIELDS:
|
||
if field not in MANAGE_FIELDS:
|
||
bits[field] = False
|
||
return bits
|
||
|
||
|
||
def _same_bits(left: dict, right: dict) -> bool:
|
||
return all(bool(left.get(f, False)) == bool(right.get(f, False)) for f in PERMISSION_FIELDS)
|
||
|
||
|
||
class ModerationRunner(_ModerationBase):
|
||
"""Command execution helpers layered on the bridge state."""
|
||
|
||
# -- Telegram helpers -------------------------------------------------
|
||
async def send_text(self, message, text: str, *, reply_markup=None, chat=None) -> None:
|
||
target_chat = chat if chat is not None else getattr(message, "chat", None)
|
||
chat_id = int(getattr(target_chat, "id", 0) or 0)
|
||
if chat_id == 0 or self.bot is None:
|
||
raise _Refusal("Не удалось отправить ответ: чат недоступен.")
|
||
kwargs = {"chat_id": chat_id, "text": text[:4000]}
|
||
if reply_markup is not None:
|
||
kwargs["reply_markup"] = reply_markup
|
||
try:
|
||
await self.bot.send_message(**kwargs)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.warning("moderation: reply failed: %s", _short_error(exc))
|
||
|
||
async def member(self, chat_id: int, uid: int):
|
||
try:
|
||
return await self.bot.get_chat_member(chat_id, uid)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.warning(
|
||
"moderation: get_chat_member(%s, %s) failed: %s",
|
||
chat_id,
|
||
uid,
|
||
_short_error(exc),
|
||
)
|
||
return None
|
||
|
||
async def chat_defaults(self, chat_id: int) -> dict:
|
||
# Always re-read before a mutation: chat defaults may have tightened
|
||
# since a previous mute. The last successful snapshot is retained for
|
||
# diagnostics only, never used to authorize a restore.
|
||
try:
|
||
chat = await self.bot.get_chat(chat_id)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
raise _Refusal(
|
||
"Не удалось получить настройки чата: %s. Действие не выполнено."
|
||
% _short_error(exc)
|
||
)
|
||
perms = getattr(chat, "permissions", None)
|
||
bits = _all_bits(True) if perms is None else _bits_from_permissions(perms, True)
|
||
self._chat_defaults[int(chat_id)] = dict(bits)
|
||
return bits
|
||
|
||
@staticmethod
|
||
def _actor_allowed(member) -> bool:
|
||
status = _status(member)
|
||
if status == "creator":
|
||
return True
|
||
if status != "administrator":
|
||
return False
|
||
return bool(getattr(member, "can_restrict_members", False))
|
||
|
||
@staticmethod
|
||
def _bot_allowed(member) -> bool:
|
||
status = _status(member)
|
||
if status == "creator":
|
||
return True
|
||
if status != "administrator":
|
||
return False
|
||
return bool(getattr(member, "can_restrict_members", False))
|
||
|
||
async def _protected_target(self, chat_id: int, uid: int, actor: int) -> object:
|
||
bot_id, _ = await self.identity()
|
||
if uid == bot_id:
|
||
raise _Refusal("Нельзя применить действие к самому боту.")
|
||
if uid == actor:
|
||
raise _Refusal("Нельзя применить действие к самому себе.")
|
||
if uid in self.admin_ids:
|
||
raise _Refusal("Нельзя применить действие к администратору бота.")
|
||
target = await self.member(chat_id, uid)
|
||
if target is None:
|
||
raise _Refusal("Не удалось проверить участника в чате. Действие не выполнено.")
|
||
if _status(target) in ("creator", "administrator"):
|
||
raise _Refusal("Нельзя ограничить администратора чата.")
|
||
return target
|
||
|
||
async def _plan(self, action: str, message, args, *, actor_allowed: bool, bot_allowed: bool):
|
||
chat = getattr(message, "chat", None)
|
||
chat_id = int(getattr(chat, "id", 0) or 0)
|
||
reply = getattr(message, "reply_to_message", None)
|
||
reply_user = getattr(reply, "from_user", None) if reply is not None else None
|
||
actor = getattr(message, "from_user", None)
|
||
actor_uid = int(getattr(actor, "id", 0) or 0)
|
||
bot_id, bot_username = await self.identity()
|
||
protected = [uid for uid in (bot_id, actor_uid) if uid > 0]
|
||
protected.extend(self.admin_ids)
|
||
payload = {
|
||
"action": action,
|
||
"args": [str(a) for a in args],
|
||
"reply_uid": int(getattr(reply_user, "id", 0) or 0),
|
||
"candidates": await self.candidates_for(chat_id, args),
|
||
"actor_allowed": bool(actor_allowed),
|
||
"bot_allowed": bool(bot_allowed),
|
||
"chat_type": _chat_type(chat),
|
||
"protected_uids": sorted(set(protected)),
|
||
"bot_username": bot_username,
|
||
}
|
||
return await self.planner.plan(payload)
|
||
|
||
# -- restriction primitives ------------------------------------------
|
||
async def apply_restriction(self, chat_id: int, uid: int, bits: dict, until_date: int) -> None:
|
||
perms = ChatPermissions(**{field: bool(bits.get(field, False)) for field in PERMISSION_FIELDS})
|
||
try:
|
||
result = await self.bot.restrict_chat_member(
|
||
chat_id, uid, permissions=perms, until_date=int(until_date or 0)
|
||
)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
raise _Refusal(
|
||
"Не удалось ограничить участника: %s. Действие не выполнено."
|
||
% _short_error(exc)
|
||
)
|
||
if result is False:
|
||
raise _Refusal("Не удалось ограничить участника. Действие не выполнено.")
|
||
|
||
async def _mute(self, message, plan) -> str:
|
||
chat = getattr(message, "chat", None)
|
||
chat_id = int(getattr(chat, "id", 0) or 0)
|
||
uid = int(plan.target_uid)
|
||
actor = int(getattr(getattr(message, "from_user", None), "id", 0) or 0)
|
||
target = await self._protected_target(chat_id, uid, actor)
|
||
duration = int(plan.duration_seconds or DEFAULT_MUTE_SECONDS)
|
||
if duration < MIN_MUTE_SECONDS or duration > MAX_MUTE_SECONDS:
|
||
raise _Refusal("Длительность блокировки должна быть от 30 секунд до 365 дней.")
|
||
now = self.clock()
|
||
until = now + max(duration, SAFE_MUTE_MIN_SECONDS)
|
||
status = _status(target)
|
||
preimage_until = 0
|
||
if status == "restricted":
|
||
preimage = _member_bits(target)
|
||
if preimage is None:
|
||
raise _Refusal(
|
||
"Не удалось прочитать текущие ограничения. Снимите ограничение вручную."
|
||
)
|
||
preimage_kind = "restricted"
|
||
preimage_until = _as_timestamp(getattr(target, "until_date", None))
|
||
else:
|
||
preimage = await self.chat_defaults(chat_id)
|
||
preimage_kind = "default"
|
||
applied = _mute_bits(preimage)
|
||
path = self.bot_db
|
||
receipt_written = False
|
||
if path:
|
||
try:
|
||
await asyncio.to_thread(
|
||
_write_mute_receipt,
|
||
path,
|
||
chat_id,
|
||
uid,
|
||
actor,
|
||
preimage,
|
||
preimage_kind,
|
||
preimage_until,
|
||
applied,
|
||
until,
|
||
now,
|
||
)
|
||
receipt_written = True
|
||
except Exception as exc:
|
||
log.warning("moderation: mute receipt write failed: %s", _short_error(exc))
|
||
raise _Refusal(
|
||
"Не удалось сохранить состояние перед блокировкой. Действие не выполнено."
|
||
)
|
||
try:
|
||
await self.apply_restriction(chat_id, uid, applied, until)
|
||
except _Refusal:
|
||
if receipt_written:
|
||
try:
|
||
await asyncio.to_thread(_delete_mute_receipt, path, chat_id, uid)
|
||
except Exception as exc:
|
||
log.warning("moderation: receipt cleanup failed: %s", _short_error(exc))
|
||
raise
|
||
return "Пользователь заблокирован на %s." % _human_duration(duration)
|
||
|
||
async def _unmute(self, message, plan) -> str:
|
||
chat = getattr(message, "chat", None)
|
||
chat_id = int(getattr(chat, "id", 0) or 0)
|
||
uid = int(plan.target_uid)
|
||
actor = int(getattr(getattr(message, "from_user", None), "id", 0) or 0)
|
||
target = await self._protected_target(chat_id, uid, actor)
|
||
path = self.bot_db
|
||
receipt = None
|
||
if path:
|
||
try:
|
||
receipt = await asyncio.to_thread(_read_mute_receipt, path, chat_id, uid)
|
||
except Exception as exc:
|
||
log.warning("moderation: mute receipt read failed: %s", _short_error(exc))
|
||
status = _status(target)
|
||
if receipt is None:
|
||
if status == "restricted":
|
||
raise _Refusal(
|
||
"Нет сохранённого состояния до блокировки: снимите ограничение вручную."
|
||
)
|
||
return "Пользователь не в муте."
|
||
now = self.clock()
|
||
try:
|
||
applied = json.loads(receipt.get("applied") or "{}")
|
||
preimage = json.loads(receipt.get("preimage") or "{}")
|
||
except (TypeError, ValueError):
|
||
raise _Refusal("Запись о блокировке повреждена: снимите ограничение вручную.")
|
||
preimage_kind = str(receipt.get("preimage_kind") or "default")
|
||
preimage_until = int(receipt.get("preimage_until") or 0)
|
||
applied_until = int(receipt.get("applied_until") or 0)
|
||
current = None
|
||
current_until = 0
|
||
if status == "restricted":
|
||
current = _member_bits(target)
|
||
if current is None:
|
||
raise _Refusal(
|
||
"Не удалось прочитать текущие ограничения. Снимите ограничение вручную."
|
||
)
|
||
current_until = _as_timestamp(getattr(target, "until_date", None))
|
||
defaults = await self.chat_defaults(chat_id)
|
||
if preimage_kind == "restricted":
|
||
if preimage_until and preimage_until <= now:
|
||
baseline = dict(defaults)
|
||
else:
|
||
baseline = _bits_from_permissions(None, True)
|
||
baseline.update({f: bool(preimage.get(f, True)) for f in PERMISSION_FIELDS})
|
||
else:
|
||
baseline = {f: bool(preimage.get(f, True)) for f in PERMISSION_FIELDS}
|
||
desired = {}
|
||
for field in PERMISSION_FIELDS:
|
||
if current is None:
|
||
desired[field] = bool(baseline[field])
|
||
elif bool(current.get(field, False)) != bool(applied.get(field, False)):
|
||
desired[field] = bool(current.get(field, False))
|
||
else:
|
||
desired[field] = bool(baseline[field])
|
||
for field in PERMISSION_FIELDS:
|
||
desired[field] = bool(desired[field]) and bool(defaults.get(field, True))
|
||
fully_open = all(desired.values())
|
||
if current is None:
|
||
if path:
|
||
await asyncio.to_thread(_delete_mute_receipt, path, chat_id, uid)
|
||
return "Пользователь не в муте."
|
||
until_date = 0
|
||
if not fully_open and current is not None:
|
||
if applied_until and current_until != applied_until:
|
||
# The target's expiry was changed independently after the mute.
|
||
until_date = current_until if current_until > now else 0
|
||
elif preimage_kind == "restricted":
|
||
until_date = preimage_until if preimage_until > now else (
|
||
current_until if current_until > now else 0
|
||
)
|
||
elif current_until and current_until > now:
|
||
until_date = current_until
|
||
if (current is not None and not fully_open and _same_bits(current, desired)
|
||
and until_date == self._restriction_until(current_until, now)):
|
||
if path:
|
||
await asyncio.to_thread(_delete_mute_receipt, path, chat_id, uid)
|
||
return "Ограничения уже соответствуют сохранённому состоянию."
|
||
await self.apply_restriction(chat_id, uid, desired, until_date)
|
||
if path:
|
||
try:
|
||
await asyncio.to_thread(_delete_mute_receipt, path, chat_id, uid)
|
||
except Exception as exc:
|
||
log.warning("moderation: receipt cleanup failed: %s", _short_error(exc))
|
||
if fully_open:
|
||
return "Ограничения сняты, права восстановлены."
|
||
return "Ограничения сняты частично: сохранены изменения, сделанные после блокировки."
|
||
|
||
@staticmethod
|
||
def _restriction_until(value: int, now: int) -> int:
|
||
return value if value > now else 0
|
||
|
||
async def _group_action(self, message, name: str, args) -> str:
|
||
chat = getattr(message, "chat", None)
|
||
chat_id = int(getattr(chat, "id", 0) or 0)
|
||
chat_type = _chat_type(chat)
|
||
actor = getattr(message, "from_user", None)
|
||
actor_uid = int(getattr(actor, "id", 0) or 0)
|
||
bot_id, _ = await self.identity()
|
||
actor_member = await self.member(chat_id, actor_uid)
|
||
bot_member = await self.member(chat_id, bot_id)
|
||
if actor_member is None or bot_member is None:
|
||
raise _Refusal("Не удалось проверить права в чате. Действие не выполнено.")
|
||
if not self._actor_allowed(actor_member):
|
||
raise _Refusal(MSG_ADMIN_ONLY)
|
||
if _status(bot_member) == "member":
|
||
raise _Refusal(MSG_BOT_RIGHTS)
|
||
if not self._bot_allowed(bot_member):
|
||
raise _Refusal(MSG_BOT_RESTRICT)
|
||
if name in ("mute", "unmute") and chat_type != "supergroup":
|
||
raise _Refusal("Блокировка доступна только в супергруппах.")
|
||
plan = await self._plan(
|
||
name,
|
||
message,
|
||
args,
|
||
actor_allowed=True,
|
||
bot_allowed=True,
|
||
)
|
||
uid = int(plan.target_uid)
|
||
if uid <= 0:
|
||
raise _Refusal("Не удалось определить пользователя.")
|
||
if name == "ban":
|
||
await self._protected_target(chat_id, uid, actor_uid)
|
||
await self._ban(chat_id, uid)
|
||
return "Пользователь забанен в чате."
|
||
if name == "unban":
|
||
return await self._unban(chat_id, uid)
|
||
if name == "kick":
|
||
await self._protected_target(chat_id, uid, actor_uid)
|
||
await self._kick(chat_id, uid)
|
||
return "Пользователь удалён из чата."
|
||
if name == "mute":
|
||
return await self._mute(message, plan)
|
||
if name == "unmute":
|
||
return await self._unmute(message, plan)
|
||
raise _Refusal("Неизвестная команда модерации.")
|
||
|
||
async def _ban(self, chat_id: int, uid: int) -> None:
|
||
try:
|
||
result = await self.bot.ban_chat_member(chat_id, uid, revoke_messages=True)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
raise _Refusal("Не удалось забанить: %s. Действие не выполнено." % _short_error(exc))
|
||
if result is False:
|
||
raise _Refusal("Не удалось забанить. Действие не выполнено.")
|
||
|
||
async def _unban(self, chat_id: int, uid: int) -> str:
|
||
try:
|
||
result = await self.bot.unban_chat_member(chat_id, uid, only_if_banned=True)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
raise _Refusal("Не удалось разбанить: %s. Действие не выполнено." % _short_error(exc))
|
||
if result is False:
|
||
return "Пользователь не был забанен."
|
||
return "Пользователь разбанен в чате."
|
||
|
||
async def _kick(self, chat_id: int, uid: int) -> None:
|
||
target = await self.member(chat_id, uid)
|
||
if _status(target) == "kicked":
|
||
raise _Refusal("Пользователь уже забанен: используйте /unban.")
|
||
try:
|
||
banned = await self.bot.ban_chat_member(chat_id, uid, revoke_messages=False)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
raise _Refusal("Не удалось удалить участника: %s. Действие не выполнено." % _short_error(exc))
|
||
if banned is False:
|
||
raise _Refusal("Не удалось удалить участника. Действие не выполнено.")
|
||
try:
|
||
unban = await self.bot.unban_chat_member(chat_id, uid, only_if_banned=True)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
raise _Refusal(
|
||
"Участник исключён, но снять бан не удалось: %s. Пользователь"
|
||
" может остаться забаненным." % _short_error(exc)
|
||
)
|
||
if unban is False:
|
||
raise _Refusal(
|
||
"Участник исключён, но снять бан не удалось. Пользователь может"
|
||
" остаться забаненным."
|
||
)
|
||
|
||
|
||
# User-facing parent group-reply setting -> bridge mode.
|
||
MODE_FROM_PARENT = {"off": "quiet", "mentions": "addressed", "reply": "normal"}
|
||
|
||
MODE_HINTS = {
|
||
"addressed": "отвечать только на упоминания и ответы боту",
|
||
"quiet": "не отвечать в группе",
|
||
"normal": "отвечать как раньше",
|
||
}
|
||
|
||
|
||
class ModerationBridge(ModerationRunner):
|
||
"""Public bridge: install(globals(), dp) wires :meth:`middleware`."""
|
||
|
||
async def handle_command(self, message, name: str, args) -> str:
|
||
chat = getattr(message, "chat", None)
|
||
if _chat_type(chat) == "private":
|
||
return await self._private_command(message, name, args)
|
||
return await self._group_command(message, name, args)
|
||
|
||
async def _require_group_admin(self, message) -> None:
|
||
chat_id = int(getattr(getattr(message, "chat", None), "id", 0) or 0)
|
||
actor_uid = int(getattr(getattr(message, "from_user", None), "id", 0) or 0)
|
||
actor_member = await self.member(chat_id, actor_uid)
|
||
if actor_member is None or not self._actor_allowed(actor_member):
|
||
raise _Refusal(MSG_ADMIN_ONLY)
|
||
|
||
async def _group_command(self, message, name: str, args) -> str:
|
||
if name == "setup":
|
||
await self._require_group_admin(message)
|
||
return await self._diagnostics(message.chat)
|
||
if name == "chatmode":
|
||
return await self._chatmode(message, args)
|
||
return await self._group_action(message, name, args)
|
||
|
||
async def _private_command(self, message, name: str, args) -> str:
|
||
actor_uid = int(getattr(getattr(message, "from_user", None), "id", 0) or 0)
|
||
if actor_uid not in self.admin_ids:
|
||
return MSG_OWNER_ONLY
|
||
if name in ("setup",):
|
||
return await self._diagnostics(message.chat)
|
||
if name == "chatmode":
|
||
return "Команда доступна только в группах."
|
||
if name in ("mute", "unmute", "kick"):
|
||
return "Команда доступна только в группах."
|
||
if name in ("ban", "unban"):
|
||
return await self._account_change(message, name, args, account_only=True)
|
||
return "Неизвестная команда модерации."
|
||
|
||
async def _account_change(self, message, name: str, args, *, account_only: bool = False) -> str:
|
||
if not self.bot_db or not self.newapi_db:
|
||
return MSG_NO_DB
|
||
if account_only:
|
||
target = await self.resolve_account_target(message, args)
|
||
else:
|
||
target = await self.resolve_target(message, args)
|
||
if target.error:
|
||
return target.error
|
||
uid = int(target.uid)
|
||
actor_uid = int(getattr(getattr(message, "from_user", None), "id", 0) or 0)
|
||
if name == "ban" and uid in self.admin_ids:
|
||
return "Нельзя забанить администратора бота."
|
||
kwargs = {"actor_uid": actor_uid, "admin_ids": frozenset(self.admin_ids)}
|
||
if self.pause_path:
|
||
kwargs["pause_path"] = self.pause_path
|
||
function = account_admin.unban_account if name == "unban" else account_admin.set_banned
|
||
call_args = (self.bot_db, self.newapi_db, uid)
|
||
if name == "ban":
|
||
call_args = call_args + (True,)
|
||
try:
|
||
report = await asyncio.to_thread(function, *call_args, **kwargs)
|
||
except Exception as exc:
|
||
verb = "снять бан" if name == "unban" else "забанить"
|
||
return "Не удалось %s: %s." % (verb, _short_error(exc))
|
||
try:
|
||
return str(account_admin.summary(report))
|
||
except Exception:
|
||
return "Готово."
|
||
|
||
async def _diagnostics(self, chat) -> str:
|
||
chat_id = int(getattr(chat, "id", 0) or 0)
|
||
bot_id, username = await self.identity()
|
||
bot_member = await self.member(chat_id, bot_id) if bot_id else None
|
||
status = _status(bot_member) or "неизвестно"
|
||
rights = "ограничивать участников: " + (
|
||
"да" if bot_member is not None and self._bot_allowed(bot_member) else "нет"
|
||
)
|
||
cfg = self.ns.get("CFG")
|
||
has_newapi = bool(
|
||
self.newapi_db or (isinstance(cfg, dict) and cfg.get("newapi_db"))
|
||
)
|
||
mode = await self.chat_mode(chat_id) if chat_id else DEFAULT_CHAT_MODE
|
||
lines = [
|
||
"Диагностика модерации",
|
||
"Чат: %s (%s)" % (chat_id, _chat_type(chat) or "неизвестно"),
|
||
"Бот: @%s (%s), статус: %s" % (username or "неизвестно", bot_id, status),
|
||
rights,
|
||
"Планировщик: %s" % (self.planner.url if isinstance(self.planner, HttpPlanner) else "встроенный"),
|
||
"Токен планировщика: %s"
|
||
% ("настроен" if getattr(self.planner, "configured", True) else "не задан"),
|
||
"База бота: %s" % ("настроена" if self.bot_db else "не задана"),
|
||
"База шлюза: %s" % ("настроена" if has_newapi else "не задана"),
|
||
"Режим ответов: %s (%s)" % (mode, MODE_HINTS.get(mode, "")),
|
||
"Таблицы: mod_seen_members, mod_chat_settings, mod_restrictions",
|
||
]
|
||
markup = None
|
||
if username:
|
||
markup = InlineKeyboardMarkup(
|
||
inline_keyboard=[
|
||
[
|
||
InlineKeyboardButton(
|
||
text="Добавить бота в чат",
|
||
url="https://t.me/%s?startgroup=setup" % username,
|
||
)
|
||
]
|
||
]
|
||
)
|
||
await self.send_text(None, "\n".join(lines), reply_markup=markup, chat=chat)
|
||
return ""
|
||
|
||
async def _chatmode(self, message, args) -> str:
|
||
chat = getattr(message, "chat", None)
|
||
chat_id = int(getattr(chat, "id", 0) or 0)
|
||
await self._require_group_admin(message)
|
||
args = [str(a).strip().lower() for a in args if str(a).strip()]
|
||
if not args:
|
||
mode = await self.chat_mode(chat_id)
|
||
return "Режим ответов: %s (%s)." % (mode, MODE_HINTS.get(mode, ""))
|
||
if len(args) > 1:
|
||
return "Укажите один режим: addressed, quiet или normal."
|
||
requested = args[0]
|
||
if requested not in MODE_TO_GO:
|
||
return "Режим должен быть addressed, quiet или normal."
|
||
plan = await self._plan(
|
||
"chatmode",
|
||
message,
|
||
[MODE_TO_GO[requested]],
|
||
actor_allowed=True,
|
||
bot_allowed=True,
|
||
)
|
||
mode = MODE_FROM_GO.get(plan.mode, "")
|
||
if not mode:
|
||
return "Планировщик вернул неизвестный режим. Настройка не изменена."
|
||
actor_uid = int(getattr(getattr(message, "from_user", None), "id", 0) or 0)
|
||
if not await self.set_chat_mode(chat_id, mode, actor_uid):
|
||
return "Не удалось сохранить режим. Настройка не изменена."
|
||
return "Режим ответов: %s (%s)." % (mode, MODE_HINTS.get(mode, ""))
|
||
|
||
async def apply_parent_mode(self, chat_id: int, parent_mode: str, actor: int = 0) -> bool:
|
||
"""Map a parent group-reply setting (off/mentions/reply) to a mode."""
|
||
mode = MODE_FROM_PARENT.get(str(parent_mode or "").strip().lower(), "")
|
||
if not mode:
|
||
return False
|
||
return await self.set_chat_mode(chat_id, mode, actor)
|
||
|
||
|
||
MSG_INTERNAL = "Команда не выполнена: внутренняя ошибка модерации."
|
||
|
||
_REGISTERED: set = set()
|
||
|
||
|
||
def _register(router, name: str, callback, owner) -> bool:
|
||
"""Register as outer middleware so unhandled updates still reach the hook."""
|
||
observer = getattr(router, name, None)
|
||
if observer is None:
|
||
return False
|
||
key = (id(router), name, id(owner))
|
||
if key in _REGISTERED:
|
||
return True
|
||
for attribute in ("outer_middleware", "middleware"):
|
||
registrar = getattr(observer, attribute, None)
|
||
if callable(registrar):
|
||
registrar(callback)
|
||
_REGISTERED.add(key)
|
||
return True
|
||
return False
|
||
|
||
|
||
class ModerationBridge(ModerationBridge):
|
||
"""Adds polling-side middleware and installation helpers."""
|
||
|
||
async def _warm(self, message) -> None:
|
||
chat = getattr(message, "chat", None)
|
||
if _chat_type(chat) in ("group", "supergroup"):
|
||
await self.chat_mode(int(getattr(chat, "id", 0) or 0))
|
||
|
||
async def _handle_if_command(self, message) -> bool:
|
||
chat = getattr(message, "chat", None)
|
||
if _chat_type(chat) not in ("group", "supergroup", "private"):
|
||
return False
|
||
sender = getattr(message, "from_user", None)
|
||
if sender is None or getattr(sender, "is_bot", False):
|
||
return False
|
||
text = getattr(message, "text", None)
|
||
if not isinstance(text, str) or not text.lstrip().startswith("/"):
|
||
return False
|
||
match = _COMMAND_RE.match(text.strip())
|
||
if match is None:
|
||
return False
|
||
name = (match.group("name") or "").lower()
|
||
if name not in ALL_COMMANDS and name != "start":
|
||
return False
|
||
suffix = match.group("mention")
|
||
if suffix:
|
||
username = await self.bot_username()
|
||
if not username or _norm_username(suffix) != username:
|
||
return False
|
||
else:
|
||
await self.identity()
|
||
args = (match.group("rest") or "").split()
|
||
try:
|
||
if name == "start":
|
||
if _chat_type(chat) == "private" or not args or args[0].lower() != "setup":
|
||
return False
|
||
await self._require_group_admin(message)
|
||
await self._diagnostics(chat)
|
||
return True
|
||
answer = await self.handle_command(message, name, args)
|
||
except PlannerRejected as exc:
|
||
await self.send_text(message, str(exc) or "Запрос модерации отклонён.")
|
||
return True
|
||
except PlannerUnavailable as exc:
|
||
log.warning("moderation: planner unavailable: %s", _short_error(exc))
|
||
await self.send_text(message, MSG_UNAVAILABLE)
|
||
return True
|
||
except _Refusal as exc:
|
||
await self.send_text(message, str(exc))
|
||
return True
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.exception("moderation: command %s failed: %s", name, _short_error(exc))
|
||
await self.send_text(message, MSG_INTERNAL)
|
||
return True
|
||
if answer:
|
||
await self.send_text(message, answer)
|
||
return True
|
||
|
||
async def middleware(self, handler, event, data):
|
||
"""Outer aiogram message middleware; consumes handled commands."""
|
||
try:
|
||
await self.observe_message(event)
|
||
if getattr(event, "new_chat_members", None):
|
||
await self.on_new_chat_members(event)
|
||
await self._warm(event)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.warning("moderation: observation failed: %s", _short_error(exc))
|
||
if await self._handle_if_command(event):
|
||
return None
|
||
return await handler(event, data)
|
||
|
||
async def chat_member_middleware(self, handler, event, data):
|
||
try:
|
||
await self.on_chat_member(event)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.warning("moderation: chat_member hook failed: %s", _short_error(exc))
|
||
return await handler(event, data)
|
||
|
||
async def new_chat_members_middleware(self, handler, event, data):
|
||
try:
|
||
await self.on_new_chat_members(event)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
log.warning("moderation: new_chat_members hook failed: %s", _short_error(exc))
|
||
return await handler(event, data)
|
||
|
||
|
||
def install(namespace, router, *, planner=None, clock=None) -> ModerationBridge:
|
||
"""Create (once) and register the bridge on ``router``.
|
||
|
||
``namespace`` is normally ``globals()`` of the bot module. Registration is
|
||
idempotent for the same router/bridge pair. Returns the bridge.
|
||
"""
|
||
if not isinstance(namespace, dict):
|
||
raise TypeError("install() expects the bot module globals()")
|
||
bridge = namespace.get("_MODERATION_BRIDGE")
|
||
if not isinstance(bridge, ModerationBridge):
|
||
bridge = ModerationBridge(namespace, planner=planner, clock=clock)
|
||
namespace["_MODERATION_BRIDGE"] = bridge
|
||
elif planner is not None:
|
||
bridge.planner = planner
|
||
namespace.setdefault("moderation_bridge", bridge)
|
||
namespace.setdefault("moderation_allow_group_message", bridge.allow_group_message)
|
||
namespace.setdefault("moderation_should_reply", bridge.should_reply)
|
||
|
||
if not _register(router, "message", bridge.middleware, bridge):
|
||
raise TypeError("install() needs a Router/Dispatcher with message middleware")
|
||
_register(router, "chat_member", bridge.chat_member_middleware, bridge)
|
||
return bridge
|
||
|
||
|
||
__all__ = [
|
||
"HttpPlanner",
|
||
"ModerationBridge",
|
||
"PlannerError",
|
||
"PlannerRejected",
|
||
"PlannerUnavailable",
|
||
"TargetResolution",
|
||
"install",
|
||
"parse_plan_response",
|
||
] |