Бот для капчи в чатах
feat web: чат пузырями (свои/чужие), превью реплаев, подгрузка фото/стикеров/медиа через бота
1 files added
5 files modified
246 ■■■■■ changed files
db.py 60 ●●●●● patch | view | raw | blame | history
track.py 35 ●●●●● patch | view | raw | blame | history
web/app.py 3 ●●●●● patch | view | raw | blame | history
web/media.py 44 ●●●●● patch | view | raw | blame | history
web/templates/messages.html 90 ●●●●● patch | view | raw | blame | history
web/views.py 14 ●●●●● patch | view | raw | blame | history
db.py
@@ -160,7 +160,12 @@
    "name TEXT, "
    "text TEXT, "
    "created_at INTEGER, "
    "tg_msg_id INTEGER DEFAULT 0)",
    "tg_msg_id INTEGER DEFAULT 0, "
    "media_type TEXT DEFAULT '', "
    "media_file_id TEXT DEFAULT '', "
    "reply_to_tg INTEGER DEFAULT 0, "
    "reply_to_name TEXT DEFAULT '', "
    "reply_to_text TEXT DEFAULT '')",
)
@@ -222,8 +227,18 @@
            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")
    if await tbl_exists(db, "messages"):
        msg_cols = {
            "tg_msg_id": "INTEGER DEFAULT 0",
            "media_type": "TEXT DEFAULT ''",
            "media_file_id": "TEXT DEFAULT ''",
            "reply_to_tg": "INTEGER DEFAULT 0",
            "reply_to_name": "TEXT DEFAULT ''",
            "reply_to_text": "TEXT DEFAULT ''",
        }
        for col, ddl in msg_cols.items():
            if not await col_exists(db, "messages", col):
                await db.execute(f"ALTER TABLE messages ADD COLUMN {col} {ddl}")
