KudoBot / app.py
saske560's picture
Upload 5 files
2c20cdc verified
Raw History Blame Contribute Delete
10.8 kB
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'<div class="notice warn"><b>Diagnóstico bot:</b> {escape(str(runtime_state["bot_start_error"]))}</div>'
missing_html = ""
if runtime_state.get("missing_bot_env_vars"):
missing_html = f'<p class="muted">Variables Telegram pendientes: <code>{escape(", ".join(runtime_state["missing_bot_env_vars"]))}</code></p>'
html = f"""
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{escape(settings.bot_name)}</title>
<style>
:root {{ color-scheme: dark; }}
* {{ box-sizing: border-box; }}
body {{ font-family: Inter, Arial, sans-serif; background: #070b16; color: #edf2ff; margin: 0; }}
.wrap {{ max-width: 1120px; margin: 0 auto; padding: 28px 16px 48px; }}
.hero {{ background: linear-gradient(135deg,#2563eb,#7c3aed 60%,#ec4899); border-radius: 28px; padding: 26px; box-shadow: 0 18px 45px rgba(0,0,0,.28); }}
.grid {{ display:grid; grid-template-columns: repeat(auto-fit,minmax(180px,1fr)); gap:16px; margin-top:20px; }}
.card {{ background:#0f172a; border:1px solid rgba(255,255,255,.09); border-radius:22px; padding:18px; box-shadow: 0 8px 25px rgba(0,0,0,.18); }}
.muted {{ color:#c7d2fe; opacity:.92; }}
.notice {{ margin-top: 16px; padding: 14px 16px; border-radius: 16px; }}
.warn {{ background:#3b1d1d; border:1px solid rgba(248,113,113,.35); color:#fecaca; }}
.ok {{ background:#0f2e1f; border:1px solid rgba(74,222,128,.28); color:#dcfce7; }}
code {{ background:#111827; padding:2px 8px; border-radius:8px; }}
a {{ color:#93c5fd; }}
input, button {{ width:100%; padding:12px 14px; border-radius:14px; border:1px solid rgba(255,255,255,.12); background:#111827; color:#fff; }}
button {{ cursor:pointer; background: linear-gradient(135deg,#2563eb,#7c3aed); border:none; font-weight:600; }}
form {{ display:grid; gap:10px; }}
ul {{ margin: 0; padding-left: 18px; }}
</style>
</head>
<body>
<div class="wrap">
<div class="hero">
<h1 style="margin:0 0 10px;">🎬 {escape(settings.bot_name)}</h1>
<p class="muted" style="margin:0;">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.</p>
</div>
<div class="grid">
<div class="card"><h3>👥 Usuarios</h3><p>{stats['users']}</p></div>
<div class="card"><h3>🛡️ Admins</h3><p>{stats['admins']}</p></div>
<div class="card"><h3>🎞️ Ítems</h3><p>{stats['library_items']}</p></div>
<div class="card"><h3>🔎 Búsquedas</h3><p>{stats['searches']}</p></div>
<div class="card"><h3>📥 Descargas</h3><p>{stats['downloads']}</p></div>
<div class="card"><h3>🤖 Telegram</h3><p>{bot_status}</p></div>
<div class="card"><h3>🍃 MongoDB</h3><p>{mongo_status}</p></div>
</div>
{bot_error_html}
<div class="grid" style="margin-top:18px;">
<div class="card">
<h3>Estado del Space</h3>
<p class="muted">Bot iniciado: <b>{'Sí' if runtime_state['bot_started'] else 'No'}</b></p>
<p class="muted">Bot configurado: <b>{'Sí' if runtime_state['bot_configured'] else 'No'}</b></p>
{missing_html}
<p class="muted">Backend: <code>{escape(str(stats.get('db_backend', 'json')))}</code></p>
<p class="muted">Chats de almacenamiento: <code>{escape(', '.join(str(x) for x in storage_ids) or 'ninguno')}</code></p>
<p class="muted">Chat búsquedas vacías: <code>{escape(str(stats.get('not_found_chat_id') or 'ninguno'))}</code></p>
<p class="muted">Persistencia recomendada: usar <code>/data</code> si tu Space tiene almacenamiento persistente.</p>
<p class="muted">IA de limpieza: <b>{'activa' if settings.ai_enabled else 'desactivada'}</b>{f" · modelo <code>{escape(settings.openrouter_model)}</code>" if settings.ai_enabled else ""}</p>
<p class="muted">Healthcheck JSON: <a href="/health">/health</a></p>
<p class="muted">Exportar: <a href="/admin/export?token={escape(settings.web_panel_token)}">/admin/export</a></p>
</div>
<div class="card">
<h3>Importar JSON</h3>
<form action="/admin/import" method="post" enctype="multipart/form-data">
<input type="password" name="token" placeholder="WEB_PANEL_TOKEN" required />
<input type="file" name="db_file" accept="application/json,.json" required />
<button type="submit">Importar base</button>
</form>
</div>
<div class="card">
<h3>Checklist Hugging Face</h3>
<ul class="muted">
<li><code>sdk: docker</code> y <code>app_port: 7860</code> en README</li>
<li><code>EXPOSE 7860</code> en Dockerfile</li>
<li>uvicorn escuchando en <code>0.0.0.0:7860</code></li>
<li>Secrets correctos en Settings → Variables and secrets</li>
<li>Si no usas Mongo, deja <code>MONGODB_URI</code> vacío</li>
</ul>
</div>
</div>
</div>
</body>
</html>
"""
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())