""" main.py — Punto de entrada del UserBot. • Carga todos los plugins automáticamente desde /plugins • Inicia un servidor HTTP mínimo de health-check en PORT (7860) para mantener el Space de Hugging Face vivo • Imprime tabla de comandos al iniciar """ import asyncio import logging import os import sys import time import importlib import pkgutil from pathlib import Path from aiohttp import web from pyrogram import idle from config import Config # ── Logging ─────────────────────────────────────────────────────────────────── logging.basicConfig( level=logging.INFO, format="%(asctime)s │ %(levelname)-8s │ %(name)s │ %(message)s", datefmt="%H:%M:%S", ) log = logging.getLogger("userbot") # Silence noisy libs for lib in ("pyrogram", "asyncio", "aiohttp.access"): logging.getLogger(lib).setLevel(logging.WARNING) # ── Sanity checks ───────────────────────────────────────────────────────────── def _check_env(): missing = [k for k in ("API_ID", "API_HASH", "SESSION_STRING") if not os.environ.get(k)] if missing: log.error("❌ Variables de entorno faltantes: %s", ", ".join(missing)) log.error(" Configúralas en HF Spaces → Settings → Secrets") sys.exit(1) # ── Plugin loader ───────────────────────────────────────────────────────────── def _load_plugins(): plugins_dir = Path(__file__).parent / "plugins" loaded = [] for _, name, _ in pkgutil.iter_modules([str(plugins_dir)]): try: importlib.import_module(f"plugins.{name}") loaded.append(name) log.info(" ✅ Plugin cargado: %s", name) except Exception as e: log.error(" ❌ Error cargando plugin '%s': %s", name, e) return loaded # ── Minimal health-check HTTP server ───────────────────────────────────────── async def _start_web(): async def health(_): return web.Response( text='{"status":"ok","userbot":"running"}', content_type="application/json", ) async def index(_): return web.Response( text="

🤖 TG UserBot — activo

", content_type="text/html", ) app_web = web.Application() app_web.router.add_get("/", index) app_web.router.add_get("/health", health) runner = web.AppRunner(app_web) await runner.setup() site = web.TCPSite(runner, "0.0.0.0", Config.PORT) await site.start() log.info("🌐 Health server escuchando en 0.0.0.0:%d", Config.PORT) # ── Banner ──────────────────────────────────────────────────────────────────── BANNER = r""" ╔══════════════════════════════════════════════════╗ ║ 🤖 TG UserBot — by Pyrogram ║ ╠══════════════════════════════════════════════════╣ ║ Prefix : {prefix:<6} Owner-only : ✅ ║ ║ Plugins: {plugins:<6} Health port: {port:<5} ║ ╚══════════════════════════════════════════════════╝ """.strip() # ── Main ────────────────────────────────────────────────────────────────────── async def main(): _check_env() # Create needed directories for d in ("plugins", "utils", "data", "temp"): Path(d).mkdir(exist_ok=True) log.info("🔌 Cargando plugins...") from bot import app as tg_app # triggers pyrogram Client creation plugins = _load_plugins() log.info("🔐 Conectando a Telegram...") await tg_app.start() me = await tg_app.get_me() log.info("✅ Conectado como: %s (@%s | ID: %s)", me.first_name, me.username or "sin_username", me.id) print("\n" + BANNER.format( prefix=Config.CMD_PREFIX, plugins=len(plugins), port=Config.PORT, ) + "\n") # Start web health server (keeps HF Space alive) await _start_web() log.info("🚀 UserBot listo. Escuchando mensajes...") await idle() log.info("🛑 Deteniendo...") await tg_app.stop() if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: log.info("Detenido por el usuario.")