async def init_db() -> None:
@@ -825,13 +840,27 @@
# --- Последние сообщения чата ---
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:
async def add_msg(
    chat_id: int,
    user_id: int,
    name: str,
    text: str,
    ts: int,
    tg_msg_id: int = 0,
    media_type: str = "",
    media_file_id: str = "",
    reply_to_tg: int = 0,
    reply_to_name: str = "",
    reply_to_text: str = "",
    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),
            "INSERT INTO messages "
            "(chat_id, user_id, name, text, created_at, tg_msg_id, media_type, media_file_id, reply_to_tg, reply_to_name, reply_to_text) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (chat_id, user_id, name, text, ts, tg_msg_id, media_type, media_file_id, reply_to_tg, reply_to_name, reply_to_text),
        )
        await db.execute(
            "DELETE FROM messages WHERE chat_id=? AND id NOT IN "
@@ -842,6 +871,23 @@
        return cur.lastrowid
async def get_msg(msg_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM messages WHERE id=?", (msg_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
async def find_msg_by_tg(chat_id: int, tg_msg_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM messages WHERE chat_id=? AND tg_msg_id=? ORDER BY id DESC LIMIT 1",
            (chat_id, tg_msg_id),
        ) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
async def list_msgs(chat_id: int, limit: int = 100) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
track.py
@@ -5,6 +5,24 @@
from util import now_ts
def _media_of(event: types.Message):
    # Тип медиа и file_id для отображения в панели.
    if event.photo:
        return "photo", event.photo[-1].file_id
    if event.sticker:
        st = event.sticker
        return "sticker", (st.thumbnail.file_id if st.thumbnail else st.file_id)
    if event.animation:
        an = event.animation
        return "animation", (an.thumbnail.file_id if an.thumbnail else an.file_id)
    if event.video:
        v = event.video
        return "video", (v.thumbnail.file_id if v.thumbnail else "")
    if event.document and (event.document.mime_type or "").startswith("image/"):
        return "photo", event.document.file_id
    return "", ""
@dp.message.middleware()
async def track_msg(handler, event: types.Message, data: dict):
    # Фиксируем чаты и пользователей, чтобы панель и /aperm могли их находить.
@@ -24,9 +42,22 @@
    # Лог последних сообщений для панели.
    if chat and chat.type in ("group", "supergroup") and u is not None and not u.is_bot:
        content = event.text or event.caption or ""
        if content:
        media_type, file_id = _media_of(event)
        if content or media_type:
            reply_to_tg = 0
            reply_to_name = ""
            reply_to_text = ""
            if event.reply_to_message:
                rm = event.reply_to_message
                reply_to_tg = rm.message_id
                if rm.from_user:
                    reply_to_name = rm.from_user.full_name
                reply_to_text = (rm.text or rm.caption or "")[:80]
            try:
                await db.add_msg(chat.id, u.id, u.full_name, content[:1000], ts, event.message_id)
                await db.add_msg(
                    chat.id, u.id, u.full_name, content[:1000], ts, event.message_id,
                    media_type, file_id, reply_to_tg, reply_to_name, reply_to_text,
                )
            except Exception as e:
                logger.warning("add_msg failed chat=%s: %s", chat.id, e)
    return await handler(event, data)
web/app.py
@@ -3,7 +3,7 @@
from aiohttp import web
from cfg import WEB_HOST, WEB_PORT, logger
from web import auth, avatar, views
from web import auth, avatar, media, views
BASE = pathlib.Path(__file__).resolve().parent
@@ -34,6 +34,7 @@
    app.router.add_get("/captcha", views.captcha_page)
    app.router.add_get("/log", views.log_page)
    app.router.add_get("/avatar/{chat_id}", avatar.avatar_handler)
    app.router.add_get("/media/{msg_id}", media.media_handler)
    app.router.add_static("/static", BASE / "static")
    return app
web/media.py
New file
@@ -0,0 +1,44 @@
import io
import mimetypes
from typing import Dict, Optional, Tuple
from aiohttp import web
import db
from cfg import bot, logger
# Кэш в памяти: file_id -> (байты, content-type).
_cache: Dict[str, Tuple[bytes, str]] = {}
async def get_media(file_id: str) -> Optional[Tuple[bytes, str]]:
    if file_id in _cache:
        return _cache[file_id]
    try:
        f = await bot.get_file(file_id)
        buf = io.BytesIO()
        await bot.download_file(f.file_path, buf)
        data = buf.getvalue()
    except Exception as e:
        logger.warning("media download: %s", e)
        return None
    ctype = mimetypes.guess_type(f.file_path or "")[0] or "application/octet-stream"
    _cache[file_id] = (data, ctype)
    return data, ctype
async def media_handler(request) -> web.Response:
    try:
        msg_id = int(request.match_info["msg_id"])
    except ValueError:
        raise web.HTTPNotFound()
    row = await db.get_msg(msg_id)
    if not row or not row.get("media_file_id"):
        raise web.HTTPNotFound()
    result = await get_media(row["media_file_id"])
    if not result:
        raise web.HTTPNotFound()
    data, ctype = result
    return web.Response(
        body=data, content_type=ctype, headers={"Cache-Control": "public, max-age=86400"}
    )
web/templates/messages.html
@@ -11,17 +11,31 @@
</div>
<section class="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
    <div id="msg-list" class="flex max-h-[55vh] flex-col gap-1 overflow-y-auto p-2 md:max-h-[60vh]">
    <div id="msg-list" class="flex max-h-[58vh] flex-col gap-2 overflow-y-auto p-3 md:max-h-[62vh]">
        {% for m in msgs %}
        <div class="msg rounded-lg px-3 py-2 text-sm" data-id="{{ m.id }}" data-tg="{{ m.tg_msg_id or 0 }}" data-name="{{ m.name }}">
            <div class="flex flex-wrap items-center justify-between gap-2">
                <span class="font-medium {% if m.name and m.name.startswith('Amadeus') %}text-brand-600 dark:text-brand-400{% endif %}">{{ m.name }}</span>
                <span class="flex items-center gap-2">
                    <span class="text-xs text-gray-400">{{ fmt_dt(m.created_at) }}</span>
                    <button type="button" class="reply-btn text-xs text-gray-400 hover:text-brand-500">ответить</button>
                </span>
        {% set is_bot = m.name and m.name.startswith('Amadeus') %}
        <div class="msg flex {{ 'justify-end' if is_bot else 'justify-start' }}"
             data-id="{{ m.id }}" data-tg="{{ m.tg_msg_id or 0 }}" data-name="{{ m.name }}">
            <div class="max-w-[82%] rounded-2xl px-3 py-2 text-sm shadow-sm
                {% if is_bot %}bg-brand-600 text-white{% else %}bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100{% endif %}">
                <div class="mb-0.5 text-xs font-semibold {% if is_bot %}text-white/80{% else %}text-brand-600 dark:text-brand-400{% endif %}">{{ m.name }}</div>
                {% if m.reply_to_tg %}
                <div class="mb-1 rounded-lg border-l-2 px-2 py-1 text-[11px]
                    {% if is_bot %}border-white/50 bg-white/10 text-white/80{% else %}border-brand-400 bg-black/5 text-gray-600 dark:bg-white/5 dark:text-gray-300{% endif %}">
                    <div class="font-medium">↪ {{ m.reply_to_name or "сообщение" }}</div>
                    {% if m.reply_to_text %}<div class="truncate">{{ m.reply_to_text }}</div>{% endif %}
                </div>
                {% endif %}
                {% if m.media_type %}
                <img src="/media/{{ m.id }}" alt="{{ m.media_type }}" loading="lazy"
                     class="mb-1 max-h-60 rounded-lg" onerror="this.style.display='none'">
                {% endif %}
                {% if m.text %}<div class="whitespace-pre-wrap break-words">{{ m.text }}</div>{% endif %}
                <div class="mt-1 flex items-center justify-end gap-2 text-[10px] {% if is_bot %}text-white/70{% else %}text-gray-400{% endif %}">
                    <span>{{ fmt_dt(m.created_at) }}</span>
                    <button type="button" class="reply-btn hover:underline">ответить</button>
                </div>
            </div>
            <div class="mt-0.5 whitespace-pre-wrap break-words">{{ m.text }}</div>
        </div>
        {% else %}
        <div id="empty" class="px-4 py-8 text-center text-gray-500">Сообщений пока нет.</div>
@@ -63,12 +77,12 @@
    function atBottom() { return list.scrollTop + list.clientHeight >= list.scrollHeight - 40; }
    function toBottom() { list.scrollTop = list.scrollHeight; }
    function bindReply(el) {
        const btn = el.querySelector(".reply-btn");
    function bindReply(wrap) {
        const btn = wrap.querySelector(".reply-btn");
        if (!btn) return;
        btn.addEventListener("click", function () {
            replyTo.value = el.dataset.tg || 0;
            replyName.textContent = el.dataset.name || "";
            replyTo.value = wrap.dataset.tg || 0;
            replyName.textContent = wrap.dataset.name || "";
            replyBar.classList.remove("hidden");
            replyBar.classList.add("flex");
            text.focus();
@@ -82,23 +96,42 @@
        replyBar.classList.remove("flex");
    });
    function bubble(m) {
        const isBot = (m.name || "").startsWith("Amadeus");
        const wrap = document.createElement("div");
        wrap.className = "msg flex " + (isBot ? "justify-end" : "justify-start");
        wrap.dataset.id = m.id;
        wrap.dataset.tg = m.tg_msg_id || 0;
        wrap.dataset.name = m.name || "";
        const box = document.createElement("div");
        box.className = "max-w-[82%] rounded-2xl px-3 py-2 text-sm shadow-sm " +
            (isBot ? "bg-brand-600 text-white" : "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100");
        let html = '<div class="mb-0.5 text-xs font-semibold ' +
            (isBot ? "text-white/80" : "text-brand-600 dark:text-brand-400") + '">' + esc(m.name) + "</div>";
        if (m.reply_to_tg) {
            html += '<div class="mb-1 rounded-lg border-l-2 px-2 py-1 text-[11px] ' +
                (isBot ? "border-white/50 bg-white/10 text-white/80" : "border-brand-400 bg-black/5 text-gray-600 dark:bg-white/5 dark:text-gray-300") + '">' +
                '<div class="font-medium">↪ ' + esc(m.reply_to_name || "сообщение") + "</div>" +
                (m.reply_to_text ? '<div class="truncate">' + esc(m.reply_to_text) + "</div>" : "") + "</div>";
        }
        if (m.media_type && m.id) {
            html += '<img src="/media/' + m.id + '" class="mb-1 max-h-60 rounded-lg" loading="lazy" onerror="this.style.display=\'none\'">';
        }
        if (m.text) html += '<div class="whitespace-pre-wrap break-words">' + esc(m.text) + "</div>";
        html += '<div class="mt-1 flex items-center justify-end gap-2 text-[10px] ' +
            (isBot ? "text-white/70" : "text-gray-400") + '"><span>' + esc(m.time || "") +
            '</span><button type="button" class="reply-btn hover:underline">ответить</button></div>';
        box.innerHTML = html;
        wrap.appendChild(box);
        return wrap;
    }
    function addMsg(m, scroll) {
        const empty = document.getElementById("empty");
        if (empty) empty.remove();
        const el = document.createElement("div");
        el.className = "msg rounded-lg px-3 py-2 text-sm";
        el.dataset.id = m.id;
        el.dataset.tg = m.tg_msg_id || 0;
        el.dataset.name = m.name || "";
        const isBot = (m.name || "").startsWith("Amadeus");
        el.innerHTML =
            '<div class="flex flex-wrap items-center justify-between gap-2">' +
            '<span class="font-medium ' + (isBot ? "text-brand-600 dark:text-brand-400" : "") + '">' + esc(m.name) + "</span>" +
            '<span class="flex items-center gap-2"><span class="text-xs text-gray-400">' + esc(m.time || "") + "</span>" +
            '<button type="button" class="reply-btn text-xs text-gray-400 hover:text-brand-500">ответить</button></span></div>' +
            '<div class="mt-0.5 whitespace-pre-wrap break-words">' + esc(m.text) + "</div>";
        list.appendChild(el);
        bindReply(el);
        const wrap = bubble(m);
        list.appendChild(wrap);
        bindReply(wrap);
        if (scroll) toBottom();
    }
@@ -139,7 +172,6 @@
        }
    });
    // Реалтайм: подтягиваем новые сообщения.
    async function poll() {
        try {
            const r = await fetch("/api/messages?chat_id=" + encodeURIComponent(chatId) + "&after=" + lastId);
@@ -149,7 +181,7 @@
                j.messages.forEach(function (m) { if (m.id > lastId) { addMsg(m, false); lastId = m.id; } });
                if (stick) toBottom();
            }
        } catch (err) { /* тихо игнорируем */ }
        } catch (err) { /* тихо */ }
    }
    toBottom();
