Spaces:
Paused
Paused
Upload 5 files
Browse files- Dockerfile +7 -8
- app.py +111 -0
- bot.py +303 -0
- requirements.txt +2 -0
Dockerfile
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
FROM python:3.11-slim
|
| 2 |
|
| 3 |
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
PYTHONUNBUFFERED=1 \
|
|
@@ -7,16 +7,15 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
|
|
| 7 |
WORKDIR /app
|
| 8 |
|
| 9 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 10 |
-
|
| 11 |
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
|
| 13 |
-
COPY requirements.txt
|
| 14 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
|
| 16 |
-
COPY .
|
| 17 |
-
|
| 18 |
-
|
| 19 |
|
| 20 |
EXPOSE 7860
|
| 21 |
-
|
| 22 |
-
CMD ["python", "main.py"]
|
|
|
|
| 1 |
+
FROM python:3.11-slim-bookworm
|
| 2 |
|
| 3 |
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
PYTHONUNBUFFERED=1 \
|
|
|
|
| 7 |
WORKDIR /app
|
| 8 |
|
| 9 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 10 |
+
ca-certificates ffmpeg gcc python3-dev build-essential \
|
| 11 |
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
|
| 13 |
+
COPY requirements.txt /app/
|
| 14 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
|
| 16 |
+
COPY . /app/
|
| 17 |
+
RUN mkdir -p /app/downloads /app/session && chown -R 1000:1000 /app
|
| 18 |
+
USER 1000
|
| 19 |
|
| 20 |
EXPOSE 7860
|
| 21 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
app.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import mimetypes
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from contextlib import asynccontextmanager
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from urllib.parse import quote
|
| 8 |
+
|
| 9 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 10 |
+
from fastapi.responses import HTMLResponse, StreamingResponse, PlainTextResponse
|
| 11 |
+
|
| 12 |
+
from bot import start_bot, stop_bot, DOWNLOAD_DIR, MAX_FILE_MB
|
| 13 |
+
|
| 14 |
+
log = logging.getLogger("file2link.app")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def find_file_by_token(token: str):
|
| 18 |
+
if not re.fullmatch(r"[a-f0-9]{32}", token):
|
| 19 |
+
return None
|
| 20 |
+
matches = list(DOWNLOAD_DIR.glob(f"{token}_*"))
|
| 21 |
+
return matches[0] if matches else None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def make_headers(path: Path, download_name: str, start: int, end: int, total: int, status_code: int):
|
| 25 |
+
mime_type, _ = mimetypes.guess_type(path.name)
|
| 26 |
+
mime_type = mime_type or "application/octet-stream"
|
| 27 |
+
quoted = quote(download_name)
|
| 28 |
+
ascii_fallback = download_name.encode("ascii", "ignore").decode("ascii") or "download"
|
| 29 |
+
ascii_fallback = ascii_fallback.replace('"', "")
|
| 30 |
+
headers = {
|
| 31 |
+
"Accept-Ranges": "bytes",
|
| 32 |
+
"Content-Type": mime_type,
|
| 33 |
+
"Content-Disposition": f"attachment; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quoted}",
|
| 34 |
+
"Cache-Control": "public, max-age=86400",
|
| 35 |
+
"Content-Length": str(end - start + 1),
|
| 36 |
+
}
|
| 37 |
+
if status_code == 206:
|
| 38 |
+
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
|
| 39 |
+
return headers
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def file_iterator(path: Path, start: int, end: int):
|
| 43 |
+
with path.open("rb") as f:
|
| 44 |
+
f.seek(start)
|
| 45 |
+
remaining = end - start + 1
|
| 46 |
+
while remaining > 0:
|
| 47 |
+
chunk = f.read(min(1024 * 1024, remaining))
|
| 48 |
+
if not chunk:
|
| 49 |
+
break
|
| 50 |
+
remaining -= len(chunk)
|
| 51 |
+
yield chunk
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@asynccontextmanager
|
| 55 |
+
async def lifespan(app: FastAPI):
|
| 56 |
+
log.info("Arrancando bot File2Link dentro del mismo loop de FastAPI...")
|
| 57 |
+
await start_bot()
|
| 58 |
+
yield
|
| 59 |
+
await stop_bot()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
app = FastAPI(title="File2Link Telegram Bot", version="5.0", lifespan=lifespan)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@app.get("/", response_class=HTMLResponse)
|
| 66 |
+
async def index():
|
| 67 |
+
return """
|
| 68 |
+
<html><head><meta charset='utf-8'><title>File2Link Bot</title></head>
|
| 69 |
+
<body style='font-family:Arial;background:#111;color:#eee;display:grid;place-items:center;min-height:100vh'>
|
| 70 |
+
<div style='text-align:center;max-width:680px'>
|
| 71 |
+
<h1>🤖 File2Link Bot</h1>
|
| 72 |
+
<p>Online. Envía archivos al bot de Telegram para generar links directos del Space.</p>
|
| 73 |
+
<p>Soporta Range para reanudar descargas con ADM / 1DM / IDM.</p>
|
| 74 |
+
</div>
|
| 75 |
+
</body></html>
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@app.get("/health")
|
| 80 |
+
async def health():
|
| 81 |
+
return {"status": "ok", "bot": "file2link", "max_file_mb": MAX_FILE_MB}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@app.get("/file/{token}/{name:path}")
|
| 85 |
+
async def download_file(token: str, name: str, request: Request):
|
| 86 |
+
path = find_file_by_token(token)
|
| 87 |
+
if not path or not path.exists() or not path.is_file():
|
| 88 |
+
raise HTTPException(status_code=404, detail="Archivo no encontrado o expirado")
|
| 89 |
+
total = path.stat().st_size
|
| 90 |
+
download_name = path.name.split("_", 1)[1] if "_" in path.name else path.name
|
| 91 |
+
range_header = request.headers.get("range") or request.headers.get("Range")
|
| 92 |
+
start, end, status_code = 0, total - 1, 200
|
| 93 |
+
if range_header:
|
| 94 |
+
m = re.match(r"bytes=(\d*)-(\d*)", range_header)
|
| 95 |
+
if not m:
|
| 96 |
+
raise HTTPException(status_code=416, detail="Rango inválido")
|
| 97 |
+
start_s, end_s = m.groups()
|
| 98 |
+
if start_s:
|
| 99 |
+
start = int(start_s)
|
| 100 |
+
if end_s:
|
| 101 |
+
end = int(end_s)
|
| 102 |
+
if start_s == "" and end_s:
|
| 103 |
+
suffix = int(end_s)
|
| 104 |
+
start = max(total - suffix, 0)
|
| 105 |
+
end = total - 1
|
| 106 |
+
if start > end or start >= total:
|
| 107 |
+
return PlainTextResponse("Rango no disponible", status_code=416, headers={"Content-Range": f"bytes */{total}"})
|
| 108 |
+
end = min(end, total - 1)
|
| 109 |
+
status_code = 206
|
| 110 |
+
headers = make_headers(path, download_name, start, end, total, status_code)
|
| 111 |
+
return StreamingResponse(file_iterator(path, start, end), status_code=status_code, headers=headers)
|
bot.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import html
|
| 3 |
+
import logging
|
| 4 |
+
import mimetypes
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
import uuid
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Optional, Tuple
|
| 11 |
+
from urllib.parse import unquote, urlparse, quote
|
| 12 |
+
from email.message import Message as EmailMessage
|
| 13 |
+
|
| 14 |
+
from aiohttp import ClientSession, ClientTimeout
|
| 15 |
+
from dotenv import load_dotenv
|
| 16 |
+
from pyrogram import Client, filters
|
| 17 |
+
from pyrogram.types import Message
|
| 18 |
+
|
| 19 |
+
load_dotenv()
|
| 20 |
+
|
| 21 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s")
|
| 22 |
+
log = logging.getLogger("file2link")
|
| 23 |
+
|
| 24 |
+
API_ID = int(os.getenv("API_ID", "0"))
|
| 25 |
+
API_HASH = os.getenv("API_HASH", "")
|
| 26 |
+
BOT_TOKEN = os.getenv("BOT_TOKEN", "")
|
| 27 |
+
BASE_URL = os.getenv("BASE_URL", "").rstrip("/")
|
| 28 |
+
SPACE_HOST = os.getenv("SPACE_HOST", "").strip()
|
| 29 |
+
if not BASE_URL and SPACE_HOST:
|
| 30 |
+
BASE_URL = f"https://{SPACE_HOST}".rstrip("/")
|
| 31 |
+
|
| 32 |
+
DOWNLOAD_DIR = Path(os.getenv("DOWNLOAD_DIR", "/app/downloads"))
|
| 33 |
+
MAX_FILE_MB = int(os.getenv("MAX_FILE_MB", "1900"))
|
| 34 |
+
KEEP_HOURS = int(os.getenv("KEEP_HOURS", "24"))
|
| 35 |
+
DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
|
| 37 |
+
if not API_ID or not API_HASH or not BOT_TOKEN:
|
| 38 |
+
raise RuntimeError("Faltan API_ID, API_HASH o BOT_TOKEN en variables de entorno.")
|
| 39 |
+
|
| 40 |
+
bot = Client(
|
| 41 |
+
"file2link_bot",
|
| 42 |
+
api_id=API_ID,
|
| 43 |
+
api_hash=API_HASH,
|
| 44 |
+
bot_token=BOT_TOKEN,
|
| 45 |
+
workdir="/app/session",
|
| 46 |
+
in_memory=False,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
SAFE_NAME_RE = re.compile(r"[^a-zA-Z0-9._() \-áéíóúÁÉÍÓÚñÑüÜ]+")
|
| 50 |
+
MEDIAFIRE_RE = re.compile(r"https?://(?:www\.)?mediafire\.com/\S+", re.I)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def human_size(num: int) -> str:
|
| 54 |
+
units = ["B", "KB", "MB", "GB", "TB"]
|
| 55 |
+
size = float(num or 0)
|
| 56 |
+
for unit in units:
|
| 57 |
+
if size < 1024 or unit == units[-1]:
|
| 58 |
+
return f"{size:.2f} {unit}" if unit != "B" else f"{int(size)} B"
|
| 59 |
+
size /= 1024
|
| 60 |
+
return f"{num} B"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def clean_name(name: str) -> str:
|
| 64 |
+
name = unquote(name or "file")
|
| 65 |
+
name = name.replace("/", "_").replace("\\", "_").replace("\x00", "")
|
| 66 |
+
name = SAFE_NAME_RE.sub("_", name).strip(" ._")
|
| 67 |
+
return name[:180] or "file"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def extension_from_mime(mime_type: Optional[str], default: str = "") -> str:
|
| 71 |
+
if not mime_type:
|
| 72 |
+
return default
|
| 73 |
+
overrides = {
|
| 74 |
+
"image/jpeg": ".jpg", "audio/ogg": ".ogg", "video/mp4": ".mp4",
|
| 75 |
+
"image/webp": ".webp", "application/x-tgsticker": ".tgs",
|
| 76 |
+
"video/webm": ".webm", "application/gzip": ".gz",
|
| 77 |
+
}
|
| 78 |
+
return overrides.get(mime_type.lower()) or mimetypes.guess_extension(mime_type) or default
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def ensure_extension(name: str, mime_type: Optional[str] = None, default_ext: str = "") -> str:
|
| 82 |
+
name = clean_name(name)
|
| 83 |
+
if Path(name).suffix:
|
| 84 |
+
return name
|
| 85 |
+
ext = extension_from_mime(mime_type, default_ext)
|
| 86 |
+
if ext and not ext.startswith("."):
|
| 87 |
+
ext = "." + ext
|
| 88 |
+
return clean_name(name + (ext or ""))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def public_link(token: str, original_name: str) -> str:
|
| 92 |
+
safe_name = quote(clean_name(original_name), safe="._-()")
|
| 93 |
+
return f"{BASE_URL}/file/{token}/{safe_name}" if BASE_URL else f"/file/{token}/{safe_name}"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_media_info(message: Message) -> Tuple[Optional[object], Optional[str], int]:
|
| 97 |
+
media = message.document or message.video or message.audio or message.voice or message.video_note or message.photo or message.animation or message.sticker
|
| 98 |
+
if not media:
|
| 99 |
+
return None, None, 0
|
| 100 |
+
file_name = getattr(media, "file_name", None)
|
| 101 |
+
file_size = getattr(media, "file_size", 0) or 0
|
| 102 |
+
mime_type = getattr(media, "mime_type", None)
|
| 103 |
+
|
| 104 |
+
if message.photo:
|
| 105 |
+
file_name = ensure_extension(file_name or f"photo_{message.id}", "image/jpeg", ".jpg")
|
| 106 |
+
elif message.voice:
|
| 107 |
+
file_name = ensure_extension(file_name or f"voice_{message.id}", mime_type or "audio/ogg", ".ogg")
|
| 108 |
+
elif message.video_note:
|
| 109 |
+
file_name = ensure_extension(file_name or f"video_note_{message.id}", mime_type or "video/mp4", ".mp4")
|
| 110 |
+
elif message.sticker:
|
| 111 |
+
if not file_name:
|
| 112 |
+
if getattr(media, "is_animated", False):
|
| 113 |
+
file_name = f"sticker_{message.id}.tgs"
|
| 114 |
+
elif getattr(media, "is_video", False):
|
| 115 |
+
file_name = f"sticker_{message.id}.webm"
|
| 116 |
+
else:
|
| 117 |
+
file_name = f"sticker_{message.id}.webp"
|
| 118 |
+
file_name = ensure_extension(file_name, mime_type, Path(file_name).suffix or ".webp")
|
| 119 |
+
elif message.video:
|
| 120 |
+
file_name = ensure_extension(file_name or f"video_{message.id}", mime_type or "video/mp4", ".mp4")
|
| 121 |
+
elif message.animation:
|
| 122 |
+
file_name = ensure_extension(file_name or f"animation_{message.id}", mime_type or "video/mp4", ".mp4")
|
| 123 |
+
elif message.audio:
|
| 124 |
+
file_name = ensure_extension(file_name or f"audio_{message.id}", mime_type or "audio/mpeg", ".mp3")
|
| 125 |
+
elif message.document:
|
| 126 |
+
file_name = ensure_extension(file_name or f"file_{message.id}", mime_type, "")
|
| 127 |
+
return media, clean_name(file_name or f"file_{message.id}"), file_size
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
async def progress(current: int, total: int, status: Message, started: float, state: dict, label: str):
|
| 131 |
+
now = time.time()
|
| 132 |
+
if now - state.get("last", 0) < 3 and current != total:
|
| 133 |
+
return
|
| 134 |
+
state["last"] = now
|
| 135 |
+
percent = current / total * 100 if total else 0
|
| 136 |
+
speed = current / max(now - started, 1)
|
| 137 |
+
try:
|
| 138 |
+
await status.edit_text(f"{label}\n{percent:.1f}% — {human_size(current)} / {human_size(total)}\nVelocidad: {human_size(int(speed))}/s")
|
| 139 |
+
except Exception:
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@bot.on_message(filters.private, group=-1000)
|
| 144 |
+
async def debug_incoming(_, message: Message):
|
| 145 |
+
log.info("📩 Mensaje recibido chat=%s id=%s text=%r media=%s", message.chat.id if message.chat else None, message.id, message.text, bool(message.media))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@bot.on_message(filters.private & (filters.command(["start", "help"], prefixes=["/", "!", "."]) | filters.regex(r"^(?:/|!|\.)?(start|help)(?:@\w+)?$")), group=-10)
|
| 149 |
+
async def start_cmd(_, message: Message):
|
| 150 |
+
await message.reply_text(
|
| 151 |
+
"👋 Estoy activo.\n\n"
|
| 152 |
+
"Envíame archivo, video, foto, audio, sticker, GIF o nota y te doy un link directo del Hugging Face Space.\n\n"
|
| 153 |
+
"También puedes enviarme un link de MediaFire: lo descargo, conservo el nombre original, te doy link y trato de reenviártelo."
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@bot.on_message(filters.private & filters.text & filters.regex(MEDIAFIRE_RE), group=0)
|
| 158 |
+
async def mediafire_handler(_, message: Message):
|
| 159 |
+
url = MEDIAFIRE_RE.search(message.text or "").group(0).rstrip(").,;")
|
| 160 |
+
status = await message.reply_text("⏳ Analizando link de MediaFire...")
|
| 161 |
+
try:
|
| 162 |
+
path, original_name, size = await download_mediafire(url, status)
|
| 163 |
+
except Exception as exc:
|
| 164 |
+
log.exception("Error descargando MediaFire")
|
| 165 |
+
await status.edit_text(f"❌ No pude descargar ese MediaFire:\n`{exc}`")
|
| 166 |
+
return
|
| 167 |
+
token = path.name.split("_", 1)[0]
|
| 168 |
+
link = public_link(token, original_name)
|
| 169 |
+
caption = f"✅ MediaFire descargado\n📦 {original_name}\n📏 {human_size(size)}\n🔗 {link}"
|
| 170 |
+
try:
|
| 171 |
+
await status.edit_text("⬆️ Subiendo a Telegram...")
|
| 172 |
+
await bot.send_document(message.chat.id, str(path), file_name=original_name, caption=caption[:1024], progress=progress, progress_args=(status, time.time(), {"last": 0}, "⬆️ Subiendo a Telegram..."))
|
| 173 |
+
await status.delete()
|
| 174 |
+
except Exception as exc:
|
| 175 |
+
await status.edit_text(f"✅ Descargado, pero Telegram no me dejó reenviarlo.\n\n📦 `{original_name}`\n📏 {human_size(size)}\n🔗 {link}\n\nError: `{exc}`")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@bot.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.voice | filters.photo | filters.animation | filters.sticker | filters.video_note), group=1)
|
| 179 |
+
async def media_handler(_, message: Message):
|
| 180 |
+
media, original_name, file_size = get_media_info(message)
|
| 181 |
+
if not media:
|
| 182 |
+
await message.reply_text("❌ No pude detectar ese archivo.")
|
| 183 |
+
return
|
| 184 |
+
if file_size and file_size > MAX_FILE_MB * 1024 * 1024:
|
| 185 |
+
await message.reply_text(f"❌ Archivo muy grande. Límite: {MAX_FILE_MB} MB.")
|
| 186 |
+
return
|
| 187 |
+
status = await message.reply_text("⏳ Descargando desde Telegram al servidor...")
|
| 188 |
+
token = uuid.uuid4().hex
|
| 189 |
+
path = DOWNLOAD_DIR / f"{token}_{original_name}"
|
| 190 |
+
try:
|
| 191 |
+
saved = await bot.download_media(message, file_name=str(path), progress=progress, progress_args=(status, time.time(), {"last": 0}, "⬇️ Descargando al servidor..."))
|
| 192 |
+
if saved and Path(saved) != path:
|
| 193 |
+
path = Path(saved)
|
| 194 |
+
except Exception as exc:
|
| 195 |
+
log.exception("Error descargando Telegram")
|
| 196 |
+
await status.edit_text(f"❌ Error descargando:\n`{exc}`")
|
| 197 |
+
return
|
| 198 |
+
if not path.exists():
|
| 199 |
+
await status.edit_text("❌ La descarga falló o no se guardó.")
|
| 200 |
+
return
|
| 201 |
+
size = path.stat().st_size
|
| 202 |
+
link = public_link(token, original_name)
|
| 203 |
+
await status.edit_text(f"✅ Archivo listo.\n\n📦 Nombre: `{original_name}`\n📏 Tamaño: `{human_size(size)}`\n🔗 Link directo:\n{link}\n\n✅ Soporta reanudar descarga con ADM/1DM/IDM.")
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@bot.on_message(filters.private & filters.text, group=100)
|
| 207 |
+
async def text_fallback(_, message: Message):
|
| 208 |
+
await message.reply_text("✅ El bot está leyendo mensajes. Envíame un archivo/media o un link de MediaFire.")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@bot.on_message(filters.private, group=101)
|
| 212 |
+
async def any_fallback(_, message: Message):
|
| 213 |
+
if not message.text and not message.media:
|
| 214 |
+
await message.reply_text("✅ Te leí, pero ese tipo de mensaje no lo puedo convertir.")
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def filename_from_headers_or_url(headers, url: str, fallback: str = "mediafire_file") -> str:
|
| 218 |
+
cd = headers.get("Content-Disposition", "") if headers else ""
|
| 219 |
+
content_type = headers.get("Content-Type", "").split(";", 1)[0].strip() if headers else ""
|
| 220 |
+
if cd:
|
| 221 |
+
msg = EmailMessage(); msg["content-disposition"] = cd
|
| 222 |
+
filename = msg.get_filename()
|
| 223 |
+
if filename:
|
| 224 |
+
return ensure_extension(filename, content_type)
|
| 225 |
+
name = Path(unquote(urlparse(str(url)).path)).name
|
| 226 |
+
if not name or name.lower() in {"download", "file"}:
|
| 227 |
+
name = fallback
|
| 228 |
+
return ensure_extension(name, content_type)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
async def get_mediafire_direct_url(session: ClientSession, mediafire_url: str) -> str:
|
| 232 |
+
async with session.get(mediafire_url, allow_redirects=True) as resp:
|
| 233 |
+
text = await resp.text(errors="ignore")
|
| 234 |
+
if resp.status >= 400:
|
| 235 |
+
raise RuntimeError(f"MediaFire respondió HTTP {resp.status}")
|
| 236 |
+
patterns = [
|
| 237 |
+
r'id=["\']downloadButton["\'][^>]+href=["\']([^"\']+)',
|
| 238 |
+
r'href=["\'](https?://download[^"\']+mediafire[^"\']+)["\']',
|
| 239 |
+
r'href=["\'](https?://[^"\']*mediafire\.com/[^"\']*/[^"\']+)["\']',
|
| 240 |
+
]
|
| 241 |
+
for pat in patterns:
|
| 242 |
+
m = re.search(pat, text, flags=re.I | re.S)
|
| 243 |
+
if m:
|
| 244 |
+
return html.unescape(m.group(1))
|
| 245 |
+
raise RuntimeError("No encontré el botón de descarga. Puede ser carpeta, privado o protegido.")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
async def download_mediafire(url: str, status: Message) -> Tuple[Path, str, int]:
|
| 249 |
+
timeout = ClientTimeout(total=None, connect=45, sock_read=180)
|
| 250 |
+
max_bytes = MAX_FILE_MB * 1024 * 1024
|
| 251 |
+
async with ClientSession(timeout=timeout, headers={"User-Agent": "Mozilla/5.0"}) as session:
|
| 252 |
+
direct = await get_mediafire_direct_url(session, url)
|
| 253 |
+
async with session.get(direct, allow_redirects=True) as resp:
|
| 254 |
+
if resp.status >= 400:
|
| 255 |
+
raise RuntimeError(f"HTTP {resp.status}")
|
| 256 |
+
total = int(resp.headers.get("Content-Length", "0") or 0)
|
| 257 |
+
if total and total > max_bytes:
|
| 258 |
+
raise RuntimeError(f"Archivo demasiado grande. Límite: {MAX_FILE_MB} MB")
|
| 259 |
+
original_name = filename_from_headers_or_url(resp.headers, str(resp.url), "mediafire_file")
|
| 260 |
+
token = uuid.uuid4().hex
|
| 261 |
+
path = DOWNLOAD_DIR / f"{token}_{original_name}"
|
| 262 |
+
downloaded = 0; started = time.time(); state = {"last": 0}
|
| 263 |
+
with path.open("wb") as f:
|
| 264 |
+
async for chunk in resp.content.iter_chunked(1024 * 1024):
|
| 265 |
+
if not chunk:
|
| 266 |
+
continue
|
| 267 |
+
downloaded += len(chunk)
|
| 268 |
+
if downloaded > max_bytes:
|
| 269 |
+
path.unlink(missing_ok=True)
|
| 270 |
+
raise RuntimeError(f"Archivo demasiado grande. Límite: {MAX_FILE_MB} MB")
|
| 271 |
+
f.write(chunk)
|
| 272 |
+
await progress(downloaded, total, status, started, state, "⬇️ Descargando desde MediaFire...")
|
| 273 |
+
return path, original_name, path.stat().st_size
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
async def cleanup_loop():
|
| 277 |
+
while True:
|
| 278 |
+
try:
|
| 279 |
+
cutoff = time.time() - KEEP_HOURS * 3600
|
| 280 |
+
for p in DOWNLOAD_DIR.glob("*"):
|
| 281 |
+
if p.is_file() and p.stat().st_mtime < cutoff:
|
| 282 |
+
p.unlink(missing_ok=True)
|
| 283 |
+
except Exception:
|
| 284 |
+
log.exception("Error limpiando archivos")
|
| 285 |
+
await asyncio.sleep(1800)
|
| 286 |
+
|
| 287 |
+
_cleanup_task = None
|
| 288 |
+
|
| 289 |
+
async def start_bot():
|
| 290 |
+
global _cleanup_task
|
| 291 |
+
me = await bot.get_me() if bot.is_connected else None
|
| 292 |
+
await bot.start()
|
| 293 |
+
me = await bot.get_me()
|
| 294 |
+
log.info("✅ Bot iniciado como @%s id=%s", me.username, me.id)
|
| 295 |
+
_cleanup_task = asyncio.create_task(cleanup_loop())
|
| 296 |
+
|
| 297 |
+
async def stop_bot():
|
| 298 |
+
global _cleanup_task
|
| 299 |
+
if _cleanup_task:
|
| 300 |
+
_cleanup_task.cancel()
|
| 301 |
+
if bot.is_connected:
|
| 302 |
+
await bot.stop()
|
| 303 |
+
log.info("Bot detenido")
|
requirements.txt
CHANGED
|
@@ -1,4 +1,6 @@
|
|
| 1 |
pyrogram==2.0.106
|
| 2 |
TgCrypto==1.2.5
|
|
|
|
|
|
|
| 3 |
aiohttp==3.9.5
|
| 4 |
python-dotenv==1.0.1
|
|
|
|
| 1 |
pyrogram==2.0.106
|
| 2 |
TgCrypto==1.2.5
|
| 3 |
+
fastapi==0.115.6
|
| 4 |
+
uvicorn[standard]==0.34.0
|
| 5 |
aiohttp==3.9.5
|
| 6 |
python-dotenv==1.0.1
|