03-sep: [videoclub] Busqueda global (miles de pelis) via Cinemeta+Torrentio con /busca /torrents /bajar a NAS

This commit is contained in:
juanjo
2026-09-03 20:44:44 +02:00
parent 451e5ce3c7
commit cfd952c780
3 changed files with 405 additions and 0 deletions

View File

@@ -8,6 +8,10 @@ import urllib.parse
import requests
# Estado por chat para la busqueda global interactiva (numero -> descarga)
ultima_titulos = {} # chat_id -> {'query':..., 'results':[...]}
ultimos_torrents = {} # chat_id -> {'titulo':..., 'torrents':[...]}
BASE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.join(BASE, "bot.log")
OFFSET_FILE = os.path.join(BASE, "bot.offset")
@@ -191,6 +195,15 @@ def procesar(texto, chat_id):
procesar_buscador_serie(nombre, chat_id)
elif t in ("novedades", "/novedades"):
procesar_novedades(chat_id)
elif t.startswith("busca ") or t.startswith("/busca "):
nombre = texto.split(" ", 1)[1].strip()
procesar_busca(nombre, chat_id)
elif t.startswith("torrents ") or t.startswith("/torrents "):
n = _int_arg(texto)
procesar_torrents(n, chat_id)
elif t.startswith("bajar ") or t.startswith("/bajar "):
n = _int_arg(texto)
procesar_bajar(n, chat_id)
elif t in ("ayuda", "/ayuda", "help", "/help"):
enviar("Comandos:\n"
"<b>estado</b> — estado de la Pi\n"
@@ -202,6 +215,9 @@ def procesar(texto, chat_id):
"<b>pelicula &lt;nombre&gt;</b> — buscar pelicula y descargar\n"
"<b>serie &lt;nombre&gt;</b> — buscar serie con temporadas/capitulos\n"
"<b>novedades</b> — ultimas novedades del catalogo\n"
"<b>busca &lt;nombre&gt;</b> — buscar en TODO internet (miles de pelis)\n"
"<b>torrents &lt;n&gt;</b> — ver torrents del resultado n de /busca\n"
"<b>bajar &lt;n&gt;</b> — descargar al NAS el torrent n de /torrents\n"
"<b>panorama</b> — fotos de las cámaras\n"
"<b>limpieza</b> — limpia procesos atascados de la Pi\n"
"<b>reboot</b> — reinicia la Pi (necesita confirmar con /confirmar-reboot)\n"
@@ -371,6 +387,105 @@ def procesar_novedades(chat_id):
enviar(m, chat_id)
def _int_arg(texto):
"""Extrae el numero de un comando tipo '/bajar 3'."""
partes = texto.split()
for p in partes[1:]:
if p.isdigit():
return int(p)
return None
def _import_global_buscar():
sys.path.insert(0, os.path.join(BASE, "..", "videoclub"))
import global_buscar as gol
return gol
def procesar_busca(nombre, chat_id):
"""Busqueda global (Cinemeta): texto -> titulos con id IMDb numerados."""
try:
gol = _import_global_buscar()
except Exception as e:
log(f"global_buscar import error: {e}")
enviar("❌ No se pudo cargar el modulo de busqueda global", chat_id)
return
enviar(f"🔎 Buscando <b>{nombre}</b> en todo el catalogo online...", chat_id)
try:
resultados = gol.buscar_titulos(nombre)
mensajes = gol.formatear_titulos(resultados)
except Exception as e:
log(f"busca error: {e}")
enviar(f"❌ Error en la busqueda: {e}", chat_id)
return
for m in mensajes:
enviar(m, chat_id)
if resultados:
ultima_titulos[chat_id] = {"query": nombre, "results": resultados}
log(f"BUSCA global '{nombre}': {len(resultados)} titulos")
def procesar_torrents(n, chat_id):
"""Muestra los torrents (Torrentio) del titulo numero n de la ultima busqueda."""
estado = ultima_titulos.get(chat_id)
if not estado or n is None or n < 1 or n > len(estado["results"]):
enviar("Primero usa <b>/busca &lt;nombre&gt;</b> y luego "
"<b>/torrents &lt;numero&gt;</b>.", chat_id)
return
try:
gol = _import_global_buscar()
except Exception as e:
log(f"global_buscar import error: {e}")
enviar("❌ No se pudo cargar el modulo", chat_id)
return
r = estado["results"][n - 1]
enviar(f"🧲 Buscando torrents de <b>{r['name']}</b>...", chat_id)
try:
torrents = gol.torrents_de(r["imdb_id"], r["type"])
torrents = gol.filtrar_torrents(torrents)
mensajes = gol.formatear_torrents(torrents, r["name"])
except Exception as e:
log(f"torrents error: {e}")
enviar(f"❌ Error obteniendo torrents: {e}", chat_id)
return
for m in mensajes:
enviar(m, chat_id)
if torrents:
ultimos_torrents[chat_id] = {"titulo": r["name"], "torrents": torrents}
log(f"TORRENTS '{r['name']}': {len(torrents)} torrents")
def procesar_bajar(n, chat_id):
"""Descarga el torrent numero n al NAS (Download Station via magnet)."""
estado = ultimos_torrents.get(chat_id)
if not estado or n is None or n < 1 or n > len(estado["torrents"]):
enviar("Primero usa <b>/busca &lt;nombre&gt;</b> y luego "
"<b>/torrents &lt;numero&gt;</b>.", chat_id)
return
try:
gol = _import_global_buscar()
except Exception as e:
log(f"global_buscar import error: {e}")
enviar("❌ No se pudo cargar el modulo", chat_id)
return
t = estado["torrents"][n - 1]
magnet = gol.magnet_de(t)
log(f"BAJAR '{estado['titulo']}' torrent {n}: {magnet[:60]}...")
try:
import nas_dl
ok = nas_dl.add_torrent(magnet)
except Exception as e:
log(f"bajar error: {e}")
enviar(f"❌ Error al anadir al NAS: {e}", chat_id)
return
if ok:
tamaño = f"{t['size']:.1f}GB" if t.get("size") else "?"
enviar(f"📥 Añadido al NAS: <b>{t['filename'] or estado['titulo']}</b> "
f"({t['calidad']}, {tamaño}).", chat_id)
else:
enviar("❌ No se pudo añadir al NAS.", chat_id)
def monitor_temperatura():
while True:
time.sleep(300)