Бот для капчи в чатах
Roman Sergienko
12 hours ago 9318fc842964d6de64b778cd5c617c6859ca56a2
web/views.py
@@ -63,7 +63,11 @@
async def dashboard(request) -> web.Response:
    user = await _user(request)
    user = request["user"]
    if user is None:
        if request.headers.get("X-Telegram-Web-App-Platform"):
            raise web.HTTPFound("/miniapp")
        raise web.HTTPFound("/login")
    chats = await allowed_chats(user["user_id"])
    ids = {c["chat_id"] for c in chats}
    names = {c["chat_id"]: c["title"] for c in chats}
@@ -88,11 +92,80 @@
async def chats_page(request) -> web.Response:
    user = await _user(request)
    user = request["user"]
    if user is None:
        if request.headers.get("X-Telegram-Web-App-Platform"):
            raise web.HTTPFound("/miniapp")
        raise web.HTTPFound("/login")
    chats = await allowed_chats(user["user_id"])
    cfgs = {c["chat_id"]: await db.get_chat_cfg(c["chat_id"]) for c in chats}
    alarms = {r["chat_id"]: r for r in await db.list_alarm_chats()}
    return render(request, "chats.html", active="chats", chats=chats, cfgs=cfgs, alarms=alarms)
async def miniapp_page(request) -> web.Response:
    """Выбирает стартовый экран Mini App по проверенному initData Telegram."""
    init_data = request.query.get("tgWebAppData", "")
    from web.auth import verify_webapp_init_data
    verified = verify_webapp_init_data(init_data) if init_data else None
    if not verified:
        raise web.HTTPUnauthorized(text="Откройте панель через Telegram.")
    try:
        tg_user = json.loads(verified["user"])
        user_id = int(tg_user["id"])
    except (KeyError, TypeError, ValueError):
        raise web.HTTPUnauthorized(text="Не удалось проверить пользователя Telegram.")
    if request["user"] is None or request["user"]["user_id"] != user_id:
        # Создаём веб-сессию на основании только что проверенного initData.
        ts = now_ts()
        await db.upsert_web_user(
            user_id,
            tg_user.get("first_name", ""),
            tg_user.get("last_name", ""),
            tg_user.get("username", ""),
            tg_user.get("photo_url", ""),
            ts,
        )
        from web.auth import COOKIE, SESS_TTL
        token = await db.create_sess(user_id, ts, SESS_TTL)
        response = web.HTTPFound(request.path_qs)
        response.set_cookie(
            COOKIE,
            token,
            max_age=SESS_TTL,
            httponly=True,
            samesite="None",
            secure=True,
        )
        raise response
    chats = await allowed_chats(user_id)
    available_ids = {c["chat_id"] for c in chats}
    context = None
    try:
        chat = json.loads(verified.get("chat", "{}"))
        candidate = int(chat.get("id", 0)) if chat else 0
        if not candidate and verified.get("chat_instance"):
            instance = verified["chat_instance"]
            candidate = int(instance) if instance.lstrip("-").isdigit() else 0
        if candidate in available_ids:
            context = candidate
    except (TypeError, ValueError):
        pass
    if context is None:
        context = request.query.get("chat_id", "")
        try:
            context = int(context)
        except (TypeError, ValueError):
            context = 0
        if context not in available_ids:
            context = 0
    if context:
        raise web.HTTPFound(f"/chats/{context}")
    raise web.HTTPFound("/chats")
async def chat_page(request) -> web.Response:
@@ -181,26 +254,99 @@
    )
async def _deliver(chat_id: int, name: str, text: str, reply_id: int) -> int:
    # Возвращает tg message_id или -1 при ошибке.
    prefix = f"От {name}:\n{text}"
    try:
        msg = await bot.send_message(chat_id, prefix, reply_to_message_id=reply_id or None)
        return getattr(msg, "message_id", 0)
    except Exception as e:
        logger.warning("say failed chat=%s: %s", chat_id, e)
        if reply_id:
            try:
                msg = await bot.send_message(chat_id, prefix)
                return getattr(msg, "message_id", 0)
            except Exception as e2:
                logger.warning("say retry failed chat=%s: %s", chat_id, e2)
        return -1
async def say(request) -> web.Response:
    # Отправка сообщения в чат от имени Амадеуса с указанием автора.
    user = await _user(request)
    data = await request.post()
    chat_id = int(data["chat_id"])
    text = (data.get("text") or "").strip()
    reply_id = int(data.get("reply_to") or 0)
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    if not text:
        raise web.HTTPFound(f"/chats/{chat_id}/messages")
    name = user.get("first_name") or str(user["user_id"])
    try:
        await bot.send_message(chat_id, f"От {name}:\n{text}")
        await db.add_msg(chat_id, user["user_id"], f"Amadeus / {name}", text, now_ts())
    tg_id = await _deliver(chat_id, name, text, reply_id)
    if tg_id >= 0:
        await db.add_msg(chat_id, user["user_id"], f"Amadeus / {name}", text, now_ts(), tg_id)
        await db.add_log(chat_id, user["user_id"], 0, "say", text[:200], now_ts())
    except Exception as e:
        logger.warning("say failed chat=%s: %s", chat_id, e)
    raise web.HTTPFound(f"/chats/{chat_id}/messages")
async def api_messages(request) -> web.Response:
    user = await _user(request)
    try:
        chat_id = int(request.query["chat_id"])
        after = int(request.query.get("after", "0") or 0)
    except (KeyError, ValueError):
        return web.json_response({"ok": False}, status=400)
    if chat_id not in await _allowed_ids(user["user_id"]):
        return web.json_response({"ok": False}, status=403)
    rows = await db.list_msgs_after(chat_id, after, 200)
    for row in rows:
        row["time"] = fmt_dt(row["created_at"])
    return web.json_response({"messages": rows})
async def api_say(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    try:
        chat_id = int(data["chat_id"])
    except (KeyError, ValueError):
        return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
    text = (data.get("text") or "").strip()
    reply_id = int(data.get("reply_to") or 0)
    if chat_id not in await _allowed_ids(user["user_id"]):
        return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
    if not text:
        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,
        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,
        "message": {
            "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,
        },
    })
async def alarm_toggle(request) -> web.Response:
    user = await _user(request)
    data = await request.post()