userbotsaskeds / main.py
saske560's picture
Upload 7 files
b405713 verified
Raw History Blame Contribute Delete
5.16 kB
"""
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="<h2>πŸ€– TG UserBot β€” activo</h2>",
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.")