Бот для капчи в чатах
db.py
@@ -9,7 +9,15 @@
    DB_DIR,
    DB_PATH,
    DEF_BTN_COUNT,
    DEF_FLOOD_ALARM_MUTE,
    DEF_FLOOD_COUNT,
    DEF_FLOOD_ENABLED,
    DEF_FLOOD_MUTE,
    DEF_FLOOD_WINDOW,
    DEF_MAX_ATTEMPTS,
    DEF_NEW_MEMBER_DAYS,
    DEF_NO_LINKS,
    DEF_SLOW_MODE,
    DEF_TIMEOUT,
    DEF_WARN_ACTION,
    DEF_WARN_DURATION,
@@ -25,6 +33,14 @@
    "warn_limit",
    "warn_action",
    "warn_duration",
    "flood_enabled",
    "flood_count",
    "flood_window",
    "flood_mute",
    "flood_alarm_mute",
    "new_member_days",
    "no_links",
    "slow_mode",
)
SQL_TABLES = (
@@ -35,14 +51,23 @@
    "max_attempts INTEGER DEFAULT 3, "
    "warn_limit INTEGER DEFAULT 3, "
    "warn_action TEXT DEFAULT 'mute', "
    "warn_duration INTEGER DEFAULT 3600)",
    "warn_duration INTEGER DEFAULT 3600, "
    "flood_enabled INTEGER DEFAULT 1, "
    "flood_count INTEGER DEFAULT 10, "
    "flood_window INTEGER DEFAULT 5, "
    "flood_mute INTEGER DEFAULT 30, "
    "flood_alarm_mute INTEGER DEFAULT 86400, "
    "new_member_days INTEGER DEFAULT 7, "
    "no_links INTEGER DEFAULT 0, "
    "slow_mode INTEGER DEFAULT 10)",
    "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)",
    "active INTEGER DEFAULT 1, "
    "msgs INTEGER DEFAULT 0)",
    "CREATE TABLE IF NOT EXISTS usr_fails ("
    "user_id INTEGER, "
    "chat_id INTEGER, "
@@ -92,6 +117,50 @@
    "username TEXT, "
    "photo_url TEXT, "
    "last_login INTEGER)",
    "CREATE TABLE IF NOT EXISTS users ("
    "user_id INTEGER PRIMARY KEY, "
    "username TEXT, "
    "first_name TEXT, "
    "last_name TEXT, "
    "updated_at INTEGER)",
    "CREATE TABLE IF NOT EXISTS reports ("
    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "target_id INTEGER, "
    "text TEXT, "
    "created_at INTEGER, "
    "status TEXT DEFAULT 'new', "
    "target_msg_id INTEGER DEFAULT 0, "
    "target_text TEXT DEFAULT '')",
    "CREATE TABLE IF NOT EXISTS report_block ("
    "user_id INTEGER, "
    "chat_id INTEGER, "
    "until INTEGER, "
    "PRIMARY KEY (user_id, chat_id))",
    "CREATE TABLE IF NOT EXISTS alarm ("
    "chat_id INTEGER PRIMARY KEY, "
    "enabled INTEGER DEFAULT 0, "
    "enabled_by INTEGER, "
    "enabled_at INTEGER, "
    "raid_until INTEGER, "
    "until INTEGER DEFAULT 0)",
    "CREATE TABLE IF NOT EXISTS member_join ("
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "joined_at INTEGER, "
    "PRIMARY KEY (chat_id, user_id))",
    "CREATE TABLE IF NOT EXISTS dm_users ("
    "user_id INTEGER PRIMARY KEY, "
    "ts INTEGER)",
    "CREATE TABLE IF NOT EXISTS messages ("
    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "name TEXT, "
    "text TEXT, "
    "created_at INTEGER, "
    "tg_msg_id INTEGER DEFAULT 0)",
)
@@ -126,14 +195,35 @@
        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 колонками системы предупреждений.
    # Дополняем 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")
        add_cols = {
            "warn_limit": "INTEGER DEFAULT 3",
            "warn_action": "TEXT DEFAULT 'mute'",
            "warn_duration": "INTEGER DEFAULT 3600",
            "flood_enabled": "INTEGER DEFAULT 1",
            "flood_count": "INTEGER DEFAULT 10",
            "flood_window": "INTEGER DEFAULT 5",
            "flood_mute": "INTEGER DEFAULT 30",
            "flood_alarm_mute": "INTEGER DEFAULT 86400",
            "new_member_days": "INTEGER DEFAULT 7",
            "no_links": "INTEGER DEFAULT 0",
            "slow_mode": "INTEGER DEFAULT 10",
        }
        for col, ddl in add_cols.items():
            if not await col_exists(db, "chat_cfg", col):
                await db.execute(f"ALTER TABLE chat_cfg ADD COLUMN {col} {ddl}")
    if await tbl_exists(db, "alarm") and not await col_exists(db, "alarm", "until"):
        await db.execute("ALTER TABLE alarm ADD COLUMN until INTEGER DEFAULT 0")
    if await tbl_exists(db, "reports"):
        if not await col_exists(db, "reports", "target_msg_id"):
            await db.execute("ALTER TABLE reports ADD COLUMN target_msg_id INTEGER DEFAULT 0")
        if not await col_exists(db, "reports", "target_text"):
            await db.execute("ALTER TABLE reports ADD COLUMN target_text TEXT DEFAULT ''")
    if await tbl_exists(db, "chats") and not await col_exists(db, "chats", "msgs"):
        await db.execute("ALTER TABLE chats ADD COLUMN msgs INTEGER DEFAULT 0")
    if await tbl_exists(db, "messages") and not await col_exists(db, "messages", "tg_msg_id"):
        await db.execute("ALTER TABLE messages ADD COLUMN tg_msg_id INTEGER DEFAULT 0")
