Spaces:
Sleeping
Sleeping
Upload 27 files
Browse files- .dockerignore +8 -8
- .env +4 -0
- .gitattributes +36 -36
- Dockerfile +26 -26
- README.md +59 -59
- docker/.dockerignore +8 -8
- docker/Dockerfile +26 -26
- docker/requirements.txt +4 -4
- requirements.txt +4 -4
- scripts/login.py +59 -59
- sessions/userbot.session +0 -0
- src/__pycache__/bot.cpython-311.pyc +0 -0
- src/__pycache__/config.cpython-311.pyc +0 -0
- src/bot.py +60 -60
- src/config.py +13 -13
- src/plugins/__init__.py +11 -11
- src/plugins/__pycache__/__init__.cpython-311.pyc +0 -0
- src/plugins/__pycache__/channels.cpython-311.pyc +0 -0
- src/plugins/__pycache__/flow.cpython-311.pyc +0 -0
- src/plugins/__pycache__/general.cpython-311.pyc +0 -0
- src/plugins/channels.py +40 -40
- src/plugins/flow.py +217 -18
- src/plugins/general.py +2 -1
- src/web/__init__.py +1 -1
- src/web/server.py +97 -97
.dockerignore
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
__pycache__/
|
| 2 |
-
*.pyc
|
| 3 |
-
.env
|
| 4 |
-
.venv/
|
| 5 |
-
venv/
|
| 6 |
-
*.session
|
| 7 |
-
*.session-journal
|
| 8 |
-
.git/
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
.venv/
|
| 5 |
+
venv/
|
| 6 |
+
*.session
|
| 7 |
+
*.session-journal
|
| 8 |
+
.git/
|
.env
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
API_ID=2040
|
| 2 |
+
API_HASH=b18441a1ff607e10a989891a5462e627
|
| 3 |
+
SESSION_STRING=1AZWarzYBu2UC9TDMcvuVA2VJTQbWxbqNyuj61Z6h09NBOvqGK_l6BzdHOuCk_V2wARdhxxbHuck-eqlKa206JB8AZfSIWNQQPYET_5ZnZR9RYBDhrMzTFNh4_9027Lw4qHwx7rYgqLngq4B2FeRi697N2FzovcYpih6e3diBkS8cw6NBVV2ilU_WwmbsY2Omsh0eBMlEIVzNF-Eq97Sfzzi74Ab8DOMU66qDNR81kMfNec1Uixp0hx7a1oXkitg6DLf6d5begbyQqz7A9ktGX6j5QH0prVmIRoF3KvYIX8XkA50O4BUnoGEphMnwBWokAWhA1d2p2XQgt4KXXRj65vMkus3A3Ko=
|
| 4 |
+
PORT=7860
|
.gitattributes
CHANGED
|
@@ -1,36 +1,36 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
-
__pycache__/bot.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
__pycache__/bot.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
Dockerfile
CHANGED
|
@@ -1,26 +1,26 @@
|
|
| 1 |
-
FROM python:3.10-slim
|
| 2 |
-
|
| 3 |
-
# Evitar buffers en logs y habilitar salida limpia
|
| 4 |
-
ENV PYTHONUNBUFFERED=1 \
|
| 5 |
-
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
-
PORT=7860
|
| 7 |
-
|
| 8 |
-
WORKDIR /app
|
| 9 |
-
|
| 10 |
-
# Instalar dependencias del sistema si fueran necesarias
|
| 11 |
-
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 12 |
-
gcc \
|
| 13 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
-
|
| 15 |
-
# Copiar requirements e instalarlos
|
| 16 |
-
COPY requirements*.txt docker/requirements*.txt ./
|
| 17 |
-
RUN if [ -f requirements.txt ]; then pip install --no-cache-dir -r requirements.txt; else pip install --no-cache-dir -r docker/requirements.txt; fi
|
| 18 |
-
|
| 19 |
-
# Copiar el código del proyecto
|
| 20 |
-
COPY . .
|
| 21 |
-
|
| 22 |
-
# Puerto por defecto de Hugging Face Spaces
|
| 23 |
-
EXPOSE 7860
|
| 24 |
-
|
| 25 |
-
# Comando para arrancar el bot y el servidor fantasma
|
| 26 |
-
CMD ["python", "src/bot.py"]
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
# Evitar buffers en logs y habilitar salida limpia
|
| 4 |
+
ENV PYTHONUNBUFFERED=1 \
|
| 5 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
+
PORT=7860
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
# Instalar dependencias del sistema si fueran necesarias
|
| 11 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 12 |
+
gcc \
|
| 13 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
+
|
| 15 |
+
# Copiar requirements e instalarlos
|
| 16 |
+
COPY requirements*.txt docker/requirements*.txt ./
|
| 17 |
+
RUN if [ -f requirements.txt ]; then pip install --no-cache-dir -r requirements.txt; else pip install --no-cache-dir -r docker/requirements.txt; fi
|
| 18 |
+
|
| 19 |
+
# Copiar el código del proyecto
|
| 20 |
+
COPY . .
|
| 21 |
+
|
| 22 |
+
# Puerto por defecto de Hugging Face Spaces
|
| 23 |
+
EXPOSE 7860
|
| 24 |
+
|
| 25 |
+
# Comando para arrancar el bot y el servidor fantasma
|
| 26 |
+
CMD ["python", "src/bot.py"]
|
README.md
CHANGED
|
@@ -1,59 +1,59 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: TwistedStreamingBrody
|
| 3 |
-
emoji: 🎬
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: blue
|
| 6 |
-
sdk: docker
|
| 7 |
-
app_port: 7860
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
# 🎬 UserBot Películas (Telegram + Web Server Fantasma + Docker HF Space)
|
| 11 |
-
|
| 12 |
-
Este proyecto incluye un UserBot con **Telethon**, un servidor web fantasma con **Flask** para mantener vivo el servicio en **Hugging Face Spaces** o cualquier PaaS, y scripts listos para Windows (.bat).
|
| 13 |
-
|
| 14 |
-
---
|
| 15 |
-
|
| 16 |
-
## 📁 Archivos Creados
|
| 17 |
-
|
| 18 |
-
- [login.py](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/login.py): Script en Python que solicita tu `API_ID`, `API_HASH`, tu número de Telegram y el código de verificación por SMS/Telegram para generar un `SESSION_STRING` y guardarlo automáticamente en `.env`.
|
| 19 |
-
- [login.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/login.bat): Archivo ejecutable de Windows para instalar dependencias y abrir el asistente de inicio de sesión con un doble clic.
|
| 20 |
-
- [bot.py](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/bot.py): Ejecuta el UserBot y en paralelo un servidor web fantasma con Flask en el puerto configurado (`PORT`, por defecto `7860`). Responde a `.ping` y `.alive`.
|
| 21 |
-
- [start.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/start.bat): Archivo ejecutable para arrancar el bot en tu PC con Windows.
|
| 22 |
-
- [Dockerfile](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/Dockerfile): Configuración Docker lista para Hugging Face Spaces (SDK: Docker, puerto 7860).
|
| 23 |
-
- [.dockerignore](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/.dockerignore): Excluye archivos locales sensibles (`.env`, sesiones, git) al construir la imagen de Docker.
|
| 24 |
-
- [requirements.txt](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/requirements.txt): Dependencias necesarias (`telethon`, `flask`, `python-dotenv`, `gunicorn`).
|
| 25 |
-
|
| 26 |
-
---
|
| 27 |
-
|
| 28 |
-
## 🚀 Pasos de Uso en Windows (Local)
|
| 29 |
-
|
| 30 |
-
1. **Obtén tus credenciales de Telegram:**
|
| 31 |
-
- Ve a [my.telegram.org](https://my.telegram.org) e inicia sesión.
|
| 32 |
-
- Ve a **API development tools** y crea una app para obtener tu `API_ID` y `API_HASH`.
|
| 33 |
-
|
| 34 |
-
2. **Iniciar Sesión:**
|
| 35 |
-
- Haz doble clic en [login.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/login.bat).
|
| 36 |
-
- Ingresa tu `API_ID`, `API_HASH`, tu número con prefijo internacional (ej. `+54...`, `+34...`, `+52...`) y el código que te llegará a Telegram.
|
| 37 |
-
- Esto creará tu `.env` con la variable `SESSION_STRING`.
|
| 38 |
-
|
| 39 |
-
3. **Iniciar el Bot:**
|
| 40 |
-
- Haz doble clic en [start.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/start.bat).
|
| 41 |
-
- Abre tu navegador en `http://localhost:7860` para ver la página fantasma activa.
|
| 42 |
-
- En cualquier chat de Telegram, envía `.ping` o `.alive` para probar que tu UserBot responde.
|
| 43 |
-
|
| 44 |
-
---
|
| 45 |
-
|
| 46 |
-
## ☁️ Despliegue en Hugging Face Spaces (24/7)
|
| 47 |
-
|
| 48 |
-
1. Crea un nuevo **Space** en [Hugging Face](https://huggingface.co/spaces).
|
| 49 |
-
2. Elige el **Space SDK: Docker** (Blank / Dockerfile).
|
| 50 |
-
3. Sube todos los archivos del repositorio:
|
| 51 |
-
- `Dockerfile`
|
| 52 |
-
- `bot.py`
|
| 53 |
-
- `requirements.txt`
|
| 54 |
-
4. En la pestaña **Settings** de tu Space, ve a **Variables and secrets** y añade los siguientes **Secrets**:
|
| 55 |
-
- `API_ID`: Tu API ID
|
| 56 |
-
- `API_HASH`: Tu API Hash
|
| 57 |
-
- `SESSION_STRING`: El StringSession generado en el paso 2
|
| 58 |
-
- `PORT`: `7860`
|
| 59 |
-
5. El Space se compilará y se mantendrá en estado `Running` gracias al puerto web expuesto.
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: TwistedStreamingBrody
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# 🎬 UserBot Películas (Telegram + Web Server Fantasma + Docker HF Space)
|
| 11 |
+
|
| 12 |
+
Este proyecto incluye un UserBot con **Telethon**, un servidor web fantasma con **Flask** para mantener vivo el servicio en **Hugging Face Spaces** o cualquier PaaS, y scripts listos para Windows (.bat).
|
| 13 |
+
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## 📁 Archivos Creados
|
| 17 |
+
|
| 18 |
+
- [login.py](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/login.py): Script en Python que solicita tu `API_ID`, `API_HASH`, tu número de Telegram y el código de verificación por SMS/Telegram para generar un `SESSION_STRING` y guardarlo automáticamente en `.env`.
|
| 19 |
+
- [login.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/login.bat): Archivo ejecutable de Windows para instalar dependencias y abrir el asistente de inicio de sesión con un doble clic.
|
| 20 |
+
- [bot.py](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/bot.py): Ejecuta el UserBot y en paralelo un servidor web fantasma con Flask en el puerto configurado (`PORT`, por defecto `7860`). Responde a `.ping` y `.alive`.
|
| 21 |
+
- [start.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/start.bat): Archivo ejecutable para arrancar el bot en tu PC con Windows.
|
| 22 |
+
- [Dockerfile](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/Dockerfile): Configuración Docker lista para Hugging Face Spaces (SDK: Docker, puerto 7860).
|
| 23 |
+
- [.dockerignore](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/.dockerignore): Excluye archivos locales sensibles (`.env`, sesiones, git) al construir la imagen de Docker.
|
| 24 |
+
- [requirements.txt](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/requirements.txt): Dependencias necesarias (`telethon`, `flask`, `python-dotenv`, `gunicorn`).
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## 🚀 Pasos de Uso en Windows (Local)
|
| 29 |
+
|
| 30 |
+
1. **Obtén tus credenciales de Telegram:**
|
| 31 |
+
- Ve a [my.telegram.org](https://my.telegram.org) e inicia sesión.
|
| 32 |
+
- Ve a **API development tools** y crea una app para obtener tu `API_ID` y `API_HASH`.
|
| 33 |
+
|
| 34 |
+
2. **Iniciar Sesión:**
|
| 35 |
+
- Haz doble clic en [login.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/login.bat).
|
| 36 |
+
- Ingresa tu `API_ID`, `API_HASH`, tu número con prefijo internacional (ej. `+54...`, `+34...`, `+52...`) y el código que te llegará a Telegram.
|
| 37 |
+
- Esto creará tu `.env` con la variable `SESSION_STRING`.
|
| 38 |
+
|
| 39 |
+
3. **Iniciar el Bot:**
|
| 40 |
+
- Haz doble clic en [start.bat](file:///c:/Users/Gonzalo/Desktop/userbotpeliculas/start.bat).
|
| 41 |
+
- Abre tu navegador en `http://localhost:7860` para ver la página fantasma activa.
|
| 42 |
+
- En cualquier chat de Telegram, envía `.ping` o `.alive` para probar que tu UserBot responde.
|
| 43 |
+
|
| 44 |
+
---
|
| 45 |
+
|
| 46 |
+
## ☁️ Despliegue en Hugging Face Spaces (24/7)
|
| 47 |
+
|
| 48 |
+
1. Crea un nuevo **Space** en [Hugging Face](https://huggingface.co/spaces).
|
| 49 |
+
2. Elige el **Space SDK: Docker** (Blank / Dockerfile).
|
| 50 |
+
3. Sube todos los archivos del repositorio:
|
| 51 |
+
- `Dockerfile`
|
| 52 |
+
- `bot.py`
|
| 53 |
+
- `requirements.txt`
|
| 54 |
+
4. En la pestaña **Settings** de tu Space, ve a **Variables and secrets** y añade los siguientes **Secrets**:
|
| 55 |
+
- `API_ID`: Tu API ID
|
| 56 |
+
- `API_HASH`: Tu API Hash
|
| 57 |
+
- `SESSION_STRING`: El StringSession generado en el paso 2
|
| 58 |
+
- `PORT`: `7860`
|
| 59 |
+
5. El Space se compilará y se mantendrá en estado `Running` gracias al puerto web expuesto.
|
docker/.dockerignore
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
__pycache__/
|
| 2 |
-
*.pyc
|
| 3 |
-
.env
|
| 4 |
-
.venv/
|
| 5 |
-
venv/
|
| 6 |
-
*.session
|
| 7 |
-
*.session-journal
|
| 8 |
-
.git/
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.env
|
| 4 |
+
.venv/
|
| 5 |
+
venv/
|
| 6 |
+
*.session
|
| 7 |
+
*.session-journal
|
| 8 |
+
.git/
|
docker/Dockerfile
CHANGED
|
@@ -1,26 +1,26 @@
|
|
| 1 |
-
FROM python:3.10-slim
|
| 2 |
-
|
| 3 |
-
# Evitar buffers en logs y habilitar salida limpia
|
| 4 |
-
ENV PYTHONUNBUFFERED=1 \
|
| 5 |
-
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
-
PORT=7860
|
| 7 |
-
|
| 8 |
-
WORKDIR /app
|
| 9 |
-
|
| 10 |
-
# Instalar dependencias del sistema si fueran necesarias
|
| 11 |
-
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 12 |
-
gcc \
|
| 13 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
-
|
| 15 |
-
# Copiar requirements e instalarlos
|
| 16 |
-
COPY docker/requirements.txt requirements.txt
|
| 17 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 18 |
-
|
| 19 |
-
# Copiar el código del proyecto
|
| 20 |
-
COPY . .
|
| 21 |
-
|
| 22 |
-
# Puerto por defecto de Hugging Face Spaces
|
| 23 |
-
EXPOSE 7860
|
| 24 |
-
|
| 25 |
-
# Comando para arrancar el bot y el servidor fantasma
|
| 26 |
-
CMD ["python", "src/bot.py"]
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
# Evitar buffers en logs y habilitar salida limpia
|
| 4 |
+
ENV PYTHONUNBUFFERED=1 \
|
| 5 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
+
PORT=7860
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
# Instalar dependencias del sistema si fueran necesarias
|
| 11 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 12 |
+
gcc \
|
| 13 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
+
|
| 15 |
+
# Copiar requirements e instalarlos
|
| 16 |
+
COPY docker/requirements.txt requirements.txt
|
| 17 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 18 |
+
|
| 19 |
+
# Copiar el código del proyecto
|
| 20 |
+
COPY . .
|
| 21 |
+
|
| 22 |
+
# Puerto por defecto de Hugging Face Spaces
|
| 23 |
+
EXPOSE 7860
|
| 24 |
+
|
| 25 |
+
# Comando para arrancar el bot y el servidor fantasma
|
| 26 |
+
CMD ["python", "src/bot.py"]
|
docker/requirements.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
telethon>=1.36.0
|
| 2 |
-
flask>=3.0.0
|
| 3 |
-
python-dotenv>=1.0.0
|
| 4 |
-
gunicorn>=22.0.0
|
|
|
|
| 1 |
+
telethon>=1.36.0
|
| 2 |
+
flask>=3.0.0
|
| 3 |
+
python-dotenv>=1.0.0
|
| 4 |
+
gunicorn>=22.0.0
|
requirements.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
telethon>=1.36.0
|
| 2 |
-
flask>=3.0.0
|
| 3 |
-
python-dotenv>=1.0.0
|
| 4 |
-
gunicorn>=22.0.0
|
|
|
|
| 1 |
+
telethon>=1.36.0
|
| 2 |
+
flask>=3.0.0
|
| 3 |
+
python-dotenv>=1.0.0
|
| 4 |
+
gunicorn>=22.0.0
|
scripts/login.py
CHANGED
|
@@ -1,59 +1,59 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sys
|
| 3 |
-
from telethon.sync import TelegramClient
|
| 4 |
-
from telethon.sessions import StringSession
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
|
| 7 |
-
load_dotenv()
|
| 8 |
-
|
| 9 |
-
# Credenciales de API de Telegram (App Oficial para generación de sesión directa)
|
| 10 |
-
DEFAULT_API_ID = 2040
|
| 11 |
-
DEFAULT_API_HASH = "b18441a1ff607e10a989891a5462e627"
|
| 12 |
-
|
| 13 |
-
def main():
|
| 14 |
-
print("=" * 55)
|
| 15 |
-
print(" INICIO DE SESIÓN TELEGRAM (USERBOT)")
|
| 16 |
-
print("=" * 55)
|
| 17 |
-
|
| 18 |
-
api_id = int(os.getenv("API_ID") or DEFAULT_API_ID)
|
| 19 |
-
api_hash = os.getenv("API_HASH") or DEFAULT_API_HASH
|
| 20 |
-
|
| 21 |
-
phone = input("\n👉 Ingresa tu número de teléfono (ejemplo: +51963264225): ").strip()
|
| 22 |
-
if not phone:
|
| 23 |
-
print("[ERROR] El número de teléfono no puede estar vacío.")
|
| 24 |
-
sys.exit(1)
|
| 25 |
-
|
| 26 |
-
print("\nConectando con Telegram...")
|
| 27 |
-
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 28 |
-
sessions_dir = os.path.join(base_dir, "sessions")
|
| 29 |
-
os.makedirs(sessions_dir, exist_ok=True)
|
| 30 |
-
session_file_path = os.path.join(sessions_dir, "userbot")
|
| 31 |
-
|
| 32 |
-
# Iniciar con archivo .session físico
|
| 33 |
-
client = TelegramClient(session_file_path, api_id, api_hash)
|
| 34 |
-
client.start(phone=phone)
|
| 35 |
-
|
| 36 |
-
# También obtener el StringSession para cuando quieras subirlo a HF Space
|
| 37 |
-
from telethon.sessions import StringSession
|
| 38 |
-
temp_client = TelegramClient(StringSession(), api_id, api_hash)
|
| 39 |
-
temp_client.session.set_dc(client.session.dc_id, client.session.server_address, client.session.port)
|
| 40 |
-
temp_client.session.auth_key = client.session.auth_key
|
| 41 |
-
session_str = temp_client.session.save()
|
| 42 |
-
client.disconnect()
|
| 43 |
-
|
| 44 |
-
print("\n" + "=" * 55)
|
| 45 |
-
print("¡AUTENTICACIÓN EXITOSA!")
|
| 46 |
-
print("=" * 55)
|
| 47 |
-
print(f"✅ Archivo de sesión creado en: sessions/userbot.session")
|
| 48 |
-
print(f"✅ SESSION_STRING para HF Spaces:\n{session_str}")
|
| 49 |
-
print("=" * 55)
|
| 50 |
-
|
| 51 |
-
# Guardar en archivo .env automáticamente en la raíz
|
| 52 |
-
env_path = os.path.join(base_dir, ".env")
|
| 53 |
-
env_content = f"API_ID={api_id}\nAPI_HASH={api_hash}\nSESSION_STRING={session_str}\nPORT=7860\n"
|
| 54 |
-
with open(env_path, "w", encoding="utf-8") as f:
|
| 55 |
-
f.write(env_content)
|
| 56 |
-
print(f"\n[OK] Configuración guardada en '.env'")
|
| 57 |
-
|
| 58 |
-
if __name__ == "__main__":
|
| 59 |
-
main()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from telethon.sync import TelegramClient
|
| 4 |
+
from telethon.sessions import StringSession
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
# Credenciales de API de Telegram (App Oficial para generación de sesión directa)
|
| 10 |
+
DEFAULT_API_ID = 2040
|
| 11 |
+
DEFAULT_API_HASH = "b18441a1ff607e10a989891a5462e627"
|
| 12 |
+
|
| 13 |
+
def main():
|
| 14 |
+
print("=" * 55)
|
| 15 |
+
print(" INICIO DE SESIÓN TELEGRAM (USERBOT)")
|
| 16 |
+
print("=" * 55)
|
| 17 |
+
|
| 18 |
+
api_id = int(os.getenv("API_ID") or DEFAULT_API_ID)
|
| 19 |
+
api_hash = os.getenv("API_HASH") or DEFAULT_API_HASH
|
| 20 |
+
|
| 21 |
+
phone = input("\n👉 Ingresa tu número de teléfono (ejemplo: +51963264225): ").strip()
|
| 22 |
+
if not phone:
|
| 23 |
+
print("[ERROR] El número de teléfono no puede estar vacío.")
|
| 24 |
+
sys.exit(1)
|
| 25 |
+
|
| 26 |
+
print("\nConectando con Telegram...")
|
| 27 |
+
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 28 |
+
sessions_dir = os.path.join(base_dir, "sessions")
|
| 29 |
+
os.makedirs(sessions_dir, exist_ok=True)
|
| 30 |
+
session_file_path = os.path.join(sessions_dir, "userbot")
|
| 31 |
+
|
| 32 |
+
# Iniciar con archivo .session físico
|
| 33 |
+
client = TelegramClient(session_file_path, api_id, api_hash)
|
| 34 |
+
client.start(phone=phone)
|
| 35 |
+
|
| 36 |
+
# También obtener el StringSession para cuando quieras subirlo a HF Space
|
| 37 |
+
from telethon.sessions import StringSession
|
| 38 |
+
temp_client = TelegramClient(StringSession(), api_id, api_hash)
|
| 39 |
+
temp_client.session.set_dc(client.session.dc_id, client.session.server_address, client.session.port)
|
| 40 |
+
temp_client.session.auth_key = client.session.auth_key
|
| 41 |
+
session_str = temp_client.session.save()
|
| 42 |
+
client.disconnect()
|
| 43 |
+
|
| 44 |
+
print("\n" + "=" * 55)
|
| 45 |
+
print("¡AUTENTICACIÓN EXITOSA!")
|
| 46 |
+
print("=" * 55)
|
| 47 |
+
print(f"✅ Archivo de sesión creado en: sessions/userbot.session")
|
| 48 |
+
print(f"✅ SESSION_STRING para HF Spaces:\n{session_str}")
|
| 49 |
+
print("=" * 55)
|
| 50 |
+
|
| 51 |
+
# Guardar en archivo .env automáticamente en la raíz
|
| 52 |
+
env_path = os.path.join(base_dir, ".env")
|
| 53 |
+
env_content = f"API_ID={api_id}\nAPI_HASH={api_hash}\nSESSION_STRING={session_str}\nPORT=7860\n"
|
| 54 |
+
with open(env_path, "w", encoding="utf-8") as f:
|
| 55 |
+
f.write(env_content)
|
| 56 |
+
print(f"\n[OK] Configuración guardada en '.env'")
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
main()
|
sessions/userbot.session
ADDED
|
Binary file (28.7 kB). View file
|
|
|
src/__pycache__/bot.cpython-311.pyc
ADDED
|
Binary file (4.04 kB). View file
|
|
|
src/__pycache__/config.cpython-311.pyc
ADDED
|
Binary file (784 Bytes). View file
|
|
|
src/bot.py
CHANGED
|
@@ -1,60 +1,60 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sys
|
| 3 |
-
import threading
|
| 4 |
-
import asyncio
|
| 5 |
-
|
| 6 |
-
# Asegurar que el directorio src esté en sys.path
|
| 7 |
-
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 8 |
-
SRC_DIR = os.path.join(BASE_DIR, "src")
|
| 9 |
-
if SRC_DIR not in sys.path:
|
| 10 |
-
sys.path.insert(0, SRC_DIR)
|
| 11 |
-
|
| 12 |
-
from telethon import TelegramClient
|
| 13 |
-
from telethon.sessions import StringSession
|
| 14 |
-
|
| 15 |
-
from config import API_ID, API_HASH, SESSION_STRING, PORT
|
| 16 |
-
from web.server import start_server, bot_status
|
| 17 |
-
from plugins import load_all_plugins
|
| 18 |
-
|
| 19 |
-
SESSION_FILE = os.path.join(BASE_DIR, "sessions", "userbot.session")
|
| 20 |
-
|
| 21 |
-
async def start_userbot():
|
| 22 |
-
# 1. Prioridad: Archivo .session local si existe
|
| 23 |
-
if os.path.exists(SESSION_FILE):
|
| 24 |
-
session_target = os.path.join(BASE_DIR, "sessions", "userbot")
|
| 25 |
-
print(f"[*] Usando archivo de sesión: {SESSION_FILE}")
|
| 26 |
-
client = TelegramClient(session_target, API_ID, API_HASH)
|
| 27 |
-
# 2. StringSession para Hugging Face Spaces o variables de entorno
|
| 28 |
-
elif SESSION_STRING:
|
| 29 |
-
print("[*] Usando SESSION_STRING desde entorno.")
|
| 30 |
-
client = TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH)
|
| 31 |
-
else:
|
| 32 |
-
bot_status["status"] = "ERROR: No hay archivo en sessions/userbot.session ni SESSION_STRING."
|
| 33 |
-
print("[ERROR] No se encontró sessions/userbot.session ni variable SESSION_STRING. Ejecuta scripts/login.bat primero.")
|
| 34 |
-
return
|
| 35 |
-
|
| 36 |
-
# Cargar todos los comandos modulares desde la carpeta plugins/
|
| 37 |
-
load_all_plugins(client)
|
| 38 |
-
|
| 39 |
-
try:
|
| 40 |
-
await client.start()
|
| 41 |
-
me = await client.get_me()
|
| 42 |
-
user_name = f"@{me.username}" if me.username else f"{me.first_name} ({me.id})"
|
| 43 |
-
bot_status["status"] = "Conectado y Escuchando"
|
| 44 |
-
bot_status["user"] = user_name
|
| 45 |
-
print(f"[OK] UserBot conectado exitosamente como: {user_name}")
|
| 46 |
-
await client.run_until_disconnected()
|
| 47 |
-
except Exception as e:
|
| 48 |
-
bot_status["status"] = f"Error: {e}"
|
| 49 |
-
print(f"[ERROR] Telethon: {e}")
|
| 50 |
-
|
| 51 |
-
def main():
|
| 52 |
-
print(f"[*] Iniciando servidor web fantasma en el puerto {PORT}...")
|
| 53 |
-
web_thread = threading.Thread(target=start_server, args=(PORT,), daemon=True)
|
| 54 |
-
web_thread.start()
|
| 55 |
-
|
| 56 |
-
print("[*] Iniciando Telegram UserBot...")
|
| 57 |
-
asyncio.run(start_userbot())
|
| 58 |
-
|
| 59 |
-
if __name__ == "__main__":
|
| 60 |
-
main()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import threading
|
| 4 |
+
import asyncio
|
| 5 |
+
|
| 6 |
+
# Asegurar que el directorio src esté en sys.path
|
| 7 |
+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 8 |
+
SRC_DIR = os.path.join(BASE_DIR, "src")
|
| 9 |
+
if SRC_DIR not in sys.path:
|
| 10 |
+
sys.path.insert(0, SRC_DIR)
|
| 11 |
+
|
| 12 |
+
from telethon import TelegramClient
|
| 13 |
+
from telethon.sessions import StringSession
|
| 14 |
+
|
| 15 |
+
from config import API_ID, API_HASH, SESSION_STRING, PORT
|
| 16 |
+
from web.server import start_server, bot_status
|
| 17 |
+
from plugins import load_all_plugins
|
| 18 |
+
|
| 19 |
+
SESSION_FILE = os.path.join(BASE_DIR, "sessions", "userbot.session")
|
| 20 |
+
|
| 21 |
+
async def start_userbot():
|
| 22 |
+
# 1. Prioridad: Archivo .session local si existe
|
| 23 |
+
if os.path.exists(SESSION_FILE):
|
| 24 |
+
session_target = os.path.join(BASE_DIR, "sessions", "userbot")
|
| 25 |
+
print(f"[*] Usando archivo de sesión: {SESSION_FILE}")
|
| 26 |
+
client = TelegramClient(session_target, API_ID, API_HASH)
|
| 27 |
+
# 2. StringSession para Hugging Face Spaces o variables de entorno
|
| 28 |
+
elif SESSION_STRING:
|
| 29 |
+
print("[*] Usando SESSION_STRING desde entorno.")
|
| 30 |
+
client = TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH)
|
| 31 |
+
else:
|
| 32 |
+
bot_status["status"] = "ERROR: No hay archivo en sessions/userbot.session ni SESSION_STRING."
|
| 33 |
+
print("[ERROR] No se encontró sessions/userbot.session ni variable SESSION_STRING. Ejecuta scripts/login.bat primero.")
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
# Cargar todos los comandos modulares desde la carpeta plugins/
|
| 37 |
+
load_all_plugins(client)
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
await client.start()
|
| 41 |
+
me = await client.get_me()
|
| 42 |
+
user_name = f"@{me.username}" if me.username else f"{me.first_name} ({me.id})"
|
| 43 |
+
bot_status["status"] = "Conectado y Escuchando"
|
| 44 |
+
bot_status["user"] = user_name
|
| 45 |
+
print(f"[OK] UserBot conectado exitosamente como: {user_name}")
|
| 46 |
+
await client.run_until_disconnected()
|
| 47 |
+
except Exception as e:
|
| 48 |
+
bot_status["status"] = f"Error: {e}"
|
| 49 |
+
print(f"[ERROR] Telethon: {e}")
|
| 50 |
+
|
| 51 |
+
def main():
|
| 52 |
+
print(f"[*] Iniciando servidor web fantasma en el puerto {PORT}...")
|
| 53 |
+
web_thread = threading.Thread(target=start_server, args=(PORT,), daemon=True)
|
| 54 |
+
web_thread.start()
|
| 55 |
+
|
| 56 |
+
print("[*] Iniciando Telegram UserBot...")
|
| 57 |
+
asyncio.run(start_userbot())
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
main()
|
src/config.py
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from dotenv import load_dotenv
|
| 3 |
-
|
| 4 |
-
load_dotenv()
|
| 5 |
-
|
| 6 |
-
# Credenciales por defecto (Telegram Oficial) o leídas desde .env / Secrets
|
| 7 |
-
API_ID = int(os.getenv("API_ID", 2040))
|
| 8 |
-
API_HASH = os.getenv("API_HASH", "b18441a1ff607e10a989891a5462e627")
|
| 9 |
-
SESSION_STRING = os.getenv("SESSION_STRING", "")
|
| 10 |
-
PORT = int(os.getenv("PORT", 7860))
|
| 11 |
-
|
| 12 |
-
# Enlace del canal destino para el flujo
|
| 13 |
-
TARGET_CHANNEL_LINK = os.getenv("TARGET_CHANNEL_LINK", "https://t.me/+IKNrGXMIt_MxMzg5")
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
|
| 4 |
+
load_dotenv()
|
| 5 |
+
|
| 6 |
+
# Credenciales por defecto (Telegram Oficial) o leídas desde .env / Secrets
|
| 7 |
+
API_ID = int(os.getenv("API_ID", 2040))
|
| 8 |
+
API_HASH = os.getenv("API_HASH", "b18441a1ff607e10a989891a5462e627")
|
| 9 |
+
SESSION_STRING = os.getenv("SESSION_STRING", "")
|
| 10 |
+
PORT = int(os.getenv("PORT", 7860))
|
| 11 |
+
|
| 12 |
+
# Enlace del canal destino para el flujo
|
| 13 |
+
TARGET_CHANNEL_LINK = os.getenv("TARGET_CHANNEL_LINK", "https://t.me/+IKNrGXMIt_MxMzg5")
|
src/plugins/__init__.py
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
-
from plugins.channels import register_channels_handlers
|
| 2 |
-
from plugins.general import register_general_handlers
|
| 3 |
-
from plugins.flow import register_flow_handlers
|
| 4 |
-
|
| 5 |
-
def load_all_plugins(client):
|
| 6 |
-
"""
|
| 7 |
-
Carga todos los módulos y comandos en el cliente de Telethon.
|
| 8 |
-
"""
|
| 9 |
-
register_general_handlers(client)
|
| 10 |
-
register_channels_handlers(client)
|
| 11 |
-
register_flow_handlers(client)
|
|
|
|
| 1 |
+
from plugins.channels import register_channels_handlers
|
| 2 |
+
from plugins.general import register_general_handlers
|
| 3 |
+
from plugins.flow import register_flow_handlers
|
| 4 |
+
|
| 5 |
+
def load_all_plugins(client):
|
| 6 |
+
"""
|
| 7 |
+
Carga todos los módulos y comandos en el cliente de Telethon.
|
| 8 |
+
"""
|
| 9 |
+
register_general_handlers(client)
|
| 10 |
+
register_channels_handlers(client)
|
| 11 |
+
register_flow_handlers(client)
|
src/plugins/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (775 Bytes). View file
|
|
|
src/plugins/__pycache__/channels.cpython-311.pyc
ADDED
|
Binary file (2.7 kB). View file
|
|
|
src/plugins/__pycache__/flow.cpython-311.pyc
ADDED
|
Binary file (31.6 kB). View file
|
|
|
src/plugins/__pycache__/general.cpython-311.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
src/plugins/channels.py
CHANGED
|
@@ -1,40 +1,40 @@
|
|
| 1 |
-
from telethon import events
|
| 2 |
-
from telethon.tl.functions.channels import CreateChannelRequest
|
| 3 |
-
from telethon.tl.functions.messages import ExportChatInviteRequest
|
| 4 |
-
|
| 5 |
-
def register_channels_handlers(client):
|
| 6 |
-
"""
|
| 7 |
-
Registra comandos relacionados a creación y gestión de canales.
|
| 8 |
-
"""
|
| 9 |
-
@client.on(events.NewMessage(chats='me', pattern=r"(?i)^/crear_canal(?:\s+(.+))?$"))
|
| 10 |
-
async def crear_canal_handler(event):
|
| 11 |
-
canal_nombre = event.pattern_match.group(1)
|
| 12 |
-
if not canal_nombre or not canal_nombre.strip():
|
| 13 |
-
await event.reply("⚠️ Debes indicar el nombre del canal.\nEjemplo: `/crear_canal Mi Canal Pelis`")
|
| 14 |
-
return
|
| 15 |
-
|
| 16 |
-
canal_nombre = canal_nombre.strip()
|
| 17 |
-
status_msg = await event.reply(f"⏳ Creando canal privado: **{canal_nombre}**...")
|
| 18 |
-
|
| 19 |
-
try:
|
| 20 |
-
# Crear el canal privado
|
| 21 |
-
result = await client(CreateChannelRequest(
|
| 22 |
-
title=canal_nombre,
|
| 23 |
-
about="Canal creado por UserBot Películas",
|
| 24 |
-
megagroup=False,
|
| 25 |
-
broadcast=True
|
| 26 |
-
))
|
| 27 |
-
|
| 28 |
-
created_chat = result.chats[0]
|
| 29 |
-
|
| 30 |
-
# Exportar enlace de invitación privado
|
| 31 |
-
invite = await client(ExportChatInviteRequest(peer=created_chat))
|
| 32 |
-
invite_link = invite.link
|
| 33 |
-
|
| 34 |
-
await status_msg.edit(
|
| 35 |
-
f"✅ **Canal creado con éxito:**\n"
|
| 36 |
-
f"📌 **Nombre:** {canal_nombre}\n"
|
| 37 |
-
f"🔗 **Enlace:** {invite_link}"
|
| 38 |
-
)
|
| 39 |
-
except Exception as e:
|
| 40 |
-
await status_msg.edit(f"❌ Error al crear el canal: `{e}`")
|
|
|
|
| 1 |
+
from telethon import events
|
| 2 |
+
from telethon.tl.functions.channels import CreateChannelRequest
|
| 3 |
+
from telethon.tl.functions.messages import ExportChatInviteRequest
|
| 4 |
+
|
| 5 |
+
def register_channels_handlers(client):
|
| 6 |
+
"""
|
| 7 |
+
Registra comandos relacionados a creación y gestión de canales.
|
| 8 |
+
"""
|
| 9 |
+
@client.on(events.NewMessage(chats='me', pattern=r"(?i)^/crear_canal(?:\s+(.+))?$"))
|
| 10 |
+
async def crear_canal_handler(event):
|
| 11 |
+
canal_nombre = event.pattern_match.group(1)
|
| 12 |
+
if not canal_nombre or not canal_nombre.strip():
|
| 13 |
+
await event.reply("⚠️ Debes indicar el nombre del canal.\nEjemplo: `/crear_canal Mi Canal Pelis`")
|
| 14 |
+
return
|
| 15 |
+
|
| 16 |
+
canal_nombre = canal_nombre.strip()
|
| 17 |
+
status_msg = await event.reply(f"⏳ Creando canal privado: **{canal_nombre}**...")
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
# Crear el canal privado
|
| 21 |
+
result = await client(CreateChannelRequest(
|
| 22 |
+
title=canal_nombre,
|
| 23 |
+
about="Canal creado por UserBot Películas",
|
| 24 |
+
megagroup=False,
|
| 25 |
+
broadcast=True
|
| 26 |
+
))
|
| 27 |
+
|
| 28 |
+
created_chat = result.chats[0]
|
| 29 |
+
|
| 30 |
+
# Exportar enlace de invitación privado
|
| 31 |
+
invite = await client(ExportChatInviteRequest(peer=created_chat))
|
| 32 |
+
invite_link = invite.link
|
| 33 |
+
|
| 34 |
+
await status_msg.edit(
|
| 35 |
+
f"✅ **Canal creado con éxito:**\n"
|
| 36 |
+
f"📌 **Nombre:** {canal_nombre}\n"
|
| 37 |
+
f"🔗 **Enlace:** {invite_link}"
|
| 38 |
+
)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
await status_msg.edit(f"❌ Error al crear el canal: `{e}`")
|
src/plugins/flow.py
CHANGED
|
@@ -1,7 +1,16 @@
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
from telethon import events
|
| 4 |
-
from telethon.tl.types import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from telethon.tl.functions.messages import ImportChatInviteRequest, CheckChatInviteRequest
|
| 6 |
from telethon.errors import (
|
| 7 |
UserAlreadyParticipantError,
|
|
@@ -11,7 +20,7 @@ from config import TARGET_CHANNEL_LINK
|
|
| 11 |
|
| 12 |
# Estado del modo escaneo
|
| 13 |
flow_state = {
|
| 14 |
-
"active":
|
| 15 |
"is_processing": False
|
| 16 |
}
|
| 17 |
|
|
@@ -98,6 +107,127 @@ def register_flow_handlers(client):
|
|
| 98 |
flow_state["active"] = False
|
| 99 |
await event.reply("🔴 **Modo Flujo DESACTIVADO**.\nEl bot ya no procesará mensajes reenviados.")
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
@client.on(events.NewMessage(chats='me'))
|
| 102 |
async def process_forwarded_content(event):
|
| 103 |
# Ignorar comandos
|
|
@@ -124,30 +254,61 @@ def register_flow_handlers(client):
|
|
| 124 |
source_peer = fwd_header.from_id
|
| 125 |
source_entity = await client.get_entity(source_peer)
|
| 126 |
|
| 127 |
-
# Verificar si es un canal
|
| 128 |
-
|
| 129 |
-
if not
|
| 130 |
-
await status_msg.edit("⚠️ **Solo se admiten
|
| 131 |
return
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
# 2. Verificar si el
|
| 137 |
if getattr(source_entity, 'noforwards', False):
|
| 138 |
-
await status_msg.edit(f"⛔ **
|
| 139 |
return
|
| 140 |
|
| 141 |
# 3. Conectar con el canal destino
|
| 142 |
await status_msg.edit(f"🎯 Conectando con el canal destino para sincronizar `{source_title}`...")
|
| 143 |
target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
|
| 144 |
|
| 145 |
-
# 4. Leer todos los videos e imágenes del
|
| 146 |
await status_msg.edit(f"📥 Leyendo contenidos de `{source_title}`...")
|
| 147 |
source_items = []
|
| 148 |
source_fps = set()
|
| 149 |
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
is_photo = bool(message.photo)
|
| 152 |
is_video = bool(message.video)
|
| 153 |
is_img_doc = False
|
|
@@ -214,7 +375,7 @@ def register_flow_handlers(client):
|
|
| 214 |
prev_msg = all_recent_target_msgs[max_idx + lookback]
|
| 215 |
# Si es foto o texto y contiene parte del título o es la portada previa
|
| 216 |
prev_txt = (prev_msg.message or "").lower()
|
| 217 |
-
if (clean_title in prev_txt) or (prev_msg.photo and prev_txt.startswith("🎬")):
|
| 218 |
if prev_msg.id not in target_series_ids:
|
| 219 |
target_series_msgs.append(prev_msg)
|
| 220 |
target_series_ids.add(prev_msg.id)
|
|
@@ -243,16 +404,23 @@ def register_flow_handlers(client):
|
|
| 243 |
)
|
| 244 |
# Reenviar los mensajes que ya estaban en el canal destino (sin etiqueta de reenvío)
|
| 245 |
sent_count = 0
|
|
|
|
| 246 |
for old_msg in target_series_msgs:
|
| 247 |
try:
|
| 248 |
if old_msg.media:
|
| 249 |
-
await client.send_file(
|
| 250 |
target_entity,
|
| 251 |
file=old_msg.media,
|
| 252 |
caption=old_msg.message or ""
|
| 253 |
)
|
| 254 |
elif old_msg.message:
|
| 255 |
-
await client.send_message(target_entity, old_msg.message)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
sent_count += 1
|
| 257 |
await asyncio.sleep(0.2)
|
| 258 |
except Exception as re_err:
|
|
@@ -263,17 +431,33 @@ def register_flow_handlers(client):
|
|
| 263 |
await status_msg.edit(f"➕ Agregando los **{len(new_missing_items)}** videos/imágenes nuevos...")
|
| 264 |
for msg_item, fp in new_missing_items:
|
| 265 |
try:
|
| 266 |
-
await client.send_file(
|
| 267 |
target_entity,
|
| 268 |
file=msg_item.media,
|
| 269 |
caption=msg_item.message or ""
|
| 270 |
)
|
|
|
|
|
|
|
|
|
|
| 271 |
sent_count += 1
|
| 272 |
await asyncio.sleep(0.2)
|
| 273 |
except Exception as new_err:
|
| 274 |
print(f"[Error enviando nuevo]: {new_err}")
|
| 275 |
await asyncio.sleep(1)
|
| 276 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
# Eliminar los mensajes viejos que quedaron arriba desactualizados
|
| 278 |
await status_msg.edit(f"🗑️ Eliminando los {len(old_msg_ids_to_delete)} mensajes anteriores desactualizados...")
|
| 279 |
try:
|
|
@@ -308,15 +492,30 @@ def register_flow_handlers(client):
|
|
| 308 |
else:
|
| 309 |
cover_to_send = None
|
| 310 |
|
|
|
|
|
|
|
| 311 |
if cover_to_send:
|
| 312 |
-
await client.send_file(target_entity, file=cover_to_send, caption=header_pattern)
|
| 313 |
if cover_to_send == avatar_path:
|
| 314 |
try:
|
| 315 |
os.remove(avatar_path)
|
| 316 |
except Exception:
|
| 317 |
pass
|
| 318 |
else:
|
| 319 |
-
await client.send_message(target_entity, header_pattern)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
sent_count = 0
|
| 322 |
for msg_item, fp in source_items:
|
|
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
from telethon import events
|
| 4 |
+
from telethon.tl.types import (
|
| 5 |
+
Channel,
|
| 6 |
+
Chat,
|
| 7 |
+
DocumentAttributeVideo,
|
| 8 |
+
MessageService,
|
| 9 |
+
MessageActionPinMessage,
|
| 10 |
+
MessageActionChatJoinedByLink,
|
| 11 |
+
MessageActionChatAddUser
|
| 12 |
+
)
|
| 13 |
+
from telethon.tl.functions.messages import GetForumTopicsByIDRequest
|
| 14 |
from telethon.tl.functions.messages import ImportChatInviteRequest, CheckChatInviteRequest
|
| 15 |
from telethon.errors import (
|
| 16 |
UserAlreadyParticipantError,
|
|
|
|
| 20 |
|
| 21 |
# Estado del modo escaneo
|
| 22 |
flow_state = {
|
| 23 |
+
"active": True,
|
| 24 |
"is_processing": False
|
| 25 |
}
|
| 26 |
|
|
|
|
| 107 |
flow_state["active"] = False
|
| 108 |
await event.reply("🔴 **Modo Flujo DESACTIVADO**.\nEl bot ya no procesará mensajes reenviados.")
|
| 109 |
|
| 110 |
+
@client.on(events.NewMessage(chats='me', pattern=r"(?i)^/fijar$"))
|
| 111 |
+
async def fijar_portadas_handler(event):
|
| 112 |
+
"""
|
| 113 |
+
Desfija todos los mensajes del canal destino y vuelve a fijar
|
| 114 |
+
exclusivamente las portadas con título (portada principal y temporadas).
|
| 115 |
+
"""
|
| 116 |
+
status_msg = await event.reply("🔄 **Iniciando proceso: Desfijando todo el canal y refijando portadas...**")
|
| 117 |
+
try:
|
| 118 |
+
target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
|
| 119 |
+
|
| 120 |
+
# 1. Desfijar absolutamente todo lo que esté fijado actualmente en el canal
|
| 121 |
+
await status_msg.edit("🧹 **Desfijando todos los mensajes fijados anteriores...**")
|
| 122 |
+
try:
|
| 123 |
+
await client.unpin_message(target_entity)
|
| 124 |
+
except Exception as unpin_err:
|
| 125 |
+
print(f"[Aviso al desfijar todo]: {unpin_err}")
|
| 126 |
+
|
| 127 |
+
await asyncio.sleep(1)
|
| 128 |
+
|
| 129 |
+
# 2. Escanear el canal destino e identificar portadas y temporadas
|
| 130 |
+
await status_msg.edit("🔍 **Escaneando canal para fijar portadas con títulos y temporadas...**")
|
| 131 |
+
pinned_count = 0
|
| 132 |
+
scanned_count = 0
|
| 133 |
+
|
| 134 |
+
# Recorrer mensajes en orden cronológico
|
| 135 |
+
async for msg in client.iter_messages(target_entity, reverse=True, limit=5000):
|
| 136 |
+
scanned_count += 1
|
| 137 |
+
|
| 138 |
+
# Debe ser foto con texto
|
| 139 |
+
if not msg.photo:
|
| 140 |
+
continue
|
| 141 |
+
|
| 142 |
+
txt = (msg.message or "").strip()
|
| 143 |
+
if not txt:
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
txt_lower = txt.lower()
|
| 147 |
+
|
| 148 |
+
# Descartar si el texto es claramente un capítulo individual (ej: "Capítulo 01")
|
| 149 |
+
if txt_lower.startswith(("capítulo", "capitulo", "cap ", "cap.")):
|
| 150 |
+
continue
|
| 151 |
+
|
| 152 |
+
es_portada_o_temporada = False
|
| 153 |
+
|
| 154 |
+
# 1. Indicadores explícitos de portada/temporada
|
| 155 |
+
keywords = [
|
| 156 |
+
"temporada", "season", "libro del", "serie:", "título:", "titulo:",
|
| 157 |
+
"estreno", "sinopsis", "finalizado", "doblaje:", "audio:", "géneros:", "generos:"
|
| 158 |
+
]
|
| 159 |
+
if any(kw in txt_lower for kw in keywords):
|
| 160 |
+
es_portada_o_temporada = True
|
| 161 |
+
|
| 162 |
+
# 2. Formatos con emojis de claqueta/cine, carpeta o cartel de título (ej: 📁 Título, 🎬 Título)
|
| 163 |
+
elif any(sym in txt for sym in ["📁", "🎬", "🍿", "📺", "🎥", "🎭"]):
|
| 164 |
+
es_portada_o_temporada = True
|
| 165 |
+
|
| 166 |
+
# 3. Títulos limpios de series en foto (cortos y en mayúsculas / título)
|
| 167 |
+
elif len(txt) <= 80 and not any(ext in txt_lower for ext in [".mp4", ".mkv", "1080p", "720p"]):
|
| 168 |
+
es_portada_o_temporada = True
|
| 169 |
+
|
| 170 |
+
if es_portada_o_temporada:
|
| 171 |
+
try:
|
| 172 |
+
await client.pin_message(target_entity, msg, notify=False)
|
| 173 |
+
pinned_count += 1
|
| 174 |
+
await asyncio.sleep(0.3)
|
| 175 |
+
except Exception as pin_err:
|
| 176 |
+
print(f"[Error fijando mensaje {msg.id}]: {pin_err}")
|
| 177 |
+
|
| 178 |
+
await status_msg.edit(
|
| 179 |
+
f"📌 **Fijado Inteligente Completado:**\n"
|
| 180 |
+
f"━━━━━━━━━━━━━━━━━━━━\n"
|
| 181 |
+
f"🧹 Se desfijaron los mensajes anteriores.\n"
|
| 182 |
+
f"🔎 Mensajes escaneados: {scanned_count}\n"
|
| 183 |
+
f"✅ Portadas y títulos fijados: **{pinned_count}**\n"
|
| 184 |
+
f"🎯 Canal: `{TARGET_CHANNEL_LINK}`"
|
| 185 |
+
)
|
| 186 |
+
except Exception as e:
|
| 187 |
+
await status_msg.edit(f"❌ Error al fijar portadas: `{e}`")
|
| 188 |
+
|
| 189 |
+
@client.on(events.NewMessage(chats='me', pattern=r"(?i)^/(eliminar_fijados|elimianr_fijados)$"))
|
| 190 |
+
async def eliminar_notificaciones_fijados_handler(event):
|
| 191 |
+
"""
|
| 192 |
+
Escanea el canal destino y elimina todos los mensajes de servicio que genera Telegram
|
| 193 |
+
al fijar mensajes (ej: 'FLOW fijó una foto', 'Te uniste a este canal', etc.)
|
| 194 |
+
para que el canal quede completamente limpio.
|
| 195 |
+
"""
|
| 196 |
+
status_msg = await event.reply("🧹 **Buscando y eliminando mensajes de 'fijó una foto' en el canal...**")
|
| 197 |
+
try:
|
| 198 |
+
target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
|
| 199 |
+
service_msg_ids = []
|
| 200 |
+
scanned = 0
|
| 201 |
+
|
| 202 |
+
async for msg in client.iter_messages(target_entity, limit=2000):
|
| 203 |
+
scanned += 1
|
| 204 |
+
# Comprobar si es un mensaje de servicio (MessageService o acciones de fijado/unirse)
|
| 205 |
+
is_service = isinstance(msg, MessageService)
|
| 206 |
+
action = getattr(msg, 'action', None)
|
| 207 |
+
if is_service or isinstance(action, (MessageActionPinMessage, MessageActionChatJoinedByLink, MessageActionChatAddUser)):
|
| 208 |
+
service_msg_ids.append(msg.id)
|
| 209 |
+
|
| 210 |
+
if not service_msg_ids:
|
| 211 |
+
await status_msg.edit("✨ **Canal limpio:** No se encontraron mensajes de notificación de fijado.")
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
# Eliminar en bloques de 100
|
| 215 |
+
deleted_count = 0
|
| 216 |
+
for i in range(0, len(service_msg_ids), 100):
|
| 217 |
+
chunk = service_msg_ids[i:i + 100]
|
| 218 |
+
await client.delete_messages(target_entity, chunk)
|
| 219 |
+
deleted_count += len(chunk)
|
| 220 |
+
await asyncio.sleep(0.5)
|
| 221 |
+
|
| 222 |
+
await status_msg.edit(
|
| 223 |
+
f"🗑️ **Limpieza Finalizada con Éxito:**\n"
|
| 224 |
+
f"━━━━━━━━━━━━━━━━━━━━\n"
|
| 225 |
+
f"✅ Se eliminaron **{deleted_count}** avisos de 'fijó una foto' / avisos de servicio.\n"
|
| 226 |
+
f"🎯 Canal: `{TARGET_CHANNEL_LINK}`"
|
| 227 |
+
)
|
| 228 |
+
except Exception as e:
|
| 229 |
+
await status_msg.edit(f"❌ Error al eliminar notificaciones de fijado: `{e}`")
|
| 230 |
+
|
| 231 |
@client.on(events.NewMessage(chats='me'))
|
| 232 |
async def process_forwarded_content(event):
|
| 233 |
# Ignorar comandos
|
|
|
|
| 254 |
source_peer = fwd_header.from_id
|
| 255 |
source_entity = await client.get_entity(source_peer)
|
| 256 |
|
| 257 |
+
# Verificar si es un canal o grupo válido
|
| 258 |
+
is_valid = isinstance(source_entity, (Channel, Chat))
|
| 259 |
+
if not is_valid:
|
| 260 |
+
await status_msg.edit("⚠️ **Solo se admiten canales y grupos.**")
|
| 261 |
return
|
| 262 |
|
| 263 |
+
# Detección de tema (Forum Topic) si proviene de un grupo con temas activados
|
| 264 |
+
topic_id = None
|
| 265 |
+
topic_title = None
|
| 266 |
+
|
| 267 |
+
# 1. Verificar si en la cabecera de reenvío o en el mensaje original viene el tema
|
| 268 |
+
orig_msg_id = getattr(fwd_header, 'channel_post', None) or getattr(fwd_header, 'saved_from_msg_id', None)
|
| 269 |
+
if orig_msg_id and getattr(source_entity, 'forum', False):
|
| 270 |
+
try:
|
| 271 |
+
orig_msgs = await client.get_messages(source_entity, ids=[orig_msg_id])
|
| 272 |
+
if orig_msgs and orig_msgs[0]:
|
| 273 |
+
orig_m = orig_msgs[0]
|
| 274 |
+
reply_header = getattr(orig_m, 'reply_to', None)
|
| 275 |
+
if reply_header and getattr(reply_header, 'forum_topic', False):
|
| 276 |
+
topic_id = getattr(reply_header, 'reply_to_top_id', None) or getattr(reply_header, 'reply_to_msg_id', None)
|
| 277 |
+
except Exception as top_err:
|
| 278 |
+
print(f"[Aviso al inspeccionar tema original]: {top_err}")
|
| 279 |
+
|
| 280 |
+
# Si se detectó un tema específico dentro del grupo
|
| 281 |
+
if topic_id:
|
| 282 |
+
try:
|
| 283 |
+
topics_res = await client(GetForumTopicsByIDRequest(peer=source_entity, topics=[topic_id]))
|
| 284 |
+
if topics_res and getattr(topics_res, 'topics', None):
|
| 285 |
+
topic_title = topics_res.topics[0].title
|
| 286 |
+
except Exception:
|
| 287 |
+
pass
|
| 288 |
+
|
| 289 |
+
# Usar siempre el título general del grupo y su portada con el emoji 📁
|
| 290 |
+
source_title = getattr(source_entity, 'title', 'Grupo/Canal')
|
| 291 |
+
header_pattern = f"📁 **{source_title}**"
|
| 292 |
|
| 293 |
+
# 2. Verificar si el origen prohíbe guardar/reenviar contenido
|
| 294 |
if getattr(source_entity, 'noforwards', False):
|
| 295 |
+
await status_msg.edit(f"⛔ **`{source_title}` prohíbe reenviar/guardar contenido.** Operación cancelada.")
|
| 296 |
return
|
| 297 |
|
| 298 |
# 3. Conectar con el canal destino
|
| 299 |
await status_msg.edit(f"🎯 Conectando con el canal destino para sincronizar `{source_title}`...")
|
| 300 |
target_entity = await get_or_join_target_channel(client, TARGET_CHANNEL_LINK)
|
| 301 |
|
| 302 |
+
# 4. Leer todos los videos e imágenes del origen (filtrando por tema si aplica)
|
| 303 |
await status_msg.edit(f"📥 Leyendo contenidos de `{source_title}`...")
|
| 304 |
source_items = []
|
| 305 |
source_fps = set()
|
| 306 |
|
| 307 |
+
iter_kwargs = {"reverse": True}
|
| 308 |
+
if topic_id:
|
| 309 |
+
iter_kwargs["reply_to"] = topic_id
|
| 310 |
+
|
| 311 |
+
async for message in client.iter_messages(source_entity, **iter_kwargs):
|
| 312 |
is_photo = bool(message.photo)
|
| 313 |
is_video = bool(message.video)
|
| 314 |
is_img_doc = False
|
|
|
|
| 375 |
prev_msg = all_recent_target_msgs[max_idx + lookback]
|
| 376 |
# Si es foto o texto y contiene parte del título o es la portada previa
|
| 377 |
prev_txt = (prev_msg.message or "").lower()
|
| 378 |
+
if (clean_title in prev_txt) or (prev_msg.photo and prev_txt.startswith(("📁", "🎬"))):
|
| 379 |
if prev_msg.id not in target_series_ids:
|
| 380 |
target_series_msgs.append(prev_msg)
|
| 381 |
target_series_ids.add(prev_msg.id)
|
|
|
|
| 404 |
)
|
| 405 |
# Reenviar los mensajes que ya estaban en el canal destino (sin etiqueta de reenvío)
|
| 406 |
sent_count = 0
|
| 407 |
+
first_sent_msg = None
|
| 408 |
for old_msg in target_series_msgs:
|
| 409 |
try:
|
| 410 |
if old_msg.media:
|
| 411 |
+
sent_item = await client.send_file(
|
| 412 |
target_entity,
|
| 413 |
file=old_msg.media,
|
| 414 |
caption=old_msg.message or ""
|
| 415 |
)
|
| 416 |
elif old_msg.message:
|
| 417 |
+
sent_item = await client.send_message(target_entity, old_msg.message)
|
| 418 |
+
else:
|
| 419 |
+
sent_item = None
|
| 420 |
+
|
| 421 |
+
if first_sent_msg is None and sent_item:
|
| 422 |
+
first_sent_msg = sent_item
|
| 423 |
+
|
| 424 |
sent_count += 1
|
| 425 |
await asyncio.sleep(0.2)
|
| 426 |
except Exception as re_err:
|
|
|
|
| 431 |
await status_msg.edit(f"➕ Agregando los **{len(new_missing_items)}** videos/imágenes nuevos...")
|
| 432 |
for msg_item, fp in new_missing_items:
|
| 433 |
try:
|
| 434 |
+
sent_item = await client.send_file(
|
| 435 |
target_entity,
|
| 436 |
file=msg_item.media,
|
| 437 |
caption=msg_item.message or ""
|
| 438 |
)
|
| 439 |
+
if first_sent_msg is None and sent_item:
|
| 440 |
+
first_sent_msg = sent_item
|
| 441 |
+
|
| 442 |
sent_count += 1
|
| 443 |
await asyncio.sleep(0.2)
|
| 444 |
except Exception as new_err:
|
| 445 |
print(f"[Error enviando nuevo]: {new_err}")
|
| 446 |
await asyncio.sleep(1)
|
| 447 |
|
| 448 |
+
# Fijar el primer mensaje enviado (portada/título de la serie)
|
| 449 |
+
if first_sent_msg:
|
| 450 |
+
try:
|
| 451 |
+
await client.pin_message(target_entity, first_sent_msg, notify=False)
|
| 452 |
+
# Limpiar notificación de servicio que genera Telegram ("FLOW fijó una foto")
|
| 453 |
+
await asyncio.sleep(0.3)
|
| 454 |
+
async for pin_notif in client.iter_messages(target_entity, limit=5):
|
| 455 |
+
if isinstance(pin_notif, MessageService) or isinstance(getattr(pin_notif, 'action', None), MessageActionPinMessage):
|
| 456 |
+
await client.delete_messages(target_entity, pin_notif.id)
|
| 457 |
+
break
|
| 458 |
+
except Exception as pin_err:
|
| 459 |
+
print(f"[Error fijando mensaje en actualizacion]: {pin_err}")
|
| 460 |
+
|
| 461 |
# Eliminar los mensajes viejos que quedaron arriba desactualizados
|
| 462 |
await status_msg.edit(f"🗑️ Eliminando los {len(old_msg_ids_to_delete)} mensajes anteriores desactualizados...")
|
| 463 |
try:
|
|
|
|
| 492 |
else:
|
| 493 |
cover_to_send = None
|
| 494 |
|
| 495 |
+
# 1. Enviar primero la portada con el título
|
| 496 |
+
first_pinned_msg = None
|
| 497 |
if cover_to_send:
|
| 498 |
+
first_pinned_msg = await client.send_file(target_entity, file=cover_to_send, caption=header_pattern)
|
| 499 |
if cover_to_send == avatar_path:
|
| 500 |
try:
|
| 501 |
os.remove(avatar_path)
|
| 502 |
except Exception:
|
| 503 |
pass
|
| 504 |
else:
|
| 505 |
+
first_pinned_msg = await client.send_message(target_entity, header_pattern)
|
| 506 |
+
|
| 507 |
+
# 2. FIJAR INMEDIATAMENTE la portada antes de enviar los videos
|
| 508 |
+
if first_pinned_msg:
|
| 509 |
+
try:
|
| 510 |
+
await client.pin_message(target_entity, first_pinned_msg, notify=False)
|
| 511 |
+
# Limpiar la notificación de servicio que genera Telegram al fijar ("FLOW fijó una foto")
|
| 512 |
+
await asyncio.sleep(0.3)
|
| 513 |
+
async for pin_notif in client.iter_messages(target_entity, limit=5):
|
| 514 |
+
if isinstance(pin_notif, MessageService) or isinstance(getattr(pin_notif, 'action', None), MessageActionPinMessage):
|
| 515 |
+
await client.delete_messages(target_entity, pin_notif.id)
|
| 516 |
+
break
|
| 517 |
+
except Exception as pin_err:
|
| 518 |
+
print(f"[Error fijando mensaje de portada]: {pin_err}")
|
| 519 |
|
| 520 |
sent_count = 0
|
| 521 |
for msg_item, fp in source_items:
|
src/plugins/general.py
CHANGED
|
@@ -12,7 +12,8 @@ def register_general_handlers(client):
|
|
| 12 |
"• `/crear_canal [nombre]` : Crea un canal privado y genera su enlace de invitación.\n\n"
|
| 13 |
"📂 **Flujo y Clonación**\n"
|
| 14 |
"• `/flow_on` : Activa el modo escaneo de canales/grupos.\n"
|
| 15 |
-
"• `/flow_off` : Desactiva el modo escaneo."
|
|
|
|
| 16 |
)
|
| 17 |
await event.reply(mensaje)
|
| 18 |
|
|
|
|
| 12 |
"• `/crear_canal [nombre]` : Crea un canal privado y genera su enlace de invitación.\n\n"
|
| 13 |
"📂 **Flujo y Clonación**\n"
|
| 14 |
"• `/flow_on` : Activa el modo escaneo de canales/grupos.\n"
|
| 15 |
+
"• `/flow_off` : Desactiva el modo escaneo.\n"
|
| 16 |
+
"• `/fijar` : Escanea el canal destino y fija todas las portadas de los animes."
|
| 17 |
)
|
| 18 |
await event.reply(mensaje)
|
| 19 |
|
src/web/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
# Paquete web
|
|
|
|
| 1 |
+
# Paquete web
|
src/web/server.py
CHANGED
|
@@ -1,97 +1,97 @@
|
|
| 1 |
-
from flask import Flask, jsonify, render_template_string
|
| 2 |
-
import logging
|
| 3 |
-
|
| 4 |
-
app = Flask(__name__)
|
| 5 |
-
|
| 6 |
-
bot_status = {
|
| 7 |
-
"status": "Iniciando...",
|
| 8 |
-
"user": None
|
| 9 |
-
}
|
| 10 |
-
|
| 11 |
-
HTML_TEMPLATE = """
|
| 12 |
-
<!DOCTYPE html>
|
| 13 |
-
<html lang="es">
|
| 14 |
-
<head>
|
| 15 |
-
<meta charset="UTF-8">
|
| 16 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 17 |
-
<title>UserBot Películas - Service Alive</title>
|
| 18 |
-
<style>
|
| 19 |
-
body {
|
| 20 |
-
margin: 0;
|
| 21 |
-
background: #0f172a;
|
| 22 |
-
color: #f8fafc;
|
| 23 |
-
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
| 24 |
-
display: flex;
|
| 25 |
-
align-items: center;
|
| 26 |
-
justify-content: center;
|
| 27 |
-
height: 100vh;
|
| 28 |
-
}
|
| 29 |
-
.card {
|
| 30 |
-
background: rgba(30, 41, 59, 0.7);
|
| 31 |
-
backdrop-filter: blur(12px);
|
| 32 |
-
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 33 |
-
border-radius: 16px;
|
| 34 |
-
padding: 32px 40px;
|
| 35 |
-
box-shadow: 0 20px 40px rgba(0,0,0,0.4);
|
| 36 |
-
text-align: center;
|
| 37 |
-
max-width: 420px;
|
| 38 |
-
width: 90%;
|
| 39 |
-
}
|
| 40 |
-
.badge {
|
| 41 |
-
display: inline-block;
|
| 42 |
-
background: #10b981;
|
| 43 |
-
color: #022c22;
|
| 44 |
-
font-weight: 700;
|
| 45 |
-
padding: 4px 14px;
|
| 46 |
-
border-radius: 9999px;
|
| 47 |
-
font-size: 0.85rem;
|
| 48 |
-
margin-bottom: 16px;
|
| 49 |
-
}
|
| 50 |
-
h1 { margin: 0 0 10px; font-size: 1.6rem; color: #38bdf8; }
|
| 51 |
-
p { color: #94a3b8; font-size: 0.95rem; line-height: 1.5; margin: 8px 0; }
|
| 52 |
-
.details {
|
| 53 |
-
margin-top: 20px;
|
| 54 |
-
padding: 12px;
|
| 55 |
-
background: #090d16;
|
| 56 |
-
border-radius: 8px;
|
| 57 |
-
font-family: monospace;
|
| 58 |
-
font-size: 0.85rem;
|
| 59 |
-
color: #a5f3fc;
|
| 60 |
-
text-align: left;
|
| 61 |
-
word-break: break-all;
|
| 62 |
-
}
|
| 63 |
-
</style>
|
| 64 |
-
</head>
|
| 65 |
-
<body>
|
| 66 |
-
<div class="card">
|
| 67 |
-
<div class="badge">ONLINE 24/7</div>
|
| 68 |
-
<h1>🎬 UserBot Películas</h1>
|
| 69 |
-
<p>Servidor web activo para Hugging Face Spaces / PaaS.</p>
|
| 70 |
-
<div class="details">
|
| 71 |
-
<div><strong>Estado:</strong> {{ status }}</div>
|
| 72 |
-
<div><strong>Cuenta:</strong> {{ user or 'Verificando...' }}</div>
|
| 73 |
-
<div><strong>Puerto:</strong> {{ port }}</div>
|
| 74 |
-
</div>
|
| 75 |
-
</div>
|
| 76 |
-
</body>
|
| 77 |
-
</html>
|
| 78 |
-
"""
|
| 79 |
-
|
| 80 |
-
@app.route("/")
|
| 81 |
-
def index():
|
| 82 |
-
from config import PORT
|
| 83 |
-
return render_template_string(
|
| 84 |
-
HTML_TEMPLATE,
|
| 85 |
-
status=bot_status["status"],
|
| 86 |
-
user=bot_status["user"],
|
| 87 |
-
port=PORT
|
| 88 |
-
)
|
| 89 |
-
|
| 90 |
-
@app.route("/health")
|
| 91 |
-
def health():
|
| 92 |
-
return jsonify({"status": "healthy", "bot": bot_status})
|
| 93 |
-
|
| 94 |
-
def start_server(port):
|
| 95 |
-
log = logging.getLogger('werkzeug')
|
| 96 |
-
log.setLevel(logging.ERROR)
|
| 97 |
-
app.run(host="0.0.0.0", port=port, use_reloader=False)
|
|
|
|
| 1 |
+
from flask import Flask, jsonify, render_template_string
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
app = Flask(__name__)
|
| 5 |
+
|
| 6 |
+
bot_status = {
|
| 7 |
+
"status": "Iniciando...",
|
| 8 |
+
"user": None
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
HTML_TEMPLATE = """
|
| 12 |
+
<!DOCTYPE html>
|
| 13 |
+
<html lang="es">
|
| 14 |
+
<head>
|
| 15 |
+
<meta charset="UTF-8">
|
| 16 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 17 |
+
<title>UserBot Películas - Service Alive</title>
|
| 18 |
+
<style>
|
| 19 |
+
body {
|
| 20 |
+
margin: 0;
|
| 21 |
+
background: #0f172a;
|
| 22 |
+
color: #f8fafc;
|
| 23 |
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
| 24 |
+
display: flex;
|
| 25 |
+
align-items: center;
|
| 26 |
+
justify-content: center;
|
| 27 |
+
height: 100vh;
|
| 28 |
+
}
|
| 29 |
+
.card {
|
| 30 |
+
background: rgba(30, 41, 59, 0.7);
|
| 31 |
+
backdrop-filter: blur(12px);
|
| 32 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 33 |
+
border-radius: 16px;
|
| 34 |
+
padding: 32px 40px;
|
| 35 |
+
box-shadow: 0 20px 40px rgba(0,0,0,0.4);
|
| 36 |
+
text-align: center;
|
| 37 |
+
max-width: 420px;
|
| 38 |
+
width: 90%;
|
| 39 |
+
}
|
| 40 |
+
.badge {
|
| 41 |
+
display: inline-block;
|
| 42 |
+
background: #10b981;
|
| 43 |
+
color: #022c22;
|
| 44 |
+
font-weight: 700;
|
| 45 |
+
padding: 4px 14px;
|
| 46 |
+
border-radius: 9999px;
|
| 47 |
+
font-size: 0.85rem;
|
| 48 |
+
margin-bottom: 16px;
|
| 49 |
+
}
|
| 50 |
+
h1 { margin: 0 0 10px; font-size: 1.6rem; color: #38bdf8; }
|
| 51 |
+
p { color: #94a3b8; font-size: 0.95rem; line-height: 1.5; margin: 8px 0; }
|
| 52 |
+
.details {
|
| 53 |
+
margin-top: 20px;
|
| 54 |
+
padding: 12px;
|
| 55 |
+
background: #090d16;
|
| 56 |
+
border-radius: 8px;
|
| 57 |
+
font-family: monospace;
|
| 58 |
+
font-size: 0.85rem;
|
| 59 |
+
color: #a5f3fc;
|
| 60 |
+
text-align: left;
|
| 61 |
+
word-break: break-all;
|
| 62 |
+
}
|
| 63 |
+
</style>
|
| 64 |
+
</head>
|
| 65 |
+
<body>
|
| 66 |
+
<div class="card">
|
| 67 |
+
<div class="badge">ONLINE 24/7</div>
|
| 68 |
+
<h1>🎬 UserBot Películas</h1>
|
| 69 |
+
<p>Servidor web activo para Hugging Face Spaces / PaaS.</p>
|
| 70 |
+
<div class="details">
|
| 71 |
+
<div><strong>Estado:</strong> {{ status }}</div>
|
| 72 |
+
<div><strong>Cuenta:</strong> {{ user or 'Verificando...' }}</div>
|
| 73 |
+
<div><strong>Puerto:</strong> {{ port }}</div>
|
| 74 |
+
</div>
|
| 75 |
+
</div>
|
| 76 |
+
</body>
|
| 77 |
+
</html>
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
@app.route("/")
|
| 81 |
+
def index():
|
| 82 |
+
from config import PORT
|
| 83 |
+
return render_template_string(
|
| 84 |
+
HTML_TEMPLATE,
|
| 85 |
+
status=bot_status["status"],
|
| 86 |
+
user=bot_status["user"],
|
| 87 |
+
port=PORT
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
@app.route("/health")
|
| 91 |
+
def health():
|
| 92 |
+
return jsonify({"status": "healthy", "bot": bot_status})
|
| 93 |
+
|
| 94 |
+
def start_server(port):
|
| 95 |
+
log = logging.getLogger('werkzeug')
|
| 96 |
+
log.setLevel(logging.ERROR)
|
| 97 |
+
app.run(host="0.0.0.0", port=port, use_reloader=False)
|