"""Telegram forum setup with persistent topic and panel identifiers. Bot API cannot create a group or enable forum mode. This module verifies both the chat and the bot permission before creating anything. Re-running setup reuses topic IDs and edits existing panels instead of posting duplicates. """ from __future__ import annotations import asyncio from contextlib import closing import html import logging import sqlite3 import time from aiogram import types log = logging.getLogger("forum-panels") TOPICS = ( ("ann", "📢 Объявления"), ("econ", "💰 Экономика"), ("quests", "📜 Квесты и баунти"), ("top", "🏆 Топ и дуэли"), ("moder", "🛠 Модерация"), ) _SETUP_LOCKS = {} def _setup_lock(): loop = asyncio.get_running_loop() lock = _SETUP_LOCKS.get(loop) if lock is None: lock = asyncio.Lock() _SETUP_LOCKS[loop] = lock return lock def ensure_schema(bot_db): with closing(sqlite3.connect(bot_db, timeout=20)) as con: con.execute("""CREATE TABLE IF NOT EXISTS forum_topics( chat_id INTEGER NOT NULL, kind TEXT NOT NULL, thread_id INTEGER NOT NULL, title TEXT NOT NULL, panel_message_id INTEGER, created INTEGER NOT NULL, PRIMARY KEY(chat_id,kind), UNIQUE(chat_id,thread_id))""") con.commit() def topic_rows(bot_db, chat_id): ensure_schema(bot_db) with closing(sqlite3.connect(bot_db, timeout=20)) as con: con.row_factory = sqlite3.Row return con.execute("SELECT * FROM forum_topics WHERE chat_id=?", (int(chat_id),)).fetchall() def panel_keyboard(buttons): if not buttons: return None rows = [[types.InlineKeyboardButton(text=text, callback_data=data) for text, data in buttons[i:i + 3]] for i in range(0, len(buttons), 3)] return types.InlineKeyboardMarkup(inline_keyboard=rows) async def status(bot_db, bot, chat_id): try: chat = await bot.get_chat(chat_id) except Exception: log.warning("forum status get_chat failed chat=%s", chat_id, exc_info=True) return "💬 Форум ИИШКО\n\nНе удалось получить чат через Telegram. Проверь доступ бота и попробуй снова." if getattr(chat, "type", "") == "private": return ("💬 Форум ИИШКО\n\nФорум живёт в групповом чате сообщества: объявления, " "экономика, квесты и баунти, топ и дуэли. Открой чат ИИШКО и выбери тему; " "настройка тем доступна администратору группы.") is_forum = bool(getattr(chat, "is_forum", False)) title = html.escape(str(getattr(chat, "title", None) or chat_id)) rows = [] if getattr(chat, "type", "") in ("group", "supergroup"): try: rows = await asyncio.to_thread(topic_rows, bot_db, chat_id) except sqlite3.Error: log.exception("forum status db failed chat=%s", chat_id) return ("💬 Форум ИИШКО\n\nСостояние тем сейчас недоступно. " "Повтори позже; настройка не менялась.") lines = ["💬 Форум ИИШКО", f"Чат: {title}", "Темы Telegram: %s" % ("включены" if is_forum else "выключены")] if not is_forum: lines += ["", "Bot API не может создать группу или включить темы.", "Администратор группы: Управление группой → Темы. Затем в группе: /forum setup"] if rows: lines.append("Сохранённых записей о темах: %d (live-проверка не выполнялась)." % len(rows)) return "\n".join(lines) by_kind = {row["kind"]: row for row in rows} lines.append("Сохранено в БД: тем %d/%d · панелей %d " "(live-проверка не выполнялась)" % ( len(rows), len(TOPICS), sum(bool(row["panel_message_id"]) for row in rows))) for kind, topic_title in TOPICS: row = by_kind.get(kind) lines.append(("✅ " if row else "▫️ ") + html.escape(topic_title) + (f" · ID {row['thread_id']}" if row else "")) if len(rows) < len(TOPICS): lines += ["", "Администратор: /forum setup"] return "\n".join(lines) def _admin_can_manage_topics(member): value = getattr(member, "status", None) status = getattr(value, "value", value) return status == "administrator" and bool(getattr(member, "can_manage_topics", False)) def _not_modified(error): return "message is not modified" in str(error).lower() def _missing_message(error): text = str(error).lower() return "message to edit not found" in text or "message_id_invalid" in text or "message not found" in text def _missing_thread(error): text = str(error).lower() return ("message thread not found" in text or "topic_deleted" in text or "topic_id_invalid" in text or "thread not found" in text) def _store_topic(bot_db, chat_id, kind, thread_id, title): with closing(sqlite3.connect(bot_db, timeout=20)) as con: con.execute("DELETE FROM forum_topics WHERE chat_id=? AND kind=?", (int(chat_id), kind)) con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created) " "VALUES(?,?,?,?,NULL,?)", (int(chat_id), kind, int(thread_id), title, int(time.time()))) con.commit() def _drop_topic(bot_db, chat_id, kind): with closing(sqlite3.connect(bot_db, timeout=20)) as con: con.execute("DELETE FROM forum_topics WHERE chat_id=? AND kind=?", (int(chat_id), kind)) con.commit() async def _create_topic(bot_db, bot, chat_id, kind, title, created): topic = await bot.create_forum_topic(chat_id=chat_id, name=title) thread_id = int(topic.message_thread_id) _store_topic(bot_db, chat_id, kind, thread_id, title) created.append("%s · ID %d" % (title, thread_id)) return {"kind": kind, "thread_id": thread_id, "panel_message_id": None} async def _send_panel(bot_db, bot, chat_id, kind, title, row, text, keyboard, created): """Send into a topic; recreate the topic once when Telegram says it is gone.""" try: return await bot.send_message(chat_id, text, reply_markup=keyboard, message_thread_id=int(row["thread_id"]), parse_mode="HTML") except Exception as error: if not _missing_thread(error): raise log.warning("forum topic missing chat=%s kind=%s; recreating", chat_id, kind) _drop_topic(bot_db, chat_id, kind) fresh = await _create_topic(bot_db, bot, chat_id, kind, title, created) return await bot.send_message(chat_id, text, reply_markup=keyboard, message_thread_id=int(fresh["thread_id"]), parse_mode="HTML") CASINO_DISABLED_TEXT = ("🎰 Казино\n\n" "Ставки и платные игры отключены навсегда. " "Бесплатные игры: /quiz, /dice, /pair, /roast.") def _casino_rows(bot_db): ensure_schema(bot_db) with closing(sqlite3.connect(bot_db, timeout=20)) as con: con.row_factory = sqlite3.Row return con.execute("SELECT * FROM forum_topics WHERE kind='casino'").fetchall() async def retire_casino_panels(bot_db, bot, chat_id=None): rows = [r for r in _casino_rows(bot_db) if chat_id is None or int(r["chat_id"]) == int(chat_id)] retired, kept, failed = 0, 0, 0 for row in rows: cid = int(row["chat_id"]) pid = int(row["panel_message_id"] or 0) if pid: try: await bot.edit_message_text(text=CASINO_DISABLED_TEXT, chat_id=cid, message_id=pid, reply_markup=None, parse_mode="HTML") except Exception as error: if not (_not_modified(error) or _missing_message(error) or _missing_thread(error)): failed += 1 log.warning("casino panel retire failed chat=%s msg=%s", cid, pid, exc_info=True) continue _drop_topic(bot_db, cid, "casino") retired += 1 if rows: log.info("casino panels retired=%s failed=%s kept=%s", retired, failed, kept) return {"found": len(rows), "retired": retired, "failed": failed} async def _setup(bot_db, bot, chat_id, panels): chat = await bot.get_chat(chat_id) if getattr(chat, "type", "") != "supergroup" or not bool(getattr(chat, "is_forum", False)): return {"ok": False, "created": 0, "panels": 0, "errors": ["not_forum"], "text": "❌ Здесь нельзя настроить форум: нужен супергрупповой чат с включёнными «Темами». " "Включи их в настройках группы и повтори /forum setup."} me = await bot.get_me() member = await bot.get_chat_member(chat_id, me.id) if not _admin_can_manage_topics(member): return {"ok": False, "created": 0, "panels": 0, "errors": ["can_manage_topics"], "text": "❌ Нет права управления темами. Сделай бота администратором с правом " "Manage Topics / Управление темами и повтори /forum setup."} ensure_schema(bot_db) try: await retire_casino_panels(bot_db, bot, chat_id) # [NO-PAID-CASINO] стухшая панель казино except Exception: log.warning("casino panel retire skipped chat=%s", chat_id, exc_info=True) created, ready, errors = [], 0, [] rows = {row["kind"]: row for row in topic_rows(bot_db, chat_id)} for kind, title in TOPICS: try: row = rows.get(kind) if row is None: row = await _create_topic(bot_db, bot, chat_id, kind, title, created) rows[kind] = row text, buttons = panels[kind] keyboard = panel_keyboard(buttons) panel_id = row["panel_message_id"] if panel_id: try: await bot.edit_message_text(text=text, chat_id=chat_id, message_id=panel_id, reply_markup=keyboard, parse_mode="HTML") except Exception as error: if _not_modified(error): pass elif _missing_message(error): sent = await _send_panel(bot_db, bot, chat_id, kind, title, row, text, keyboard, created) panel_id = sent.message_id else: raise else: sent = await _send_panel(bot_db, bot, chat_id, kind, title, row, text, keyboard, created) panel_id = sent.message_id if int(panel_id) != int(row["panel_message_id"] or 0): with closing(sqlite3.connect(bot_db, timeout=20)) as con: con.execute("UPDATE forum_topics SET panel_message_id=? WHERE chat_id=? AND kind=?", (int(panel_id), int(chat_id), kind)) con.commit() ready += 1 except Exception as error: log.warning("forum setup item failed chat=%s kind=%s", chat_id, kind, exc_info=True) errors.append("%s: %s" % (title, html.escape(str(error)[:100]))) lines = [] if created: lines.append("✅ Созданы темы:\n" + "\n".join(created)) else: lines.append("✅ Новых тем не потребовалось: использую сохранённые ID.") lines.append("Панелей готово: %d/%d." % (ready, len(TOPICS))) if errors: lines.append("⚠️ Ошибки:\n" + "\n".join(errors)) lines.append("Повторный /forum setup обновит панели без создания дублей.") return {"ok": not errors and ready == len(TOPICS), "created": len(created), "panels": ready, "errors": errors, "text": "\n\n".join(lines)} async def setup(bot_db, bot, chat_id, panels): async with _setup_lock(): try: return await _setup(bot_db, bot, chat_id, panels) except Exception: log.exception("forum setup failed chat=%s", chat_id) return {"ok": False, "created": 0, "panels": 0, "errors": ["setup_failed"], "text": "❌ Настройка не завершена. Проверь права бота и логи; повтор безопасен."}