Бот для капчи в чатах
db.py
@@ -153,6 +153,13 @@
    "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)",
)
@@ -811,3 +818,29 @@
    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, keep: int = 200) -> None:
    # Храним последние keep сообщений на чат.
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO messages (chat_id, user_id, name, text, created_at) VALUES (?, ?, ?, ?, ?)",
            (chat_id, user_id, name, text, ts),
        )
        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()
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]