Spaces:
Sleeping
Sleeping
Upload 71 files
Browse files- bot_telegram/bot.py +36 -34
bot_telegram/bot.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
|
|
|
| 3 |
from telethon import TelegramClient, events
|
| 4 |
from fastapi import FastAPI, UploadFile, File
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
|
@@ -16,7 +17,7 @@ API_HASH = os.getenv("TELEGRAM_API_HASH", "")
|
|
| 16 |
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
|
| 17 |
CHANNEL_ID = int(os.getenv("TELEGRAM_CHANNEL_ID", "0"))
|
| 18 |
|
| 19 |
-
#
|
| 20 |
PORT = int(os.getenv("PORT", "7860"))
|
| 21 |
|
| 22 |
if not os.path.exists("sessions"):
|
|
@@ -25,8 +26,26 @@ if not os.path.exists("sessions"):
|
|
| 25 |
# 2. Inicializar Cliente de Telethon
|
| 26 |
client = TelegramClient('sessions/bot_session', API_ID, API_HASH)
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
# 3. Servidor API con FastAPI
|
| 29 |
-
app_api = FastAPI()
|
| 30 |
|
| 31 |
app_api.add_middleware(
|
| 32 |
CORSMiddleware,
|
|
@@ -35,21 +54,18 @@ app_api.add_middleware(
|
|
| 35 |
allow_headers=["*"],
|
| 36 |
)
|
| 37 |
|
| 38 |
-
# --- COMANDOS DEL BOT
|
| 39 |
|
| 40 |
@client.on(events.NewMessage(pattern='/start'))
|
| 41 |
async def start_handler(event):
|
| 42 |
parts = event.raw_text.split()
|
| 43 |
if len(parts) > 1:
|
| 44 |
-
file_id = parts[1]
|
| 45 |
try:
|
| 46 |
-
msg_id = int(
|
| 47 |
await client.forward_messages(event.chat_id, msg_id, CHANNEL_ID)
|
| 48 |
return
|
| 49 |
-
except
|
| 50 |
-
|
| 51 |
-
return
|
| 52 |
-
|
| 53 |
await event.respond('¡Hola! Soy el bot de CodeByDante. Usa la web para descargar tus archivos.')
|
| 54 |
|
| 55 |
# --- ENDPOINTS DE LA API ---
|
|
@@ -62,24 +78,21 @@ async def upload_file(file: UploadFile = File(...)):
|
|
| 62 |
content = await file.read()
|
| 63 |
buffer.write(content)
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
file_path,
|
| 68 |
-
caption=f"Archivo subido desde CodeByDante: {file.filename}"
|
| 69 |
-
)
|
| 70 |
os.remove(file_path)
|
|
|
|
| 71 |
return {
|
| 72 |
"status": "success",
|
| 73 |
"message_id": sent_msg.id,
|
| 74 |
-
"channel_id": CHANNEL_ID
|
| 75 |
-
"filename": file.filename
|
| 76 |
}
|
| 77 |
except Exception as e:
|
|
|
|
| 78 |
return {"status": "error", "message": str(e)}
|
| 79 |
|
| 80 |
-
# --- SERVIR FRONTEND
|
| 81 |
|
| 82 |
-
# Ruta a la carpeta 'dist' (está un nivel arriba si corremos desde bot_telegram/)
|
| 83 |
dist_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "dist"))
|
| 84 |
|
| 85 |
if os.path.exists(dist_path):
|
|
@@ -92,25 +105,14 @@ if os.path.exists(dist_path):
|
|
| 92 |
|
| 93 |
@app_api.get("/{full_path:path}")
|
| 94 |
async def serve_spa(full_path: str):
|
| 95 |
-
# Si la ruta no es un archivo real, sirve el index.html (para React Router)
|
| 96 |
local_file = os.path.join(dist_path, full_path)
|
| 97 |
if os.path.exists(local_file) and os.path.isfile(local_file):
|
| 98 |
return FileResponse(local_file)
|
| 99 |
return FileResponse(os.path.join(dist_path, "index.html"))
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
print("Iniciando Bot de Telegram...")
|
| 105 |
-
await client.start(bot_token=BOT_TOKEN)
|
| 106 |
-
print("Bot en línea.")
|
| 107 |
-
|
| 108 |
-
config = uvicorn.Config(app_api, host="0.0.0.0", port=PORT, log_level="info")
|
| 109 |
-
server = uvicorn.Server(config)
|
| 110 |
-
await server.serve()
|
| 111 |
|
| 112 |
if __name__ == '__main__':
|
| 113 |
-
|
| 114 |
-
asyncio.run(main())
|
| 115 |
-
except KeyboardInterrupt:
|
| 116 |
-
pass
|
|
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
+
from contextlib import asynccontextmanager
|
| 4 |
from telethon import TelegramClient, events
|
| 5 |
from fastapi import FastAPI, UploadFile, File
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 17 |
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
|
| 18 |
CHANNEL_ID = int(os.getenv("TELEGRAM_CHANNEL_ID", "0"))
|
| 19 |
|
| 20 |
+
# FORZAMOS el puerto 7860 para Hugging Face
|
| 21 |
PORT = int(os.getenv("PORT", "7860"))
|
| 22 |
|
| 23 |
if not os.path.exists("sessions"):
|
|
|
|
| 26 |
# 2. Inicializar Cliente de Telethon
|
| 27 |
client = TelegramClient('sessions/bot_session', API_ID, API_HASH)
|
| 28 |
|
| 29 |
+
# --- CICLO DE VIDA (LIFESPAN) ---
|
| 30 |
+
# Esto asegura que el bot arranque sin importar cómo se inicie el servidor
|
| 31 |
+
@asynccontextmanager
|
| 32 |
+
async def lifespan(app: FastAPI):
|
| 33 |
+
print("--- INICIANDO SISTEMA HÍBRIDO ---")
|
| 34 |
+
print(f"Puerto detectado: {PORT}")
|
| 35 |
+
try:
|
| 36 |
+
print("Iniciando Bot de Telegram...")
|
| 37 |
+
await client.start(bot_token=BOT_TOKEN)
|
| 38 |
+
print("¡Bot en línea y escuchando!")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"ERROR AL INICIAR BOT: {e}")
|
| 41 |
+
|
| 42 |
+
yield
|
| 43 |
+
|
| 44 |
+
print("Apagando sistema...")
|
| 45 |
+
await client.disconnect()
|
| 46 |
+
|
| 47 |
# 3. Servidor API con FastAPI
|
| 48 |
+
app_api = FastAPI(lifespan=lifespan)
|
| 49 |
|
| 50 |
app_api.add_middleware(
|
| 51 |
CORSMiddleware,
|
|
|
|
| 54 |
allow_headers=["*"],
|
| 55 |
)
|
| 56 |
|
| 57 |
+
# --- COMANDOS DEL BOT ---
|
| 58 |
|
| 59 |
@client.on(events.NewMessage(pattern='/start'))
|
| 60 |
async def start_handler(event):
|
| 61 |
parts = event.raw_text.split()
|
| 62 |
if len(parts) > 1:
|
|
|
|
| 63 |
try:
|
| 64 |
+
msg_id = int(parts[1])
|
| 65 |
await client.forward_messages(event.chat_id, msg_id, CHANNEL_ID)
|
| 66 |
return
|
| 67 |
+
except:
|
| 68 |
+
pass
|
|
|
|
|
|
|
| 69 |
await event.respond('¡Hola! Soy el bot de CodeByDante. Usa la web para descargar tus archivos.')
|
| 70 |
|
| 71 |
# --- ENDPOINTS DE LA API ---
|
|
|
|
| 78 |
content = await file.read()
|
| 79 |
buffer.write(content)
|
| 80 |
|
| 81 |
+
print(f"Subiendo '{file.filename}' a Telegram...")
|
| 82 |
+
sent_msg = await client.send_file(CHANNEL_ID, file_path)
|
|
|
|
|
|
|
|
|
|
| 83 |
os.remove(file_path)
|
| 84 |
+
|
| 85 |
return {
|
| 86 |
"status": "success",
|
| 87 |
"message_id": sent_msg.id,
|
| 88 |
+
"channel_id": CHANNEL_ID
|
|
|
|
| 89 |
}
|
| 90 |
except Exception as e:
|
| 91 |
+
print(f"Error en upload: {e}")
|
| 92 |
return {"status": "error", "message": str(e)}
|
| 93 |
|
| 94 |
+
# --- SERVIR FRONTEND ---
|
| 95 |
|
|
|
|
| 96 |
dist_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "dist"))
|
| 97 |
|
| 98 |
if os.path.exists(dist_path):
|
|
|
|
| 105 |
|
| 106 |
@app_api.get("/{full_path:path}")
|
| 107 |
async def serve_spa(full_path: str):
|
|
|
|
| 108 |
local_file = os.path.join(dist_path, full_path)
|
| 109 |
if os.path.exists(local_file) and os.path.isfile(local_file):
|
| 110 |
return FileResponse(local_file)
|
| 111 |
return FileResponse(os.path.join(dist_path, "index.html"))
|
| 112 |
+
else:
|
| 113 |
+
@app_api.get("/")
|
| 114 |
+
async def hello():
|
| 115 |
+
return {"message": "Servidor activo. Carpeta 'dist' no encontrada."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
if __name__ == '__main__':
|
| 118 |
+
uvicorn.run(app_api, host="0.0.0.0", port=PORT)
|
|
|
|
|
|
|
|
|