Spaces:
Sleeping
Sleeping
Upload 71 files
Browse files- Dockerfile +24 -16
- bot_telegram/bot.py +32 -27
- components/EditorToolbar.tsx +1 -1
- requirements.txt +6 -0
Dockerfile
CHANGED
|
@@ -1,25 +1,33 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
# Establecer el directorio de trabajo
|
| 4 |
WORKDIR /app
|
| 5 |
-
|
| 6 |
-
# Copiar los archivos package.json y package-lock.json
|
| 7 |
COPY package*.json ./
|
| 8 |
-
|
| 9 |
-
# Instalar dependencias
|
| 10 |
RUN npm install
|
| 11 |
-
|
| 12 |
-
# Copiar el resto del código
|
| 13 |
COPY . .
|
| 14 |
-
|
| 15 |
-
# Construir la aplicación para producción con Vite
|
| 16 |
RUN npm run build
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
#
|
| 22 |
EXPOSE 7860
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
CMD ["
|
|
|
|
| 1 |
+
# --- STAGE 1: Build the React Frontend ---
|
| 2 |
+
FROM node:18 AS build-stage
|
|
|
|
| 3 |
WORKDIR /app
|
|
|
|
|
|
|
| 4 |
COPY package*.json ./
|
|
|
|
|
|
|
| 5 |
RUN npm install
|
|
|
|
|
|
|
| 6 |
COPY . .
|
|
|
|
|
|
|
| 7 |
RUN npm run build
|
| 8 |
|
| 9 |
+
# --- STAGE 2: Run the Python Bot + FastAPI Server ---
|
| 10 |
+
FROM python:3.11-slim
|
| 11 |
+
WORKDIR /app
|
| 12 |
+
|
| 13 |
+
# Instalar dependencias del sistema
|
| 14 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 15 |
+
build-essential \
|
| 16 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 17 |
+
|
| 18 |
+
# Copiar requerimientos e instalar
|
| 19 |
+
COPY requirements.txt .
|
| 20 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 21 |
+
|
| 22 |
+
# Copiar el build del frontend
|
| 23 |
+
COPY --from=build-stage /app/dist /app/dist
|
| 24 |
+
|
| 25 |
+
# Copiar el código del bot
|
| 26 |
+
COPY bot_telegram /app/bot_telegram
|
| 27 |
+
WORKDIR /app/bot_telegram
|
| 28 |
|
| 29 |
+
# Exponer el puerto de Hugging Face (7860)
|
| 30 |
EXPOSE 7860
|
| 31 |
|
| 32 |
+
# El comando de inicio será correr el bot
|
| 33 |
+
CMD ["python", "bot.py"]
|
bot_telegram/bot.py
CHANGED
|
@@ -3,6 +3,8 @@ import asyncio
|
|
| 3 |
from telethon import TelegramClient, events
|
| 4 |
from fastapi import FastAPI, UploadFile, File
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
|
| 6 |
import uvicorn
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
|
|
@@ -14,11 +16,13 @@ API_HASH = os.getenv("TELEGRAM_API_HASH", "")
|
|
| 14 |
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
|
| 15 |
CHANNEL_ID = int(os.getenv("TELEGRAM_CHANNEL_ID", "0"))
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
if not os.path.exists("sessions"):
|
| 18 |
os.makedirs("sessions")
|
| 19 |
|
| 20 |
# 2. Inicializar Cliente de Telethon
|
| 21 |
-
# Usamos 'sessions/bot_session' para guardar el archivo .session
|
| 22 |
client = TelegramClient('sessions/bot_session', API_ID, API_HASH)
|
| 23 |
|
| 24 |
# 3. Servidor API con FastAPI
|
|
@@ -35,29 +39,18 @@ app_api.add_middleware(
|
|
| 35 |
|
| 36 |
@client.on(events.NewMessage(pattern='/start'))
|
| 37 |
async def start_handler(event):
|
| 38 |
-
# Revisar si el comando trae un ID (Deep Link)
|
| 39 |
-
# Ejemplo: /start 12345
|
| 40 |
parts = event.raw_text.split()
|
| 41 |
if len(parts) > 1:
|
| 42 |
file_id = parts[1]
|
| 43 |
try:
|
| 44 |
msg_id = int(file_id)
|
| 45 |
-
print(f"Buscando archivo con ID: {msg_id} para el usuario {event.sender_id}")
|
| 46 |
-
|
| 47 |
-
# Reenviar el archivo desde el canal al usuario
|
| 48 |
await client.forward_messages(event.chat_id, msg_id, CHANNEL_ID)
|
| 49 |
-
return
|
| 50 |
except Exception as e:
|
| 51 |
-
|
| 52 |
-
await event.respond("Lo siento, no pude encontrar ese archivo o ha sido eliminado.")
|
| 53 |
return
|
| 54 |
|
| 55 |
-
|
| 56 |
-
await event.respond('¡Hola! Soy el bot de CodeByDante. Usa los botones de la web para descargar tus archivos aquí.')
|
| 57 |
-
|
| 58 |
-
@client.on(events.NewMessage(pattern='/id'))
|
| 59 |
-
async def id_handler(event):
|
| 60 |
-
await event.respond(f'Tu ID es: `{event.sender_id}`\nID del Chat: `{event.chat_id}`')
|
| 61 |
|
| 62 |
# --- ENDPOINTS DE LA API ---
|
| 63 |
|
|
@@ -69,15 +62,11 @@ async def upload_file(file: UploadFile = File(...)):
|
|
| 69 |
content = await file.read()
|
| 70 |
buffer.write(content)
|
| 71 |
|
| 72 |
-
print(f"Subiendo '{file.filename}' a Telegram vía Telethon...")
|
| 73 |
-
# Enviar al canal y capturar el mensaje enviado
|
| 74 |
sent_msg = await client.send_file(
|
| 75 |
CHANNEL_ID,
|
| 76 |
file_path,
|
| 77 |
caption=f"Archivo subido desde CodeByDante: {file.filename}"
|
| 78 |
)
|
| 79 |
-
print(f"¡Subida completada con éxito! ID: {sent_msg.id}")
|
| 80 |
-
|
| 81 |
os.remove(file_path)
|
| 82 |
return {
|
| 83 |
"status": "success",
|
|
@@ -86,22 +75,38 @@ async def upload_file(file: UploadFile = File(...)):
|
|
| 86 |
"filename": file.filename
|
| 87 |
}
|
| 88 |
except Exception as e:
|
| 89 |
-
print(f"Error en subida: {e}")
|
| 90 |
return {"status": "error", "message": str(e)}
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
# --- INICIO COMBINADO ---
|
| 93 |
|
| 94 |
async def main():
|
| 95 |
-
|
| 96 |
-
print("Iniciando Bot de Telegram (Telethon)...")
|
| 97 |
await client.start(bot_token=BOT_TOKEN)
|
| 98 |
-
print("Bot en línea
|
| 99 |
|
| 100 |
-
|
| 101 |
-
config = uvicorn.Config(app_api, host="0.0.0.0", port=8080, log_level="info")
|
| 102 |
server = uvicorn.Server(config)
|
| 103 |
-
|
| 104 |
-
# Ejecutar ambos sin bloquearse
|
| 105 |
await server.serve()
|
| 106 |
|
| 107 |
if __name__ == '__main__':
|
|
|
|
| 3 |
from telethon import TelegramClient, events
|
| 4 |
from fastapi import FastAPI, UploadFile, File
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from fastapi.staticfiles import StaticFiles
|
| 7 |
+
from fastapi.responses import FileResponse
|
| 8 |
import uvicorn
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
|
|
|
|
| 16 |
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
|
| 17 |
CHANNEL_ID = int(os.getenv("TELEGRAM_CHANNEL_ID", "0"))
|
| 18 |
|
| 19 |
+
# Hugging Face usa el puerto 7860
|
| 20 |
+
PORT = int(os.getenv("PORT", "7860"))
|
| 21 |
+
|
| 22 |
if not os.path.exists("sessions"):
|
| 23 |
os.makedirs("sessions")
|
| 24 |
|
| 25 |
# 2. Inicializar Cliente de Telethon
|
|
|
|
| 26 |
client = TelegramClient('sessions/bot_session', API_ID, API_HASH)
|
| 27 |
|
| 28 |
# 3. Servidor API con FastAPI
|
|
|
|
| 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(file_id)
|
|
|
|
|
|
|
|
|
|
| 47 |
await client.forward_messages(event.chat_id, msg_id, CHANNEL_ID)
|
| 48 |
+
return
|
| 49 |
except Exception as e:
|
| 50 |
+
await event.respond("Lo siento, no pude encontrar ese archivo.")
|
|
|
|
| 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 ---
|
| 56 |
|
|
|
|
| 62 |
content = await file.read()
|
| 63 |
buffer.write(content)
|
| 64 |
|
|
|
|
|
|
|
| 65 |
sent_msg = await client.send_file(
|
| 66 |
CHANNEL_ID,
|
| 67 |
file_path,
|
| 68 |
caption=f"Archivo subido desde CodeByDante: {file.filename}"
|
| 69 |
)
|
|
|
|
|
|
|
| 70 |
os.remove(file_path)
|
| 71 |
return {
|
| 72 |
"status": "success",
|
|
|
|
| 75 |
"filename": file.filename
|
| 76 |
}
|
| 77 |
except Exception as e:
|
|
|
|
| 78 |
return {"status": "error", "message": str(e)}
|
| 79 |
|
| 80 |
+
# --- SERVIR FRONTEND (HUGGING FACE) ---
|
| 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):
|
| 86 |
+
print(f"Sirviendo frontend desde: {dist_path}")
|
| 87 |
+
app_api.mount("/assets", StaticFiles(directory=os.path.join(dist_path, "assets")), name="assets")
|
| 88 |
+
|
| 89 |
+
@app_api.get("/")
|
| 90 |
+
async def serve_index():
|
| 91 |
+
return FileResponse(os.path.join(dist_path, "index.html"))
|
| 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 |
# --- INICIO COMBINADO ---
|
| 102 |
|
| 103 |
async def main():
|
| 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__':
|
components/EditorToolbar.tsx
CHANGED
|
@@ -514,7 +514,7 @@ export const EditorToolbar: React.FC<EditorToolbarProps> = ({
|
|
| 514 |
}
|
| 515 |
};
|
| 516 |
|
| 517 |
-
xhr.open('POST', '
|
| 518 |
xhr.send(formData);
|
| 519 |
});
|
| 520 |
}
|
|
|
|
| 514 |
}
|
| 515 |
};
|
| 516 |
|
| 517 |
+
xhr.open('POST', '/upload', true);
|
| 518 |
xhr.send(formData);
|
| 519 |
});
|
| 520 |
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
telethon
|
| 2 |
+
fastapi
|
| 3 |
+
uvicorn
|
| 4 |
+
python-multipart
|
| 5 |
+
python-dotenv
|
| 6 |
+
aiofiles
|