"""
app.py — Servidor FastAPI mínimo
=================================
• Mantiene el Hugging Face Space activo (keepalive)
• Arranca el bot de Telegram con su propio event loop en un hilo separado
• Sin Google Drive ni OAuth — todo en Telegram
"""
import os
import asyncio
import threading
import logging
import pathlib
import uvicorn
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(message)s",
level=logging.INFO
)
log = logging.getLogger(__name__)
DATA_DIR = pathlib.Path(os.environ.get("DATA_DIR", "/home/user/app/data"))
DATA_DIR.mkdir(parents=True, exist_ok=True)
api = FastAPI(title="TelegramMediaBot")
@api.get("/", response_class=HTMLResponse)
async def root():
token = os.environ.get("TELEGRAM_TOKEN", "")
if not token:
return HTMLResponse("""
⚠️ Falta TELEGRAM_TOKEN
Agrega la variable TELEGRAM_TOKEN en
Settings → Variables and Secrets y reinicia el Space.
""")
return """
📱 TelegramMediaBot
Tu galería personal en Telegram.
Fotos, videos, audios y álbumes.
Bot activo · Almacenamiento nativo Telegram
"""
@api.get("/health")
async def health():
token_ok = bool(os.environ.get("TELEGRAM_TOKEN"))
return {"status": "ok" if token_ok else "misconfigured", "telegram_token": token_ok}
def start_bot():
"""Crea su propio event loop en el hilo secundario y corre el bot."""
import bot
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(bot.main_async())
except Exception as e:
log.exception(f"Error en el bot: {e}")
finally:
loop.close()
if __name__ == "__main__":
import bot as bot_module
bot_module.DB_PATH = str(DATA_DIR / "media.db")
bot_module.init_db()
if not os.environ.get("TELEGRAM_TOKEN"):
log.error("TELEGRAM_TOKEN no configurado — el bot no iniciara")
log.info("Servidor web activo igualmente para mostrar instrucciones")
else:
t = threading.Thread(target=start_bot, daemon=True)
t.start()
log.info("Bot lanzado en hilo secundario")
port = int(os.environ.get("PORT", 7860))
log.info(f"Servidor FastAPI en puerto {port}")
uvicorn.run(api, host="0.0.0.0", port=port)