web/views.py
@@ -247,10 +247,20 @@
        return web.json_response({"ok": False, "msg": "Пустое сообщение."}, status=400)
    name = user.get("first_name") or str(user["user_id"])
    ts = now_ts()
    reply_to_name = ""
    reply_to_text = ""
    if reply_id:
        rm = await db.find_msg_by_tg(chat_id, reply_id)
        if rm:
            reply_to_name = rm["name"] or ""
            reply_to_text = (rm["text"] or "")[:80]
    tg_id = await _deliver(chat_id, name, text, reply_id)
    if tg_id < 0:
        return web.json_response({"ok": False, "msg": "Не удалось отправить. Проверьте права бота."}, status=502)
    mid = await db.add_msg(chat_id, user["user_id"], f"Amadeus / {name}", text, ts, tg_id)
    mid = await db.add_msg(
        chat_id, user["user_id"], f"Amadeus / {name}", text, ts, tg_id,
        reply_to_tg=reply_id, reply_to_name=reply_to_name, reply_to_text=reply_to_text,
    )
    await db.add_log(chat_id, user["user_id"], 0, "say", text[:200], ts)
    return web.json_response({
        "ok": True,
@@ -258,6 +268,8 @@
            "id": mid, "chat_id": chat_id, "user_id": user["user_id"],
            "name": f"Amadeus / {name}", "text": text, "created_at": ts,
            "tg_msg_id": tg_id, "time": fmt_dt(ts),
            "media_type": "", "media_file_id": "",
            "reply_to_tg": reply_id, "reply_to_name": reply_to_name, "reply_to_text": reply_to_text,
        },
    })