Бот для капчи в чатах
web/views.py
@@ -20,6 +20,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": "Медленный режим в тревоге, сек",
}
@@ -66,8 +74,16 @@
        if k[0] in ids
    ]
    logs = [row for row in await db.list_log(limit=300) if row["chat_id"] in ids][:10]
    alarms = [r for r in await db.list_alarm_chats() if r["chat_id"] in ids]
    return render(
        request, "dashboard.html", active="dash", st=st, captchas=captchas, logs=logs, names=names
        request,
        "dashboard.html",
        active="dash",
        st=st,
        captchas=captchas,
        logs=logs,
        names=names,
        alarms=alarms,
    )
@@ -75,7 +91,8 @@
    user = await _user(request)
    chats = await allowed_chats(user["user_id"])
    cfgs = {c["chat_id"]: await db.get_chat_cfg(c["chat_id"]) for c in chats}
    return render(request, "chats.html", active="chats", chats=chats, cfgs=cfgs)
    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 chat_page(request) -> web.Response:
@@ -104,6 +121,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(
@@ -150,6 +169,38 @@
    )
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 say(request) -> web.Response:
    # Отправка сообщения в чат от имени Амадеуса с указанием автора.
    user = await _user(request)
    data = await request.post()
    chat_id = int(data["chat_id"])
    text = (data.get("text") or "").strip()
    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())
        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 alarm_toggle(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
@@ -160,7 +211,12 @@
    if not await pm.check_perm(chat_id, user["user_id"], P_ALARM):
        raise web.HTTPForbidden()
    if enabled:
        await alarm.enable_alarm(chat_id, user["user_id"])
        try:
            hours = int(data.get("hours", "24"))
        except ValueError:
            hours = 24
        hours = max(1, min(720, hours))
        await alarm.enable_alarm(chat_id, user["user_id"], now_ts() + hours * 3600)
    else:
        await alarm.disable_alarm(chat_id, user["user_id"])
    raise web.HTTPFound(f"/chats/{chat_id}")
@@ -175,6 +231,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}")
@@ -195,6 +291,14 @@
            "warn_limit": int(data["warn_limit"]),
            "warn_action": data["warn_action"],
            "warn_duration": int(data["warn_duration"]),
            "flood_enabled": int(data.get("flood_enabled", "0")),
            "flood_count": int(data["flood_count"]),
            "flood_window": int(data["flood_window"]),
            "flood_mute": int(data["flood_mute"]),
            "flood_alarm_mute": int(data["flood_alarm_mute"]),
            "new_member_days": int(data["new_member_days"]),
            "no_links": int(data.get("no_links", "0")),
            "slow_mode": int(data["slow_mode"]),
        }
    except (KeyError, ValueError):
        raise web.HTTPFound(f"/chats/{chat_id}?err=cfg")
@@ -315,6 +419,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()
@@ -343,19 +474,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)