Upload 5 files
Browse files- README.md +72 -17
- app.py +122 -26
- requirements.txt +3 -0
README.md
CHANGED
|
@@ -10,7 +10,7 @@ pinned: false
|
|
| 10 |
|
| 11 |
# MediaVault Bot
|
| 12 |
|
| 13 |
-
Bot de Telegram hecho con **Pyrogram** + **FastAPI** + **
|
| 14 |
|
| 15 |
## Importante
|
| 16 |
|
|
@@ -18,19 +18,24 @@ Este proyecto está pensado para **tu propia biblioteca de archivos** o para mat
|
|
| 18 |
|
| 19 |
## Novedades de esta versión
|
| 20 |
|
| 21 |
-
-
|
| 22 |
-
-
|
| 23 |
-
-
|
| 24 |
-
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
## Qué hace
|
| 27 |
|
| 28 |
- Indexa automáticamente videos y documentos que se publiquen en tu **canal o grupo de almacenamiento**.
|
| 29 |
-
- Detecta de forma automática si parece **película** o **
|
| 30 |
- Intenta sacar **temporada**, **capítulo**, **parte**, **año**, **calidad** e **idioma** a partir del nombre y la descripción.
|
| 31 |
- Los usuarios pueden buscar escribiendo **solo el nombre**, sin comandos.
|
| 32 |
-
- Entrega
|
| 33 |
- Tiene **admins**, **owner protegido**, **planes**, **favoritos**, **descargas recientes**, **import/export JSON**, **panel web** y **reindexado**.
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
## OpenRouter
|
| 36 |
|
|
@@ -53,17 +58,16 @@ Qué hace la IA aquí:
|
|
| 53 |
|
| 54 |
Si no configuras OpenRouter, el bot sigue funcionando con el parser local.
|
| 55 |
|
| 56 |
-
##
|
| 57 |
|
| 58 |
-
El
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
- `Final de temporada`
|
| 67 |
|
| 68 |
## Variables de entorno
|
| 69 |
|
|
@@ -80,12 +84,17 @@ RESULT_PAGE_SIZE=8
|
|
| 80 |
AUTO_REINDEX_ON_START=false
|
| 81 |
REINDEX_LIMIT_ON_START=150
|
| 82 |
LOG_CHAT_ID=
|
|
|
|
| 83 |
OPENROUTER_API_KEY=
|
| 84 |
OPENROUTER_MODEL=
|
| 85 |
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
| 86 |
OPENROUTER_HTTP_REFERER=
|
| 87 |
OPENROUTER_TITLE=MediaVault Bot
|
| 88 |
OPENROUTER_TIMEOUT_SECONDS=25
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
```
|
| 90 |
|
| 91 |
## Telegram
|
|
@@ -95,7 +104,7 @@ OPENROUTER_TIMEOUT_SECONDS=25
|
|
| 95 |
3. Añade el bot al grupo/canal de almacenamiento.
|
| 96 |
4. En grupos, desactiva **Privacy Mode** si quieres que vea mensajes normales del grupo.
|
| 97 |
5. En canales, dale permisos para leer publicaciones.
|
| 98 |
-
6. Para
|
| 99 |
|
| 100 |
## Ejecutar local
|
| 101 |
|
|
@@ -121,6 +130,10 @@ uvicorn app:app --host 0.0.0.0 --port 7860
|
|
| 121 |
- `/start`
|
| 122 |
- `/help`
|
| 123 |
- `/miplan`
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
- `/favoritos`
|
| 125 |
- `/misdescargas`
|
| 126 |
|
|
@@ -147,6 +160,11 @@ uvicorn app:app --host 0.0.0.0 --port 7860
|
|
| 147 |
- `/deladmin <user_id>`
|
| 148 |
- `/addstorage <chat_id>`
|
| 149 |
- `/delstorage <chat_id>`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
### En el chat de almacenamiento
|
| 152 |
|
|
@@ -157,4 +175,41 @@ uvicorn app:app --host 0.0.0.0 --port 7860
|
|
| 157 |
|
| 158 |
- OpenRouter no es gratis e ilimitado por definición; depende del modelo y del saldo/cuotas que tengas.
|
| 159 |
- La IA puede equivocarse, así que el bot mantiene fallback heurístico.
|
|
|
|
| 160 |
- Si borras un mensaje del chat fuente, el índice puede quedar desactualizado hasta que vuelvas a reindexar o limpies la base.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# MediaVault Bot
|
| 12 |
|
| 13 |
+
Bot de Telegram hecho con **Pyrogram** + **FastAPI** + **JSON** con espejo opcional en **MongoDB**.
|
| 14 |
|
| 15 |
## Importante
|
| 16 |
|
|
|
|
| 18 |
|
| 19 |
## Novedades de esta versión
|
| 20 |
|
| 21 |
+
- mensajes y botones con estilo más moderno
|
| 22 |
+
- resultados agrupados por título
|
| 23 |
+
- en series: **temporadas → episodios**, con botón para **temporada completa** y **serie completa**
|
| 24 |
+
- en películas con partes: botón para **película completa**
|
| 25 |
+
- integración opcional con **OpenRouter** para limpiar metadatos y mejorar títulos/captions
|
| 26 |
+
- persistencia en **JSON** y espejo opcional en **MongoDB** mediante snapshot
|
| 27 |
|
| 28 |
## Qué hace
|
| 29 |
|
| 30 |
- Indexa automáticamente videos y documentos que se publiquen en tu **canal o grupo de almacenamiento**.
|
| 31 |
+
- Detecta de forma automática si parece **película**, **serie** o **anime**.
|
| 32 |
- Intenta sacar **temporada**, **capítulo**, **parte**, **año**, **calidad** e **idioma** a partir del nombre y la descripción.
|
| 33 |
- Los usuarios pueden buscar escribiendo **solo el nombre**, sin comandos.
|
| 34 |
+
- Entrega los archivos desde el bot usando el `file_id` guardado.
|
| 35 |
- Tiene **admins**, **owner protegido**, **planes**, **favoritos**, **descargas recientes**, **import/export JSON**, **panel web** y **reindexado**.
|
| 36 |
+
- El plan **free** envía los medios con protección para bloquear reenvío y guardado cuando Telegram lo soporta, y deja favoritos para **VIP/Premium**.
|
| 37 |
+
- Sincroniza los **comandos del bot** según el rol: usuarios normales ven solo los suyos y cada admin ve el menú completo.
|
| 38 |
+
- Puede reportar búsquedas sin resultados a un **chat de búsquedas vacías**.
|
| 39 |
|
| 40 |
## OpenRouter
|
| 41 |
|
|
|
|
| 58 |
|
| 59 |
Si no configuras OpenRouter, el bot sigue funcionando con el parser local.
|
| 60 |
|
| 61 |
+
## MongoDB
|
| 62 |
|
| 63 |
+
MongoDB es opcional. El bot sigue usando `database.json`, pero cuando configuras Mongo guarda un **snapshot espejo** también en tu cluster y, al arrancar, se queda con la versión más reciente entre JSON y Mongo.
|
| 64 |
|
| 65 |
+
```env
|
| 66 |
+
MONGODB_URI=
|
| 67 |
+
MONGODB_DB_NAME=media_archive_bot
|
| 68 |
+
MONGODB_COLLECTION=snapshots
|
| 69 |
+
MONGODB_SERVER_SELECTION_TIMEOUT_MS=5000
|
| 70 |
+
```
|
|
|
|
| 71 |
|
| 72 |
## Variables de entorno
|
| 73 |
|
|
|
|
| 84 |
AUTO_REINDEX_ON_START=false
|
| 85 |
REINDEX_LIMIT_ON_START=150
|
| 86 |
LOG_CHAT_ID=
|
| 87 |
+
NOT_FOUND_CHAT_ID=
|
| 88 |
OPENROUTER_API_KEY=
|
| 89 |
OPENROUTER_MODEL=
|
| 90 |
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
| 91 |
OPENROUTER_HTTP_REFERER=
|
| 92 |
OPENROUTER_TITLE=MediaVault Bot
|
| 93 |
OPENROUTER_TIMEOUT_SECONDS=25
|
| 94 |
+
MONGODB_URI=
|
| 95 |
+
MONGODB_DB_NAME=media_archive_bot
|
| 96 |
+
MONGODB_COLLECTION=snapshots
|
| 97 |
+
MONGODB_SERVER_SELECTION_TIMEOUT_MS=5000
|
| 98 |
```
|
| 99 |
|
| 100 |
## Telegram
|
|
|
|
| 104 |
3. Añade el bot al grupo/canal de almacenamiento.
|
| 105 |
4. En grupos, desactiva **Privacy Mode** si quieres que vea mensajes normales del grupo.
|
| 106 |
5. En canales, dale permisos para leer publicaciones.
|
| 107 |
+
6. Para IA y Mongo, guarda secretos en **Variables and secrets** y no dentro del código.
|
| 108 |
|
| 109 |
## Ejecutar local
|
| 110 |
|
|
|
|
| 130 |
- `/start`
|
| 131 |
- `/help`
|
| 132 |
- `/miplan`
|
| 133 |
+
- `/catalogo`
|
| 134 |
+
- `/peliculas`
|
| 135 |
+
- `/series`
|
| 136 |
+
- `/anime`
|
| 137 |
- `/favoritos`
|
| 138 |
- `/misdescargas`
|
| 139 |
|
|
|
|
| 160 |
- `/deladmin <user_id>`
|
| 161 |
- `/addstorage <chat_id>`
|
| 162 |
- `/delstorage <chat_id>`
|
| 163 |
+
- `/setmisschat <chat_id|off>`
|
| 164 |
+
|
| 165 |
+
### Admin extra
|
| 166 |
+
|
| 167 |
+
- `/misschat`
|
| 168 |
|
| 169 |
### En el chat de almacenamiento
|
| 170 |
|
|
|
|
| 175 |
|
| 176 |
- OpenRouter no es gratis e ilimitado por definición; depende del modelo y del saldo/cuotas que tengas.
|
| 177 |
- La IA puede equivocarse, así que el bot mantiene fallback heurístico.
|
| 178 |
+
- El envío completo manda varios archivos seguidos; si el grupo tiene muchos episodios puede tardar.
|
| 179 |
- Si borras un mensaje del chat fuente, el índice puede quedar desactualizado hasta que vuelvas a reindexar o limpies la base.
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
## Arranque robusto en Hugging Face Spaces
|
| 183 |
+
|
| 184 |
+
Esta versión cambia dos cosas importantes:
|
| 185 |
+
|
| 186 |
+
- Si `MONGODB_URI` está vacío, arranca en **modo JSON** sin romper nada.
|
| 187 |
+
- Si faltan `API_ID`, `API_HASH` o `BOT_TOKEN`, la **web sigue arrancando** igualmente y el panel muestra qué falta. Así el Space no se queda muerto por una mala variable.
|
| 188 |
+
|
| 189 |
+
### Solución rápida si el Space no inicia
|
| 190 |
+
|
| 191 |
+
1. Revisa que el `README.md` tenga `sdk: docker` y `app_port: 7860`.
|
| 192 |
+
2. Revisa que el `Dockerfile` tenga `EXPOSE 7860`.
|
| 193 |
+
3. Revisa que el comando final escuche en `0.0.0.0:7860`.
|
| 194 |
+
4. Abre `/health` para ver el diagnóstico JSON.
|
| 195 |
+
5. Si no usas Mongo, deja `MONGODB_URI=` vacío.
|
| 196 |
+
6. Si solo quieres que arranque la web primero, puedes dejar vacíos `API_ID`, `API_HASH` y `BOT_TOKEN`; la web levantará y te lo indicará.
|
| 197 |
+
|
| 198 |
+
### Mínimo para web sola
|
| 199 |
+
|
| 200 |
+
```env
|
| 201 |
+
WEB_PANEL_TOKEN=cambia_esto
|
| 202 |
+
DATA_DIR=/data/media_archive_bot
|
| 203 |
+
MONGODB_URI=
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
### Mínimo para web + bot
|
| 207 |
+
|
| 208 |
+
```env
|
| 209 |
+
API_ID=123456
|
| 210 |
+
API_HASH=tu_api_hash
|
| 211 |
+
BOT_TOKEN=123456:ABCDEF
|
| 212 |
+
WEB_PANEL_TOKEN=cambia_esto
|
| 213 |
+
DATA_DIR=/data/media_archive_bot
|
| 214 |
+
MONGODB_URI=
|
| 215 |
+
```
|
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import logging
|
| 4 |
import tempfile
|
| 5 |
from html import escape
|
|
@@ -8,29 +9,87 @@ from pathlib import Path
|
|
| 8 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 9 |
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
| 10 |
|
| 11 |
-
from
|
|
|
|
| 12 |
from bot.config import get_settings
|
|
|
|
|
|
|
|
|
|
| 13 |
from bot.database import JsonDatabase
|
| 14 |
|
| 15 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s")
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
settings = get_settings()
|
| 19 |
-
database = JsonDatabase(
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
app = FastAPI(title=settings.bot_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
@app.on_event("startup")
|
| 26 |
async def startup_event() -> None:
|
| 27 |
-
await database.mutate(
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
@app.on_event("shutdown")
|
| 32 |
async def shutdown_event() -> None:
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
@app.get("/", response_class=HTMLResponse)
|
|
@@ -38,6 +97,14 @@ async def index() -> HTMLResponse:
|
|
| 38 |
stats = await database.get_stats()
|
| 39 |
stats["ai_enabled"] = settings.ai_enabled
|
| 40 |
storage_ids = await database.get_storage_chat_ids()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
html = f"""
|
| 42 |
<!doctype html>
|
| 43 |
<html lang="es">
|
|
@@ -47,41 +114,52 @@ async def index() -> HTMLResponse:
|
|
| 47 |
<title>{escape(settings.bot_name)}</title>
|
| 48 |
<style>
|
| 49 |
:root {{ color-scheme: dark; }}
|
|
|
|
| 50 |
body {{ font-family: Inter, Arial, sans-serif; background: #070b16; color: #edf2ff; margin: 0; }}
|
| 51 |
-
.wrap {{ max-width:
|
| 52 |
.hero {{ background: linear-gradient(135deg,#2563eb,#7c3aed 60%,#ec4899); border-radius: 28px; padding: 26px; box-shadow: 0 18px 45px rgba(0,0,0,.28); }}
|
| 53 |
-
.grid {{ display:grid; grid-template-columns: repeat(auto-fit,minmax(
|
| 54 |
.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); }}
|
| 55 |
.muted {{ color:#c7d2fe; opacity:.92; }}
|
|
|
|
|
|
|
|
|
|
| 56 |
code {{ background:#111827; padding:2px 8px; border-radius:8px; }}
|
| 57 |
a {{ color:#93c5fd; }}
|
| 58 |
input, button {{ width:100%; padding:12px 14px; border-radius:14px; border:1px solid rgba(255,255,255,.12); background:#111827; color:#fff; }}
|
| 59 |
button {{ cursor:pointer; background: linear-gradient(135deg,#2563eb,#7c3aed); border:none; font-weight:600; }}
|
| 60 |
form {{ display:grid; gap:10px; }}
|
|
|
|
| 61 |
</style>
|
| 62 |
</head>
|
| 63 |
<body>
|
| 64 |
<div class="wrap">
|
| 65 |
<div class="hero">
|
| 66 |
<h1 style="margin:0 0 10px;">🎬 {escape(settings.bot_name)}</h1>
|
| 67 |
-
<p class="muted" style="margin:0;">
|
| 68 |
</div>
|
| 69 |
<div class="grid">
|
| 70 |
-
<div class="card"><h3>Usuarios</h3><p>{stats['users']}</p></div>
|
| 71 |
-
<div class="card"><h3>Admins</h3><p>{stats['admins']}</p></div>
|
| 72 |
-
<div class="card"><h3>Ítems</h3><p>{stats['library_items']}</p></div>
|
| 73 |
-
<div class="card"><h3>Búsquedas</h3><p>{stats['searches']}</p></div>
|
| 74 |
-
<div class="card"><h3>Descargas</h3><p>{stats['downloads']}</p></div>
|
| 75 |
-
<div class="card"><h3>
|
| 76 |
-
<div class="card"><h3>
|
| 77 |
</div>
|
|
|
|
| 78 |
<div class="grid" style="margin-top:18px;">
|
| 79 |
<div class="card">
|
| 80 |
-
<h3>Estado</h3>
|
| 81 |
-
<p class="muted">Bot iniciado: <b>{'Sí' if
|
|
|
|
|
|
|
|
|
|
| 82 |
<p class="muted">Chats de almacenamiento: <code>{escape(', '.join(str(x) for x in storage_ids) or 'ninguno')}</code></p>
|
|
|
|
| 83 |
<p class="muted">Persistencia recomendada: usar <code>/data</code> si tu Space tiene almacenamiento persistente.</p>
|
| 84 |
-
<p class="muted">IA de limpieza: <b>{
|
|
|
|
| 85 |
<p class="muted">Exportar: <a href="/admin/export?token={escape(settings.web_panel_token)}">/admin/export</a></p>
|
| 86 |
</div>
|
| 87 |
<div class="card">
|
|
@@ -92,6 +170,16 @@ async def index() -> HTMLResponse:
|
|
| 92 |
<button type="submit">Importar base</button>
|
| 93 |
</form>
|
| 94 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
</div>
|
| 96 |
</div>
|
| 97 |
</body>
|
|
@@ -103,13 +191,21 @@ async def index() -> HTMLResponse:
|
|
| 103 |
@app.get("/health")
|
| 104 |
async def health() -> JSONResponse:
|
| 105 |
stats = await database.get_stats()
|
| 106 |
-
return JSONResponse(
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
@app.get("/admin/export")
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import asyncio
|
| 4 |
import logging
|
| 5 |
import tempfile
|
| 6 |
from html import escape
|
|
|
|
| 9 |
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 10 |
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
| 11 |
|
| 12 |
+
from typing import TYPE_CHECKING
|
| 13 |
+
|
| 14 |
from bot.config import get_settings
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from bot.bot_service import BotService
|
| 18 |
from bot.database import JsonDatabase
|
| 19 |
|
| 20 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s")
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
settings = get_settings()
|
| 24 |
+
database = JsonDatabase(
|
| 25 |
+
settings.database_path,
|
| 26 |
+
owner_ids=settings.owner_ids,
|
| 27 |
+
storage_chat_ids=settings.storage_chat_ids,
|
| 28 |
+
mongodb_uri=settings.mongodb_uri,
|
| 29 |
+
mongodb_db_name=settings.mongodb_db_name,
|
| 30 |
+
mongodb_collection=settings.mongodb_collection,
|
| 31 |
+
mongodb_server_selection_timeout_ms=settings.mongodb_server_selection_timeout_ms,
|
| 32 |
+
)
|
| 33 |
|
| 34 |
app = FastAPI(title=settings.bot_name)
|
| 35 |
+
bot: "BotService | None" = None
|
| 36 |
+
runtime_state = {
|
| 37 |
+
"bot_started": False,
|
| 38 |
+
"bot_configured": settings.bot_enabled,
|
| 39 |
+
"bot_start_error": None,
|
| 40 |
+
"missing_bot_env_vars": settings.missing_bot_env_vars,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
async def _start_bot_if_possible() -> None:
|
| 45 |
+
global bot
|
| 46 |
+
runtime_state["bot_configured"] = settings.bot_enabled
|
| 47 |
+
runtime_state["missing_bot_env_vars"] = settings.missing_bot_env_vars
|
| 48 |
+
|
| 49 |
+
if not settings.bot_enabled:
|
| 50 |
+
runtime_state["bot_start_error"] = (
|
| 51 |
+
"Faltan variables para Telegram: " + ", ".join(settings.missing_bot_env_vars)
|
| 52 |
+
)
|
| 53 |
+
logger.warning(runtime_state["bot_start_error"])
|
| 54 |
+
return
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
from bot.bot_service import BotService
|
| 58 |
+
|
| 59 |
+
bot = BotService(settings, database)
|
| 60 |
+
await asyncio.wait_for(bot.start(), timeout=45)
|
| 61 |
+
runtime_state["bot_started"] = True
|
| 62 |
+
runtime_state["bot_start_error"] = None
|
| 63 |
+
except Exception as exc:
|
| 64 |
+
runtime_state["bot_started"] = False
|
| 65 |
+
runtime_state["bot_start_error"] = str(exc)
|
| 66 |
+
logger.exception("No pude iniciar el bot de Telegram")
|
| 67 |
+
bot = None
|
| 68 |
|
| 69 |
|
| 70 |
@app.on_event("startup")
|
| 71 |
async def startup_event() -> None:
|
| 72 |
+
await database.mutate(
|
| 73 |
+
lambda data: data.setdefault("config", {}).update(
|
| 74 |
+
{
|
| 75 |
+
"ai_enabled": settings.ai_enabled,
|
| 76 |
+
"db_backend": "json+mongo" if settings.mongodb_enabled else "json",
|
| 77 |
+
"not_found_chat_id": settings.not_found_chat_id,
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
)
|
| 81 |
+
await _start_bot_if_possible()
|
| 82 |
|
| 83 |
|
| 84 |
@app.on_event("shutdown")
|
| 85 |
async def shutdown_event() -> None:
|
| 86 |
+
global bot
|
| 87 |
+
if not bot:
|
| 88 |
+
return
|
| 89 |
+
try:
|
| 90 |
+
await bot.stop()
|
| 91 |
+
finally:
|
| 92 |
+
runtime_state["bot_started"] = False
|
| 93 |
|
| 94 |
|
| 95 |
@app.get("/", response_class=HTMLResponse)
|
|
|
|
| 97 |
stats = await database.get_stats()
|
| 98 |
stats["ai_enabled"] = settings.ai_enabled
|
| 99 |
storage_ids = await database.get_storage_chat_ids()
|
| 100 |
+
mongo_status = "🟢 conectado" if stats.get("mongo_ready") else ("🟡 configurado" if stats.get("mongo_enabled") else "⚪ JSON local")
|
| 101 |
+
bot_status = "🟢 conectado" if runtime_state["bot_started"] else ("🟡 pendiente" if runtime_state["bot_configured"] else "⚪ web solo")
|
| 102 |
+
bot_error_html = ""
|
| 103 |
+
if runtime_state.get("bot_start_error"):
|
| 104 |
+
bot_error_html = f'<div class="notice warn"><b>Diagnóstico bot:</b> {escape(str(runtime_state["bot_start_error"]))}</div>'
|
| 105 |
+
missing_html = ""
|
| 106 |
+
if runtime_state.get("missing_bot_env_vars"):
|
| 107 |
+
missing_html = f'<p class="muted">Variables Telegram pendientes: <code>{escape(", ".join(runtime_state["missing_bot_env_vars"]))}</code></p>'
|
| 108 |
html = f"""
|
| 109 |
<!doctype html>
|
| 110 |
<html lang="es">
|
|
|
|
| 114 |
<title>{escape(settings.bot_name)}</title>
|
| 115 |
<style>
|
| 116 |
:root {{ color-scheme: dark; }}
|
| 117 |
+
* {{ box-sizing: border-box; }}
|
| 118 |
body {{ font-family: Inter, Arial, sans-serif; background: #070b16; color: #edf2ff; margin: 0; }}
|
| 119 |
+
.wrap {{ max-width: 1120px; margin: 0 auto; padding: 28px 16px 48px; }}
|
| 120 |
.hero {{ background: linear-gradient(135deg,#2563eb,#7c3aed 60%,#ec4899); border-radius: 28px; padding: 26px; box-shadow: 0 18px 45px rgba(0,0,0,.28); }}
|
| 121 |
+
.grid {{ display:grid; grid-template-columns: repeat(auto-fit,minmax(180px,1fr)); gap:16px; margin-top:20px; }}
|
| 122 |
.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); }}
|
| 123 |
.muted {{ color:#c7d2fe; opacity:.92; }}
|
| 124 |
+
.notice {{ margin-top: 16px; padding: 14px 16px; border-radius: 16px; }}
|
| 125 |
+
.warn {{ background:#3b1d1d; border:1px solid rgba(248,113,113,.35); color:#fecaca; }}
|
| 126 |
+
.ok {{ background:#0f2e1f; border:1px solid rgba(74,222,128,.28); color:#dcfce7; }}
|
| 127 |
code {{ background:#111827; padding:2px 8px; border-radius:8px; }}
|
| 128 |
a {{ color:#93c5fd; }}
|
| 129 |
input, button {{ width:100%; padding:12px 14px; border-radius:14px; border:1px solid rgba(255,255,255,.12); background:#111827; color:#fff; }}
|
| 130 |
button {{ cursor:pointer; background: linear-gradient(135deg,#2563eb,#7c3aed); border:none; font-weight:600; }}
|
| 131 |
form {{ display:grid; gap:10px; }}
|
| 132 |
+
ul {{ margin: 0; padding-left: 18px; }}
|
| 133 |
</style>
|
| 134 |
</head>
|
| 135 |
<body>
|
| 136 |
<div class="wrap">
|
| 137 |
<div class="hero">
|
| 138 |
<h1 style="margin:0 0 10px;">🎬 {escape(settings.bot_name)}</h1>
|
| 139 |
+
<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>
|
| 140 |
</div>
|
| 141 |
<div class="grid">
|
| 142 |
+
<div class="card"><h3>👥 Usuarios</h3><p>{stats['users']}</p></div>
|
| 143 |
+
<div class="card"><h3>🛡️ Admins</h3><p>{stats['admins']}</p></div>
|
| 144 |
+
<div class="card"><h3>🎞️ Ítems</h3><p>{stats['library_items']}</p></div>
|
| 145 |
+
<div class="card"><h3>🔎 Búsquedas</h3><p>{stats['searches']}</p></div>
|
| 146 |
+
<div class="card"><h3>📥 Descargas</h3><p>{stats['downloads']}</p></div>
|
| 147 |
+
<div class="card"><h3>🤖 Telegram</h3><p>{bot_status}</p></div>
|
| 148 |
+
<div class="card"><h3>🍃 MongoDB</h3><p>{mongo_status}</p></div>
|
| 149 |
</div>
|
| 150 |
+
{bot_error_html}
|
| 151 |
<div class="grid" style="margin-top:18px;">
|
| 152 |
<div class="card">
|
| 153 |
+
<h3>Estado del Space</h3>
|
| 154 |
+
<p class="muted">Bot iniciado: <b>{'Sí' if runtime_state['bot_started'] else 'No'}</b></p>
|
| 155 |
+
<p class="muted">Bot configurado: <b>{'Sí' if runtime_state['bot_configured'] else 'No'}</b></p>
|
| 156 |
+
{missing_html}
|
| 157 |
+
<p class="muted">Backend: <code>{escape(str(stats.get('db_backend', 'json')))}</code></p>
|
| 158 |
<p class="muted">Chats de almacenamiento: <code>{escape(', '.join(str(x) for x in storage_ids) or 'ninguno')}</code></p>
|
| 159 |
+
<p class="muted">Chat búsquedas vacías: <code>{escape(str(stats.get('not_found_chat_id') or 'ninguno'))}</code></p>
|
| 160 |
<p class="muted">Persistencia recomendada: usar <code>/data</code> si tu Space tiene almacenamiento persistente.</p>
|
| 161 |
+
<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>
|
| 162 |
+
<p class="muted">Healthcheck JSON: <a href="/health">/health</a></p>
|
| 163 |
<p class="muted">Exportar: <a href="/admin/export?token={escape(settings.web_panel_token)}">/admin/export</a></p>
|
| 164 |
</div>
|
| 165 |
<div class="card">
|
|
|
|
| 170 |
<button type="submit">Importar base</button>
|
| 171 |
</form>
|
| 172 |
</div>
|
| 173 |
+
<div class="card">
|
| 174 |
+
<h3>Checklist Hugging Face</h3>
|
| 175 |
+
<ul class="muted">
|
| 176 |
+
<li><code>sdk: docker</code> y <code>app_port: 7860</code> en README</li>
|
| 177 |
+
<li><code>EXPOSE 7860</code> en Dockerfile</li>
|
| 178 |
+
<li>uvicorn escuchando en <code>0.0.0.0:7860</code></li>
|
| 179 |
+
<li>Secrets correctos en Settings → Variables and secrets</li>
|
| 180 |
+
<li>Si no usas Mongo, deja <code>MONGODB_URI</code> vacío</li>
|
| 181 |
+
</ul>
|
| 182 |
+
</div>
|
| 183 |
</div>
|
| 184 |
</div>
|
| 185 |
</body>
|
|
|
|
| 191 |
@app.get("/health")
|
| 192 |
async def health() -> JSONResponse:
|
| 193 |
stats = await database.get_stats()
|
| 194 |
+
return JSONResponse(
|
| 195 |
+
{
|
| 196 |
+
"ok": True,
|
| 197 |
+
"web_ok": True,
|
| 198 |
+
"bot_started": runtime_state["bot_started"],
|
| 199 |
+
"bot_configured": runtime_state["bot_configured"],
|
| 200 |
+
"bot_start_error": runtime_state["bot_start_error"],
|
| 201 |
+
"missing_bot_env_vars": runtime_state["missing_bot_env_vars"],
|
| 202 |
+
"users": stats["users"],
|
| 203 |
+
"library_items": stats["library_items"],
|
| 204 |
+
"maintenance": stats["maintenance"],
|
| 205 |
+
"db_backend": stats.get("db_backend", "json"),
|
| 206 |
+
"mongo_ready": stats.get("mongo_ready", False),
|
| 207 |
+
}
|
| 208 |
+
)
|
| 209 |
|
| 210 |
|
| 211 |
@app.get("/admin/export")
|
requirements.txt
CHANGED
|
@@ -5,3 +5,6 @@ uvicorn[standard]==0.34.0
|
|
| 5 |
python-dotenv==1.0.1
|
| 6 |
python-multipart==0.0.9
|
| 7 |
httpx==0.28.1
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
python-dotenv==1.0.1
|
| 6 |
python-multipart==0.0.9
|
| 7 |
httpx==0.28.1
|
| 8 |
+
pymongo[srv]==4.11.1
|
| 9 |
+
|
| 10 |
+
dnspython==2.7.0
|