Бот для капчи в чатах
Roman Sergienko
8 hours ago 47fba49d1835442f096739b92a3dd3ed9476470b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
from aiohttp import web
 
import db
import mod
import alarm
import perms as pm
from captcha import CAP_STATE
import cfg
from cfg import bot, logger
from perms import P_ALARM, P_BAN, P_CFG, P_MUTE, P_PERMS, P_UNBAN, P_UNMUTE, P_UNWARN, P_WARN, PERM_LABELS
from util import fmt_dt, fmt_dur, mention, now_ts, parse_dur
from web.auth import is_staff
from web.render import render
 
# Человекочитаемые названия настроек для уведомлений в чат.
CFG_LABELS = {
    "btn_count": "Кнопки капчи",
    "timeout": "Таймаут капчи, сек",
    "max_attempts": "Попыток до наказания",
    "warn_limit": "Лимит варнов",
    "warn_action": "Действие при лимите",
    "warn_duration": "Длительность наказания, сек",
    "flood_enabled": "Антифлуд",
    "flood_count": "Порог сообщений",
    "flood_window": "Окно антифлуда, сек",
    "flood_mute": "Мут за флуд, сек",
    "flood_alarm_mute": "Мут за флуд в тревоге, сек",
    "new_member_days": "Новый участник, дней",
    "no_links": "Фильтр ссылок",
    "slow_mode": "Медленный режим в тревоге, сек",
}
 
 
async def _notify(chat_id: int, text: str) -> None:
    try:
        await bot.send_message(chat_id, text, parse_mode="HTML")
    except Exception as e:
        logger.warning("notify failed chat=%s: %s", chat_id, e)
 
# Соответствие действия и требуемого права.
ACTION_PERM = {
    "warn": P_WARN,
    "mute": P_MUTE,
    "ban": P_BAN,
    "unmute": P_UNMUTE,
    "unban": P_UNBAN,
    "unwarn": P_UNWARN,
}
 
 
async def allowed_chats(user_id: int):
    if is_staff(user_id):
        return await db.list_chats(active_only=True)
    return await pm.adm_chats(bot, user_id)
 
 
async def _allowed_ids(user_id: int) -> set:
    return {c["chat_id"] for c in await allowed_chats(user_id)}
 
 
async def _user(request) -> dict:
    return request["user"]
 
 
async def dashboard(request) -> web.Response:
    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}
    st = await db.stats_scoped(ids, now_ts())
    captchas = [
        {"chat_id": k[0], "user_id": k[1], "left": max(0, v.get("deadline", 0) - now_ts())}
        for k, v in CAP_STATE.items()
        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,
        alarms=alarms,
    )
 
 
async def chats_page(request) -> web.Response:
    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:
    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)}
    cfg = await db.get_chat_cfg(chat_id)
 
    admins = []
    try:
        for m in await bot.get_chat_administrators(chat_id):
            u = m.user
            admins.append(
                {
                    "id": u.id,
                    "name": u.full_name,
                    "username": u.username or "",
                    "perms": await pm.perms_of(chat_id, u.id),
                }
            )
    except Exception:
        pass
 
    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(
        request,
        "chat.html",
        active="chats",
        chat=chat,
        cfg=cfg,
        admins=admins,
        warns=warns,
        punish=punish,
        reports=reports,
        alarm=alarm_state,
        myperms=myperms,
        labels=PERM_LABELS,
        now=now_ts(),
        fmt_dt=fmt_dt,
        fmt_dur=fmt_dur,
    )
 
 
async def admin_page(request) -> web.Response:
    user = await _user(request)
    chat_id = int(request.match_info["chat_id"])
    target_id = int(request.match_info["user_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)}
    target = await db.get_user(target_id) or {"user_id": target_id}
    try:
        member = await bot.get_chat_member(chat_id, target_id)
        target = {**target, "first_name": member.user.full_name, "username": member.user.username or ""}
    except Exception:
        pass
    return render(
        request,
        "admin.html",
        active="chats",
        chat=chat,
        target_id=target_id,
        target=target,
        perms=await pm.perms_of(chat_id, target_id),
        labels=PERM_LABELS,
    )
 
 
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()
    chat_id = int(data["chat_id"])
    enabled = data.get("enabled") == "1"
    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_ALARM):
        raise web.HTTPForbidden()
    if enabled:
        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}")
 
 
