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'
Variables Telegram pendientes: {escape(", ".join(runtime_state["missing_bot_env_vars"]))}
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.
{stats['users']}
{stats['admins']}
{stats['library_items']}
{stats['searches']}
{stats['downloads']}
{bot_status}
{mongo_status}
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
sdk: docker y app_port: 7860 en READMEEXPOSE 7860 en Dockerfile0.0.0.0:7860MONGODB_URI vacío