Add RP actions web panel with GIF upload support
- Add /chats/{chat_id}/rp page to manage roleplay actions
- Add api_rp_add endpoint to create actions with optional GIF upload
- Add api_rp_delete endpoint to remove actions
- Create rp.html template with form and action list
- Update rp.py handler to support local GIF files
- Add navigation link to RP Actions in chat panel
- GIFs stored locally in data/rp_gifs/ with timestamp+uuid naming
2 files added
5 files modified
| | |
| | | "reply_to_tg INTEGER DEFAULT 0, " |
| | | "reply_to_name TEXT DEFAULT '', " |
| | | "reply_to_text TEXT DEFAULT '')", |
| | | "CREATE TABLE IF NOT EXISTS rp_actions (" |
| | | "id INTEGER PRIMARY KEY AUTOINCREMENT, " |
| | | "chat_id INTEGER, " |
| | | "trigger TEXT COLLATE NOCASE, " |
| | | "response_text TEXT, " |
| | | "gif_file_id TEXT, " |
| | | "enabled INTEGER DEFAULT 1, " |
| | | "created_at INTEGER, " |
| | | "UNIQUE(chat_id, trigger))", |
| | | ) |
| | | |
| | | |
| | |
| | | (chat_id, after_id, limit), |
| | | ) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | # --- RP Actions --- |
| | | |
| | | async def add_rp_action(chat_id: int, trigger: str, response_text: str, gif_file_id: Optional[str], ts: int) -> Optional[int]: |
| | | async with db_conn() as db: |
| | | try: |
| | | await db.execute( |
| | | "INSERT INTO rp_actions (chat_id, trigger, response_text, gif_file_id, enabled, created_at) " |
| | | "VALUES (?, ?, ?, ?, 1, ?)", |
| | | (chat_id, trigger, response_text, gif_file_id, ts), |
| | | ) |
| | | await db.commit() |
| | | return (await db.execute("SELECT last_insert_rowid()")).fetchone()[0] |
| | | except Exception: |
| | | return None |
| | | |
| | | |
| | | async def list_rp_actions(chat_id: int) -> List[dict]: |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT * FROM rp_actions WHERE chat_id=? AND enabled=1 ORDER BY created_at", |
| | | (chat_id,), |
| | | ) as cur: |
| | | return [dict(r) for r in await cur.fetchall()] |
| | | |
| | | |
| | | async def get_rp_action(action_id: int) -> Optional[dict]: |
| | | async with db_conn() as db: |
| | | async with db.execute("SELECT * FROM rp_actions WHERE id=?", (action_id,)) as cur: |
| | | row = await cur.fetchone() |
| | | return dict(row) if row else None |
| | | |
| | | |
| | | async def delete_rp_action(action_id: int) -> bool: |
| | | async with db_conn() as db: |
| | | await db.execute("DELETE FROM rp_actions WHERE id=?", (action_id,)) |
| | | await db.commit() |
| | | return True |
| | | |
| | | |
| | | async def check_rp_trigger(chat_id: int, text: str) -> Optional[dict]: |
| | | text_upper = text.upper() |
| | | async with db_conn() as db: |
| | | async with db.execute( |
| | | "SELECT * FROM rp_actions WHERE chat_id=? AND enabled=1", |
| | | (chat_id,), |
| | | ) as cur: |
| | | rows = await cur.fetchall() |
| | | for row in rows: |
| | | if row["trigger"].upper() in text_upper: |
| | | return dict(row) |
| | | return None |
| | |
| | | import flood # noqa: F401 |
| | | import fun # noqa: F401 |
| | | import cmds # noqa: F401 |
| | | import rp # noqa: F401 |
| | | import track # noqa: F401 |
| | | from web.app import start_web |
| | | |
| New file |
| | |
| | | from aiogram import types |
| | | import pathlib |
| | | |
| | | import db |
| | | from cfg import dp |
| | | |
| | | |
| | | @dp.message() |
| | | async def rp_action_handler(message: types.Message) -> None: |
| | | """Проверяет сообщение на РП триггеры и отправляет действие если найдено.""" |
| | | if not message.text or message.from_user is None: |
| | | return |
| | | |
| | | # Пропускаем команды |
| | | if message.text.startswith("/"): |
| | | return |
| | | |
| | | action = await db.check_rp_trigger(message.chat.id, message.text) |
| | | if not action: |
| | | return |
| | | |
| | | # Формируем ответ |
| | | response = action["response_text"].format(user=message.from_user.first_name) |
| | | |
| | | # Отправляем гифку + текст |
| | | if action["gif_file_id"]: |
| | | try: |
| | | gif_path = action["gif_file_id"] |
| | | # Проверяем, является ли это локальным файлом или Telegram file_id |
| | | if isinstance(gif_path, str) and (gif_path.startswith("data/") or pathlib.Path(gif_path).exists()): |
| | | # Локальный файл |
| | | with open(gif_path, "rb") as f: |
| | | await message.reply_animation( |
| | | animation=f, |
| | | caption=response, |
| | | show_caption_above_media=True, |
| | | ) |
| | | else: |
| | | # Telegram file_id |
| | | await message.reply_animation( |
| | | animation=gif_path, |
| | | caption=response, |
| | | show_caption_above_media=True, |
| | | ) |
| | | except Exception: |
| | | # Если гифка недоступна, отправляем просто текст |
| | | await message.reply(response) |
| | | else: |
| | | await message.reply(response) |
| | |
| | | app.router.add_get("/chats/{chat_id}", views.chat_page) |
| | | app.router.add_get("/chats/{chat_id}/admin/{user_id}", views.admin_page) |
| | | app.router.add_get("/chats/{chat_id}/messages", views.messages_page) |
| | | app.router.add_get("/chats/{chat_id}/rp", views.rp_page) |
| | | app.router.add_post("/chats/cfg", views.chat_cfg) |
| | | app.router.add_post("/chats/perm", views.chat_perm) |
| | | app.router.add_post("/chats/alarm", views.alarm_toggle) |
| | |
| | | app.router.add_get("/api/messages", views.api_messages) |
| | | app.router.add_post("/api/say", views.api_say) |
| | | app.router.add_post("/api/perm", views.api_perm) |
| | | app.router.add_post("/api/rp/add", views.api_rp_add) |
| | | app.router.add_post("/api/rp/delete", views.api_rp_delete) |
| | | app.router.add_get("/users", views.users_page) |
| | | app.router.add_get("/users/{chat_id}/{user_id}", views.user_page) |
| | | app.router.add_post("/action", views.action) |
| | |
| | | class="h-12 w-12 rounded-full bg-gray-200 object-cover dark:bg-gray-700" |
| | | onerror="this.style.visibility='hidden'"> |
| | | <div class="min-w-0 flex-1 text-sm text-gray-500">id {{ chat.chat_id }} · {{ chat.type }}</div> |
| | | <div class="flex gap-2"> |
| | | <a href="/chats/{{ chat.chat_id }}/messages" target="_blank" rel="noopener" |
| | | class="shrink-0 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-brand-600 hover:bg-gray-100 dark:border-gray-700 dark:text-brand-400 dark:hover:bg-gray-800"> |
| | | Последние сообщения ↗ |
| | | Сообщения ↗ |
| | | </a> |
| | | <a href="/chats/{{ chat.chat_id }}/rp" |
| | | class="shrink-0 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-brand-600 hover:bg-gray-100 dark:border-gray-700 dark:text-brand-400 dark:hover:bg-gray-800"> |
| | | RP Actions |
| | | </a> |
| | | </div> |
| | | </div> |
| | | |
| | | <section class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"> |
| New file |
| | |
| | | {% extends "base.html" %} |
| | | {% block title %}RP Actions - {{ chat.title or chat.chat_id }} - Amadeus{% endblock %} |
| | | {% block header %}RP Actions · {{ chat.title or chat.chat_id }}{% endblock %} |
| | | {% block content %} |
| | | |
| | | <div class="space-y-6"> |
| | | <section class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900 md:p-5"> |
| | | <h2 class="mb-4 font-semibold">Добавить новое действие</h2> |
| | | <form method="post" action="/api/rp/add" enctype="multipart/form-data" class="space-y-4" id="rp-form"> |
| | | <input type="hidden" name="chat_id" value="{{ chat.chat_id }}"> |
| | | <label class="block text-sm">Триггер (ключевое слово, любой регистр) |
| | | <input name="trigger" type="text" required placeholder="например: привет" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700"> |
| | | </label> |
| | | <label class="block text-sm">Ответ (используйте {user} для имени) |
| | | <input name="response_text" type="text" required placeholder="например: Привет, {user}!" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700"> |
| | | </label> |
| | | <label class="block text-sm">GIF (опционально) |
| | | <input name="gif" type="file" accept=".gif,image/gif" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700"> |
| | | </label> |
| | | <div> |
| | | <button type="submit" class="rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700">Добавить действие</button> |
| | | </div> |
| | | </form> |
| | | <div id="rp-message" class="mt-3 hidden rounded-lg px-3 py-2 text-sm"></div> |
| | | </section> |
| | | |
| | | {% if actions %} |
| | | <section class="rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900"> |
| | | <div class="border-b border-gray-200 px-5 py-3 font-semibold dark:border-gray-800">Существующие действия ({{ actions|length }})</div> |
| | | <div class="divide-y divide-gray-100 dark:divide-gray-800"> |
| | | {% for a in actions %} |
| | | <div class="flex items-center justify-between gap-4 px-5 py-3 text-sm"> |
| | | <div class="min-w-0 flex-1"> |
| | | <div class="font-medium text-gray-900 dark:text-white">{{ a.trigger }}</div> |
| | | <div class="mt-1 text-gray-600 dark:text-gray-300">{{ a.response_text }}</div> |
| | | {% if a.gif_file_id %} |
| | | <div class="mt-1 text-xs text-gray-500">GIF прикреплена</div> |
| | | {% endif %} |
| | | </div> |
| | | <button type="button" class="shrink-0 rounded-lg border border-red-300 px-3 py-1 text-xs text-red-600 hover:bg-red-50 dark:border-red-800 dark:text-red-300 dark:hover:bg-red-950/40 rp-delete" data-action-id="{{ a.id }}" data-chat-id="{{ chat.chat_id }}">Удалить</button> |
| | | </div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | {% else %} |
| | | <section class="rounded-xl border border-gray-200 bg-white p-6 text-center shadow-sm dark:border-gray-800 dark:bg-gray-900"> |
| | | <div class="text-gray-500">Нет созданных действий. Добавьте первое!</div> |
| | | </section> |
| | | {% endif %} |
| | | </div> |
| | | |
| | | <script> |
| | | document.getElementById('rp-form').addEventListener('submit', async (e) => { |
| | | e.preventDefault(); |
| | | const form = e.target; |
| | | const msgEl = document.getElementById('rp-message'); |
| | | |
| | | try { |
| | | const formData = new FormData(form); |
| | | const response = await fetch('/api/rp/add', { |
| | | method: 'POST', |
| | | body: formData |
| | | }); |
| | | const result = await response.json(); |
| | | |
| | | msgEl.classList.remove('hidden'); |
| | | if (result.ok) { |
| | | msgEl.className = 'mt-3 rounded-lg bg-green-50 px-3 py-2 text-sm text-green-700 dark:bg-green-950/40 dark:text-green-300'; |
| | | msgEl.textContent = 'Действие добавлено!'; |
| | | form.reset(); |
| | | setTimeout(() => location.reload(), 1000); |
| | | } else { |
| | | msgEl.className = 'mt-3 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-300'; |
| | | msgEl.textContent = result.msg || 'Ошибка при добавлении действия'; |
| | | } |
| | | } catch (err) { |
| | | msgEl.classList.remove('hidden'); |
| | | msgEl.className = 'mt-3 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-300'; |
| | | msgEl.textContent = 'Ошибка сети: ' + err.message; |
| | | } |
| | | }); |
| | | |
| | | document.querySelectorAll('.rp-delete').forEach(btn => { |
| | | btn.addEventListener('click', async (e) => { |
| | | if (!confirm('Удалить это действие?')) return; |
| | | |
| | | const actionId = btn.dataset.actionId; |
| | | const chatId = btn.dataset.chatId; |
| | | |
| | | try { |
| | | const response = await fetch('/api/rp/delete', { |
| | | method: 'POST', |
| | | headers: {'Content-Type': 'application/x-www-form-urlencoded'}, |
| | | body: new URLSearchParams({action_id: actionId, chat_id: chatId}) |
| | | }); |
| | | const result = await response.json(); |
| | | |
| | | if (result.ok) { |
| | | btn.closest('.flex').remove(); |
| | | } else { |
| | | alert(result.msg || 'Ошибка при удалении'); |
| | | } |
| | | } catch (err) { |
| | | alert('Ошибка сети: ' + err.message); |
| | | } |
| | | }); |
| | | }); |
| | | </script> |
| | | |
| | | {% endblock %} |
| | |
| | | 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: |
| | | user = await _user(request) |
| | | 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): |
| | | 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 + trigger) |
| | | 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}) |
| | | |
| | | |
| | | 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}) |