async def init_db() -> None:
@@ -152,10 +242,11 @@
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) "
            "INSERT INTO chats (chat_id, title, type, added_at, updated_at, active, msgs) "
            "VALUES (?, ?, ?, ?, ?, 1, 1) "
            "ON CONFLICT(chat_id) DO UPDATE SET "
            "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, active=1",
            "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, "
            "active=1, msgs=msgs+1",
            (chat_id, title, ctype, ts, ts),
        )
        await db.commit()
@@ -194,6 +285,14 @@
        "warn_limit": DEF_WARN_LIMIT,
        "warn_action": DEF_WARN_ACTION,
        "warn_duration": DEF_WARN_DURATION,
        "flood_enabled": DEF_FLOOD_ENABLED,
        "flood_count": DEF_FLOOD_COUNT,
        "flood_window": DEF_FLOOD_WINDOW,
        "flood_mute": DEF_FLOOD_MUTE,
        "flood_alarm_mute": DEF_FLOOD_ALARM_MUTE,
        "new_member_days": DEF_NEW_MEMBER_DAYS,
        "no_links": DEF_NO_LINKS,
        "slow_mode": DEF_SLOW_MODE,
    }
@@ -405,6 +504,36 @@
        }
async def stats_scoped(ids, ts: int) -> dict:
    # Статистика только по доступным пользователю чатам (для дашборда).
    result = {"chats": len(ids), "warns": 0, "mutes": 0, "bans": 0, "logs": 0}
    ids = list(ids)
    if not ids:
        return result
    ph = ",".join("?" for _ in ids)
    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]
        result["warns"] = await one(
            f"SELECT COUNT(*) FROM warns WHERE chat_id IN ({ph}) "
            f"AND (expires_at IS NULL OR expires_at > ?)",
            tuple(ids) + (ts,),
        )
        result["mutes"] = await one(
            f"SELECT COUNT(*) FROM punish WHERE chat_id IN ({ph}) AND active=1 AND kind='mute'",
            tuple(ids),
        )
        result["bans"] = await one(
            f"SELECT COUNT(*) FROM punish WHERE chat_id IN ({ph}) AND active=1 AND kind='ban'",
            tuple(ids),
        )
        result["logs"] = await one(
            f"SELECT COUNT(*) FROM mod_log WHERE chat_id IN ({ph})", tuple(ids)
        )
    return result
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(
@@ -507,3 +636,225 @@
        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
# --- Кеш пользователей (для поиска по @username) ---
async def upsert_user(user_id: int, username: Optional[str], first_name: Optional[str], last_name: Optional[str], ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO users (user_id, username, first_name, last_name, updated_at) "
            "VALUES (?, ?, ?, ?, ?) "
            "ON CONFLICT(user_id) DO UPDATE SET "
            "username=excluded.username, first_name=excluded.first_name, "
            "last_name=excluded.last_name, updated_at=excluded.updated_at",
            (user_id, username, first_name, last_name, ts),
        )
        await db.commit()
async def find_user_by_username(username: str) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM users WHERE lower(username)=lower(?) ORDER BY updated_at DESC LIMIT 1",
            (username.lstrip("@"),),
        ) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
