Бот для капчи в чатах
Roman Sergienko
8 hours ago 40d1e4fb89e332ff34c0996f56eee012ec0ddb15
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,43 @@
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 по chat_id из Telegram launch URL."""
    if request["user"] is None:
        raise web.HTTPFound("/miniapp/login")
    user_id = request["user"]["user_id"]
    chats = await allowed_chats(user_id)
    available_ids = {c["chat_id"] for c in chats}
    try:
        context = int(request.query.get("chat_id", "") or 0)
    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 miniapp_login_page(request) -> web.Response:
    """Стартовая HTML-страница: получает initData через Telegram WebApp JS API."""
    if request["user"] is not None:
        raise web.HTTPFound("/miniapp")
    response = render(request, "miniapp_login.html")
    response.headers["X-Amadeus-MiniApp-Version"] = "5387fa6"
    return response
async def chat_page(request) -> web.Response:
@@ -121,6 +157,8 @@
    warns = await db.list_warns(chat_id)
    punish = await db.list_punish(chat_id, active_only=False)
    reports = await db.list_reports(chat_id)
    for r in reports:
        r["link"] = msg_link(chat_id, r.get("target_msg_id") or 0)
    alarm_state = await db.get_alarm(chat_id)
    myperms = await pm.perms_of(chat_id, user["user_id"])
    return render(
@@ -167,6 +205,111 @@
    )
async def messages_page(request) -> web.Response:
    user = await _user(request)
    chat_id = int(request.match_info["chat_id"])
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    chat = await db.get_chat(chat_id) or {"chat_id": chat_id, "title": str(chat_id)}
    msgs = await db.list_msgs(chat_id, 100)
    return render(
        request, "messages.html", active="chats", chat=chat, msgs=msgs, fmt_dt=fmt_dt
    )
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"])
    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())
    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()
@@ -197,6 +340,46 @@
        raise web.HTTPForbidden()
    if not await pm.check_perm(chat_id, user["user_id"], P_CFG):
        raise web.HTTPForbidden()
    await db.close_report(report_id)
    raise web.HTTPFound(f"/chats/{chat_id}")
async def report_clear(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    chat_id = int(data["chat_id"])
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    if not await pm.check_perm(chat_id, user["user_id"], P_CFG):
        raise web.HTTPForbidden()
    await db.clr_reports(chat_id)
    raise web.HTTPFound(f"/chats/{chat_id}")
async def report_accept(request) -> web.Response:
    # Принять репорт: сразу применить выбранное действие к его объекту.
    user = await _user(request)
    data = await request.post()
    chat_id = int(data["chat_id"])
    report_id = int(data["report_id"])
    kind = data.get("kind", "")
    reason = (data.get("reason") or "").strip()
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    rep = await db.get_report(report_id)
    if not rep or rep["chat_id"] != chat_id or kind not in ACTION_PERM:
        raise web.HTTPFound(f"/chats/{chat_id}")
    if not await pm.check_perm(chat_id, user["user_id"], ACTION_PERM[kind]):
        raise web.HTTPForbidden()
    target = rep["target_id"] or 0
    dur = None
    if kind in ("mute", "ban"):
        try:
            dur = parse_dur(data.get("dur") or "-")
        except ValueError:
            dur = None
    if target:
        await _apply_action(user["user_id"], chat_id, target, f"id {target}", kind, dur, reason or "по репорту")
    await db.close_report(report_id)
    raise web.HTTPFound(f"/chats/{chat_id}")
@@ -345,6 +528,33 @@
    )
def msg_link(chat_id: int, msg_id: int) -> str:
    # Ссылка на сообщение (работает для участников чата).
    if not msg_id or msg_id <= 0:
        return ""
    s = str(chat_id)
    internal = s[4:] if s.startswith("-100") else str(abs(chat_id))
    return f"https://t.me/c/{internal}/{msg_id}"
async def _apply_action(actor: int, chat_id: int, target_id: int, name: str, kind: str, dur, reason: str) -> None:
    # Владельца бота и самого бота не трогаем.
    if target_id == cfg.BOT_ID or target_id == cfg.OWNER_ID:
        return
    if kind == "warn":
        await mod.apply_warn(chat_id, target_id, name, actor, reason)
    elif kind == "mute":
        await mod.apply_mute(chat_id, target_id, name, dur, actor, reason)
    elif kind == "ban":
        await mod.apply_ban(chat_id, target_id, name, dur, actor, reason)
    elif kind == "unmute":
        await mod.apply_unmute(chat_id, target_id, name, actor, reason)
    elif kind == "unban":
        await mod.apply_unban(chat_id, target_id, name, actor, reason)
    elif kind == "unwarn":
        await mod.apply_unwarn(chat_id, target_id, name, actor)
async def action(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
@@ -373,19 +583,7 @@
    else:
        dur = None
    actor = user["user_id"]
    if kind == "warn":
        await mod.apply_warn(chat_id, target_id, name, actor, reason)
    elif kind == "mute":
        await mod.apply_mute(chat_id, target_id, name, dur, actor, reason)
    elif kind == "ban":
        await mod.apply_ban(chat_id, target_id, name, dur, actor, reason)
    elif kind == "unmute":
        await mod.apply_unmute(chat_id, target_id, name, actor, reason)
    elif kind == "unban":
        await mod.apply_unban(chat_id, target_id, name, actor, reason)
    elif kind == "unwarn":
        await mod.apply_unwarn(chat_id, target_id, name, actor)
    await _apply_action(user["user_id"], chat_id, target_id, name, kind, dur, reason)
    raise web.HTTPFound(back)
@@ -409,3 +607,113 @@
    ids = set(names)
    rows = [r for r in await db.list_log(limit=500) if r["chat_id"] in ids][:200]
    return render(request, "log.html", active="log", rows=rows, names=names, fmt_dt=fmt_dt)
async def rp_page(request) -> web.Response:
    user = await _user(request)
    chat_id = int(request.match_info["chat_id"])
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    chat = await db.get_chat(chat_id) or {"chat_id": chat_id, "title": str(chat_id)}
    actions = await db.list_rp_actions(chat_id)
    return render(request, "rp.html", active="chats", chat=chat, actions=actions)
async def api_rp_add(request) -> web.Response:
    try:
        user = await _user(request)
        if user is None:
            return web.json_response({"ok": False, "msg": "Не авторизован."}, status=401)
        data = await request.post()
        try:
            chat_id = int(data["chat_id"])
            trigger = (data.get("trigger") or "").strip()
            response_text = (data.get("response_text") or "").strip()
        except (KeyError, ValueError) as e:
            return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
        if chat_id not in await _allowed_ids(user["user_id"]):
            return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
        if not trigger or not response_text:
            return web.json_response({"ok": False, "msg": "Триггер и текст обязательны."}, status=400)
        # Обработка загруженной гифки
        gif_file_id = None
        if "gif" in data:
            file = data["gif"]
            if file.filename and file.file:
                try:
                    import pathlib
                    # Создаём директорию для гифок если не существует
                    gif_dir = pathlib.Path("data/rp_gifs")
                    gif_dir.mkdir(parents=True, exist_ok=True)
                    # Генерируем имя файла (timestamp + uuid)
                    import uuid
                    file_name = f"{now_ts()}_{uuid.uuid4().hex[:8]}.gif"
                    file_path = gif_dir / file_name
                    # Сохраняем файл
                    content = file.file.read()
                    with open(file_path, "wb") as f:
                        f.write(content)
                    gif_file_id = str(file_path)
                except Exception as e:
                    logger.warning("Failed to save GIF: %s", e)
        # Добавляем действие
        action_id = await db.add_rp_action(chat_id, trigger, response_text, gif_file_id, now_ts())
        if not action_id:
            return web.json_response({"ok": False, "msg": "Триггер уже существует."}, status=400)
        await db.add_log(chat_id, user["user_id"], 0, "rp_add", f"{trigger} -> {response_text[:50]}", now_ts())
        return web.json_response({"ok": True})
    except Exception as e:
        logger.exception("api_rp_add error: %s", e)
        return web.json_response({"ok": False, "msg": "Внутренняя ошибка сервера."}, status=500)
async def api_rp_delete(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    try:
        action_id = int(data["action_id"])
        chat_id = int(data["chat_id"])
    except (KeyError, ValueError):
        return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
    if chat_id not in await _allowed_ids(user["user_id"]):
        return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
    action = await db.get_rp_action(action_id)
    if not action or action["chat_id"] != chat_id:
        return web.json_response({"ok": False, "msg": "Действие не найдено."}, status=404)
    await db.delete_rp_action(action_id)
    await db.add_log(chat_id, user["user_id"], 0, "rp_delete", action["trigger"], now_ts())
    return web.json_response({"ok": True})
async def api_rp_toggle(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    try:
        action_id = int(data["action_id"])
        chat_id = int(data["chat_id"])
        enabled = data.get("enabled") == "1"
    except (KeyError, ValueError):
        return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
    if chat_id not in await _allowed_ids(user["user_id"]):
        return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
    action = await db.get_rp_action(action_id)
    if not action or action["chat_id"] != chat_id:
        return web.json_response({"ok": False, "msg": "Действие не найдено."}, status=404)
    await db.set_rp_action_enabled(action_id, enabled)
    await db.add_log(chat_id, user["user_id"], 0, "rp_enable" if enabled else "rp_disable", action["trigger"], now_ts())
    return web.json_response({"ok": True})