async def report_close(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    chat_id = int(data["chat_id"])
    report_id = int(data["report_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.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}")
 
 
async def chat_cfg(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()
    try:
        fields = {
            "btn_count": int(data["btn_count"]),
            "timeout": int(data["timeout"]),
            "max_attempts": int(data["max_attempts"]),
            "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")
    if fields["warn_action"] not in ("mute", "ban"):
        fields["warn_action"] = "mute"
 
    old = await db.get_chat_cfg(chat_id)
    await db.save_chat_cfg(chat_id, **fields)
 
    # Сообщаем в чат, что настройки изменены из панели, и что именно поменялось.
    changed = []
    for key, new in fields.items():
        if old.get(key) != new:
            if key == "warn_action":
                prev, nxt = _act_label(old.get(key)), _act_label(new)
            else:
                prev, nxt = old.get(key), new
            changed.append(f"{CFG_LABELS.get(key, key)}: {prev} -> {nxt}")
    if changed:
        actor = user["user_id"]
        name = user.get("first_name") or str(actor)
        await db.add_log(chat_id, actor, 0, "config", "; ".join(changed), now_ts())
        await _notify(
            chat_id,
            "Настройки чата изменены через веб-панель.\n"
            f"Изменил: {mention(actor, name)}\n" + "\n".join(f"- {c}" for c in changed),
        )
    raise web.HTTPFound(f"/chats/{chat_id}")
 
 
def _act_label(value) -> str:
    return "бан" if value == "ban" else "мут"
 
 
async def _do_perm(user, chat_id: int, target_id: int, perm: str, allow: bool):
    # Общая логика смены права: применяем, логируем и уведомляем чат.
    if perm not in PERM_LABELS:
        return False, "Неизвестное право."
    ok, msg = await pm.set_perm(chat_id, user["user_id"], target_id, perm, allow)
    if ok:
        actor = user["user_id"]
        name = user.get("first_name") or str(actor)
        state = "включено" if allow else "выключено"
        await db.add_log(chat_id, actor, target_id, "perm", f"{perm}={allow}", now_ts())
        await _notify(
            chat_id,
            f"Право «{PERM_LABELS[perm]}» для {mention(target_id)} {state} через веб-панель.\n"
            f"Изменил: {mention(actor, name)}",
        )
    return ok, msg
 
 
async def chat_perm(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    chat_id = int(data["chat_id"])
    target_id = int(data["user_id"])
    perm = data["perm"]
    allow = data.get("allow") == "1"
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    await _do_perm(user, chat_id, target_id, perm, allow)
    raise web.HTTPFound(f"/chats/{chat_id}")
 
 
async def api_perm(request) -> web.Response:
    # Тот же путь, но с JSON-ответом: используется для переключения чипов без перезагрузки.
    user = await _user(request)
    data = await request.post()
    try:
        chat_id = int(data["chat_id"])
        target_id = int(data["user_id"])
        perm = data["perm"]
    except (KeyError, ValueError):
        return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
    allow = data.get("allow") == "1"
    if chat_id not in await _allowed_ids(user["user_id"]):
        return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
    ok, msg = await _do_perm(user, chat_id, target_id, perm, allow)
    return web.json_response({"ok": ok, "allow": allow, "msg": msg})
 
 
async def users_page(request) -> web.Response:
    user = await _user(request)
    chats = await allowed_chats(user["user_id"])
    names = {c["chat_id"]: c["title"] for c in chats}
    rows = []
    for c in chats:
        for p in await db.list_punish(c["chat_id"], active_only=True):
            rows.append(p)
    warns = []
    for c in chats:
        warns.extend(await db.list_warns(c["chat_id"]))
    return render(
        request, "users.html", active="users", rows=rows, warns=warns, names=names, fmt_dt=fmt_dt, fmt_dur=fmt_dur
    )
 
 
async def user_page(request) -> web.Response:
    user = await _user(request)
    chat_id = int(request.match_info["chat_id"])
    target_id = int(request.match_info["user_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)}
    warns = await db.list_warns(chat_id, target_id)
    hist = await db.hist_punish(chat_id, target_id)
    return render(
        request,
        "user.html",
        active="users",
        chat=chat,
        target_id=target_id,
        warns=warns,
        hist=hist,
        fmt_dt=fmt_dt,
        fmt_dur=fmt_dur,
    )
 
 
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()
    chat_id = int(data["chat_id"])
    target_id = int(data["user_id"])
    kind = data.get("kind", "")
    reason = (data.get("reason") or "").strip()
    name = (data.get("name") or str(target_id)).strip()
    back = data.get("back") or f"/chats/{chat_id}"
 
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    if kind not in ACTION_PERM:
        raise web.HTTPFound(back)
    # Себя (бота) наказывать нельзя.
    if target_id == cfg.BOT_ID:
        raise web.HTTPFound(back)
    if not await pm.check_perm(chat_id, user["user_id"], ACTION_PERM[kind]):
        raise web.HTTPForbidden()
 
    if kind in ("mute", "ban"):
        try:
            dur = parse_dur(data.get("dur") or "-")
        except ValueError:
            dur = None
    else:
        dur = None
 
    await _apply_action(user["user_id"], chat_id, target_id, name, kind, dur, reason)
    raise web.HTTPFound(back)
 
 
async def captcha_page(request) -> web.Response:
    user = await _user(request)
    chats = await allowed_chats(user["user_id"])
    names = {c["chat_id"]: c["title"] for c in chats}
    ids = set(names)
    rows = [
        {"chat_id": k[0], "user_id": k[1], "left": max(0, v.get("deadline", 0) - now_ts())}
        for k, v in CAP_STATE.items()
        if k[0] in ids
    ]
    return render(request, "captcha.html", active="captcha", rows=rows, names=names)
 
 
async def log_page(request) -> web.Response:
    user = await _user(request)
    chats = await allowed_chats(user["user_id"])
    names = {c["chat_id"]: c["title"] for c in chats}
    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 = await 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})