async def get_user(user_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM users WHERE user_id=?", (user_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
# --- Репорты ---
async def add_report(chat_id: int, user_id: int, target_id: int, text: str, ts: int, target_msg_id: int = 0, target_text: str = "") -> int:
    async with db_conn() as db:
        cur = await db.execute(
            "INSERT INTO reports (chat_id, user_id, target_id, text, created_at, status, target_msg_id, target_text) "
            "VALUES (?, ?, ?, ?, ?, 'new', ?, ?)",
            (chat_id, user_id, target_id, text, ts, target_msg_id, target_text),
        )
        await db.commit()
        return cur.lastrowid
async def get_report(report_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM reports WHERE id=?", (report_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
async def clr_reports(chat_id: int) -> None:
    async with db_conn() as db:
        await db.execute("DELETE FROM reports WHERE chat_id=?", (chat_id,))
        await db.commit()
async def list_reports(chat_id: int, limit: int = 200) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM reports WHERE chat_id=? ORDER BY created_at DESC LIMIT ?",
            (chat_id, limit),
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]
async def cnt_reports_since(chat_id: int, user_id: int, since: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT COUNT(*) FROM reports WHERE chat_id=? AND user_id=? AND created_at >= ?",
            (chat_id, user_id, since),
        ) as cur:
            return (await cur.fetchone())[0]
async def close_report(report_id: int) -> None:
    async with db_conn() as db:
        await db.execute("UPDATE reports SET status='closed' WHERE id=?", (report_id,))
        await db.commit()
async def report_block_until(chat_id: int, user_id: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT until FROM report_block WHERE chat_id=? AND user_id=?", (chat_id, user_id)
        ) as cur:
            row = await cur.fetchone()
    return row[0] if row else 0
async def set_report_block(chat_id: int, user_id: int, until: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO report_block (user_id, chat_id, until) VALUES (?, ?, ?) "
            "ON CONFLICT(user_id, chat_id) DO UPDATE SET until=excluded.until",
            (user_id, chat_id, until),
        )
        await db.commit()
# --- Режим тревоги ---
async def get_alarm(chat_id: int) -> dict:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM alarm WHERE chat_id=?", (chat_id,)) as cur:
            row = await cur.fetchone()
    if row:
        return dict(row)
    return {"chat_id": chat_id, "enabled": 0, "enabled_by": 0, "enabled_at": 0, "raid_until": 0, "until": 0}
async def set_alarm(chat_id: int, enabled: bool, by: int, ts: int, until: int = 0) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO alarm (chat_id, enabled, enabled_by, enabled_at, raid_until, until) "
            "VALUES (?, ?, ?, ?, 0, ?) "
            "ON CONFLICT(chat_id) DO UPDATE SET "
            "enabled=excluded.enabled, enabled_by=excluded.enabled_by, "
            "enabled_at=excluded.enabled_at, until=excluded.until",
            (chat_id, 1 if enabled else 0, by, ts, until if enabled else 0),
        )
        # При выключении сбрасываем авто-кик.
        if not enabled:
            await db.execute("UPDATE alarm SET raid_until=0 WHERE chat_id=?", (chat_id,))
        await db.commit()
async def set_raid_until(chat_id: int, until: int) -> None:
    async with db_conn() as db:
        await db.execute("UPDATE alarm SET raid_until=? WHERE chat_id=?", (until, chat_id))
        await db.commit()
async def expired_alarms(ts: int) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM alarm WHERE enabled=1 AND until > 0 AND until <= ?", (ts,)
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]
async def list_alarm_chats() -> List[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM alarm WHERE enabled=1") as cur:
            return [dict(r) for r in await cur.fetchall()]
# --- Время входа и ЛС-подписка ---
async def set_join(chat_id: int, user_id: int, ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO member_join (chat_id, user_id, joined_at) VALUES (?, ?, ?) "
            "ON CONFLICT(chat_id, user_id) DO UPDATE SET joined_at=excluded.joined_at",
            (chat_id, user_id, ts),
        )
        await db.commit()
async def get_join(chat_id: int, user_id: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT joined_at FROM member_join WHERE chat_id=? AND user_id=?", (chat_id, user_id)
        ) as cur:
            row = await cur.fetchone()
    return row[0] if row else 0
async def add_dm(user_id: int, ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO dm_users (user_id, ts) VALUES (?, ?) "
            "ON CONFLICT(user_id) DO UPDATE SET ts=excluded.ts",
            (user_id, ts),
        )
        await db.commit()
async def has_dm(user_id: int) -> bool:
    async with db_conn() as db:
        async with db.execute("SELECT 1 FROM dm_users WHERE user_id=?", (user_id,)) as cur:
            return await cur.fetchone() is not None
# --- Последние сообщения чата ---
async def add_msg(chat_id: int, user_id: int, name: str, text: str, ts: int, tg_msg_id: int = 0, keep: int = 200) -> int:
    # Храним последние keep сообщений на чат.
    async with db_conn() as db:
        cur = await db.execute(
            "INSERT INTO messages (chat_id, user_id, name, text, created_at, tg_msg_id) "
            "VALUES (?, ?, ?, ?, ?, ?)",
            (chat_id, user_id, name, text, ts, tg_msg_id),
        )
        await db.execute(
            "DELETE FROM messages WHERE chat_id=? AND id NOT IN "
            "(SELECT id FROM messages WHERE chat_id=? ORDER BY id DESC LIMIT ?)",
            (chat_id, chat_id, keep),
        )
        await db.commit()
        return cur.lastrowid
async def list_msgs(chat_id: int, limit: int = 100) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM messages WHERE chat_id=? ORDER BY id DESC LIMIT ?", (chat_id, limit)
        ) as cur:
            rows = [dict(r) for r in await cur.fetchall()]
    return rows[::-1]
async def list_msgs_after(chat_id: int, after_id: int, limit: int = 100) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM messages WHERE chat_id=? AND id > ? ORDER BY id ASC LIMIT ?",
            (chat_id, after_id, limit),
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]