from __future__ import annotations import asyncio import logging import tempfile from html import escape from pathlib import Path from fastapi import FastAPI, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from typing import TYPE_CHECKING from bot.config import get_settings if TYPE_CHECKING: from bot.bot_service import BotService from bot.database import JsonDatabase logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s") logger = logging.getLogger(__name__) settings = get_settings() database = JsonDatabase( settings.database_path, owner_ids=settings.owner_ids, storage_chat_ids=settings.storage_chat_ids, mongodb_uri=settings.mongodb_uri, mongodb_db_name=settings.mongodb_db_name, mongodb_collection=settings.mongodb_collection, mongodb_server_selection_timeout_ms=settings.mongodb_server_selection_timeout_ms, ) app = FastAPI(title=settings.bot_name) bot: "BotService | None" = None runtime_state = { "bot_started": False, "bot_configured": settings.bot_enabled, "bot_start_error": None, "missing_bot_env_vars": settings.missing_bot_env_vars, } async def _start_bot_if_possible() -> None: global bot runtime_state["bot_configured"] = settings.bot_enabled runtime_state["missing_bot_env_vars"] = settings.missing_bot_env_vars if not settings.bot_enabled: runtime_state["bot_start_error"] = ( "Faltan variables para Telegram: " + ", ".join(settings.missing_bot_env_vars) ) logger.warning(runtime_state["bot_start_error"]) return try: from bot.bot_service import BotService bot = BotService(settings, database) await asyncio.wait_for(bot.start(), timeout=45) runtime_state["bot_started"] = True runtime_state["bot_start_error"] = None except Exception as exc: runtime_state["bot_started"] = False runtime_state["bot_start_error"] = str(exc) logger.exception("No pude iniciar el bot de Telegram") bot = None @app.on_event("startup") async def startup_event() -> None: await database.mutate( lambda data: data.setdefault("config", {}).update( { "ai_enabled": settings.ai_enabled, "db_backend": "json+mongo" if settings.mongodb_enabled else "json", "not_found_chat_id": settings.not_found_chat_id, } ) ) await _start_bot_if_possible() @app.on_event("shutdown") async def shutdown_event() -> None: global bot if not bot: return try: await bot.stop() finally: runtime_state["bot_started"] = False @app.get("/", response_class=HTMLResponse) async def index() -> HTMLResponse: stats = await database.get_stats() stats["ai_enabled"] = settings.ai_enabled storage_ids = await database.get_storage_chat_ids() mongo_status = "🟢 conectado" if stats.get("mongo_ready") else ("🟡 configurado" if stats.get("mongo_enabled") else "⚪ JSON local") bot_status = "🟢 conectado" if runtime_state["bot_started"] else ("🟡 pendiente" if runtime_state["bot_configured"] else "⚪ web solo") bot_error_html = "" if runtime_state.get("bot_start_error"): bot_error_html = f'
Diagnóstico bot: {escape(str(runtime_state["bot_start_error"]))}
' missing_html = "" if runtime_state.get("missing_bot_env_vars"): missing_html = f'

Variables Telegram pendientes: {escape(", ".join(runtime_state["missing_bot_env_vars"]))}

' html = f""" {escape(settings.bot_name)}

🎬 {escape(settings.bot_name)}

FastAPI + Pyrogram + JSON con espejo opcional en MongoDB. Ahora la web puede iniciar sola aunque falten variables de Telegram o MongoDB, para que el Space quede vivo y te muestre el diagnóstico.

👥 Usuarios

{stats['users']}

🛡️ Admins

{stats['admins']}

🎞️ Ítems

{stats['library_items']}

🔎 Búsquedas

{stats['searches']}

📥 Descargas

{stats['downloads']}

🤖 Telegram

{bot_status}

🍃 MongoDB

{mongo_status}

{bot_error_html}

Estado del Space

Bot iniciado: {'Sí' if runtime_state['bot_started'] else 'No'}

Bot configurado: {'Sí' if runtime_state['bot_configured'] else 'No'}

{missing_html}

Backend: {escape(str(stats.get('db_backend', 'json')))}

Chats de almacenamiento: {escape(', '.join(str(x) for x in storage_ids) or 'ninguno')}

Chat búsquedas vacías: {escape(str(stats.get('not_found_chat_id') or 'ninguno'))}

Persistencia recomendada: usar /data si tu Space tiene almacenamiento persistente.

IA de limpieza: {'activa' if settings.ai_enabled else 'desactivada'}{f" · modelo {escape(settings.openrouter_model)}" if settings.ai_enabled else ""}

Healthcheck JSON: /health

Exportar: /admin/export

Importar JSON

Checklist Hugging Face

  • sdk: docker y app_port: 7860 en README
  • EXPOSE 7860 en Dockerfile
  • uvicorn escuchando en 0.0.0.0:7860
  • Secrets correctos en Settings → Variables and secrets
  • Si no usas Mongo, deja MONGODB_URI vacío
""" return HTMLResponse(html) @app.get("/health") async def health() -> JSONResponse: stats = await database.get_stats() return JSONResponse( { "ok": True, "web_ok": True, "bot_started": runtime_state["bot_started"], "bot_configured": runtime_state["bot_configured"], "bot_start_error": runtime_state["bot_start_error"], "missing_bot_env_vars": runtime_state["missing_bot_env_vars"], "users": stats["users"], "library_items": stats["library_items"], "maintenance": stats["maintenance"], "db_backend": stats.get("db_backend", "json"), "mongo_ready": stats.get("mongo_ready", False), } ) @app.get("/admin/export") async def admin_export(token: str) -> FileResponse: if token != settings.web_panel_token: raise HTTPException(status_code=403, detail="Token inválido") path = await database.export_copy(settings.export_dir) return FileResponse(path, media_type="application/json", filename=path.name) @app.post("/admin/import") async def admin_import(token: str = Form(...), db_file: UploadFile = File(...)) -> JSONResponse: if token != settings.web_panel_token: raise HTTPException(status_code=403, detail="Token inválido") suffix = Path(db_file.filename or "database.json").suffix or ".json" with tempfile.NamedTemporaryFile(delete=False, suffix=suffix, dir=settings.export_dir) as handle: temp_path = Path(handle.name) handle.write(await db_file.read()) try: actor_id = settings.owner_ids[0] if settings.owner_ids else 0 await database.import_from_path(temp_path, actor_id=actor_id) finally: temp_path.unlink(missing_ok=True) return JSONResponse({"ok": True}) @app.get("/admin/raw") async def admin_raw(token: str) -> JSONResponse: if token != settings.web_panel_token: raise HTTPException(status_code=403, detail="Token inválido") return JSONResponse(await database.read())