Spaces:
Paused
Paused
Download bot.py from saske560/Filetolink12: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/spaces/saske560/Filetolink12/resolve/main/bot.py
- Command line
-
hf download hf://spaces/saske560/Filetolink12/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/saske560/Filetolink12/resolve/main/bot.py
13.4 kB
| import asyncio | |
| import html | |
| import logging | |
| import mimetypes | |
| import os | |
| import re | |
| import time | |
| import uuid | |
| from pathlib import Path | |
| from typing import Optional, Tuple | |
| from urllib.parse import unquote, urlparse, quote | |
| from email.message import Message as EmailMessage | |
| from aiohttp import ClientSession, ClientTimeout | |
| from dotenv import load_dotenv | |
| from pyrogram import Client, filters | |
| from pyrogram.types import Message | |
| load_dotenv() | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s") | |
| log = logging.getLogger("file2link") | |
| API_ID = int(os.getenv("API_ID", "0")) | |
| API_HASH = os.getenv("API_HASH", "") | |
| BOT_TOKEN = os.getenv("BOT_TOKEN", "") | |
| BASE_URL = os.getenv("BASE_URL", "").rstrip("/") | |
| SPACE_HOST = os.getenv("SPACE_HOST", "").strip() | |
| if not BASE_URL and SPACE_HOST: | |
| BASE_URL = f"https://{SPACE_HOST}".rstrip("/") | |
| DOWNLOAD_DIR = Path(os.getenv("DOWNLOAD_DIR", "/app/downloads")) | |
| MAX_FILE_MB = int(os.getenv("MAX_FILE_MB", "1900")) | |
| KEEP_HOURS = int(os.getenv("KEEP_HOURS", "24")) | |
| DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True) | |
| if not API_ID or not API_HASH or not BOT_TOKEN: | |
| raise RuntimeError("Faltan API_ID, API_HASH o BOT_TOKEN en variables de entorno.") | |
| bot = Client( | |
| "file2link_bot", | |
| api_id=API_ID, | |
| api_hash=API_HASH, | |
| bot_token=BOT_TOKEN, | |
| workdir="/app/session", | |
| in_memory=False, | |
| ) | |
| SAFE_NAME_RE = re.compile(r"[^a-zA-Z0-9._() \-áéíóúÁÉÍÓÚñÑüÜ]+") | |
| MEDIAFIRE_RE = re.compile(r"https?://(?:www\.)?mediafire\.com/\S+", re.I) | |
| def human_size(num: int) -> str: | |
| units = ["B", "KB", "MB", "GB", "TB"] | |
| size = float(num or 0) | |
| for unit in units: | |
| if size < 1024 or unit == units[-1]: | |
| return f"{size:.2f} {unit}" if unit != "B" else f"{int(size)} B" | |
| size /= 1024 | |
| return f"{num} B" | |
| def clean_name(name: str) -> str: | |
| name = unquote(name or "file") | |
| name = name.replace("/", "_").replace("\\", "_").replace("\x00", "") | |
| name = SAFE_NAME_RE.sub("_", name).strip(" ._") | |
| return name[:180] or "file" | |
| def extension_from_mime(mime_type: Optional[str], default: str = "") -> str: | |
| if not mime_type: | |
| return default | |
| overrides = { | |
| "image/jpeg": ".jpg", "audio/ogg": ".ogg", "video/mp4": ".mp4", | |
| "image/webp": ".webp", "application/x-tgsticker": ".tgs", | |
| "video/webm": ".webm", "application/gzip": ".gz", | |
| } | |
| return overrides.get(mime_type.lower()) or mimetypes.guess_extension(mime_type) or default | |
| def ensure_extension(name: str, mime_type: Optional[str] = None, default_ext: str = "") -> str: | |
| name = clean_name(name) | |
| if Path(name).suffix: | |
| return name | |
| ext = extension_from_mime(mime_type, default_ext) | |
| if ext and not ext.startswith("."): | |
| ext = "." + ext | |
| return clean_name(name + (ext or "")) | |
| def public_link(token: str, original_name: str) -> str: | |
| safe_name = quote(clean_name(original_name), safe="._-()") | |
| return f"{BASE_URL}/file/{token}/{safe_name}" if BASE_URL else f"/file/{token}/{safe_name}" | |
| def get_media_info(message: Message) -> Tuple[Optional[object], Optional[str], int]: | |
| 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 | |
| if not media: | |
| return None, None, 0 | |
| file_name = getattr(media, "file_name", None) | |
| file_size = getattr(media, "file_size", 0) or 0 | |
| mime_type = getattr(media, "mime_type", None) | |
| if message.photo: | |
| file_name = ensure_extension(file_name or f"photo_{message.id}", "image/jpeg", ".jpg") | |
| elif message.voice: | |
| file_name = ensure_extension(file_name or f"voice_{message.id}", mime_type or "audio/ogg", ".ogg") | |
| elif message.video_note: | |
| file_name = ensure_extension(file_name or f"video_note_{message.id}", mime_type or "video/mp4", ".mp4") | |
| elif message.sticker: | |
| if not file_name: | |
| if getattr(media, "is_animated", False): | |
| file_name = f"sticker_{message.id}.tgs" | |
| elif getattr(media, "is_video", False): | |
| file_name = f"sticker_{message.id}.webm" | |
| else: | |
| file_name = f"sticker_{message.id}.webp" | |
| file_name = ensure_extension(file_name, mime_type, Path(file_name).suffix or ".webp") | |
| elif message.video: | |
| file_name = ensure_extension(file_name or f"video_{message.id}", mime_type or "video/mp4", ".mp4") | |
| elif message.animation: | |
| file_name = ensure_extension(file_name or f"animation_{message.id}", mime_type or "video/mp4", ".mp4") | |
| elif message.audio: | |
| file_name = ensure_extension(file_name or f"audio_{message.id}", mime_type or "audio/mpeg", ".mp3") | |
| elif message.document: | |
| file_name = ensure_extension(file_name or f"file_{message.id}", mime_type, "") | |
| return media, clean_name(file_name or f"file_{message.id}"), file_size | |
| async def progress(current: int, total: int, status: Message, started: float, state: dict, label: str): | |
| now = time.time() | |
| if now - state.get("last", 0) < 3 and current != total: | |
| return | |
| state["last"] = now | |
| percent = current / total * 100 if total else 0 | |
| speed = current / max(now - started, 1) | |
| try: | |
| await status.edit_text(f"{label}\n{percent:.1f}% — {human_size(current)} / {human_size(total)}\nVelocidad: {human_size(int(speed))}/s") | |
| except Exception: | |
| pass | |
| async def debug_incoming(_, message: Message): | |
| 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)) | |
| async def start_cmd(_, message: Message): | |
| await message.reply_text( | |
| "👋 Estoy activo.\n\n" | |
| "Envíame archivo, video, foto, audio, sticker, GIF o nota y te doy un link directo del Hugging Face Space.\n\n" | |
| "También puedes enviarme un link de MediaFire: lo descargo, conservo el nombre original, te doy link y trato de reenviártelo." | |
| ) | |
| async def mediafire_handler(_, message: Message): | |
| url = MEDIAFIRE_RE.search(message.text or "").group(0).rstrip(").,;") | |
| status = await message.reply_text("⏳ Analizando link de MediaFire...") | |
| try: | |
| path, original_name, size = await download_mediafire(url, status) | |
| except Exception as exc: | |
| log.exception("Error descargando MediaFire") | |
| await status.edit_text(f"❌ No pude descargar ese MediaFire:\n`{exc}`") | |
| return | |
| token = path.name.split("_", 1)[0] | |
| link = public_link(token, original_name) | |
| caption = f"✅ MediaFire descargado\n📦 {original_name}\n📏 {human_size(size)}\n🔗 {link}" | |
| try: | |
| await status.edit_text("⬆️ Subiendo a Telegram...") | |
| 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...")) | |
| await status.delete() | |
| except Exception as exc: | |
| 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}`") | |
| async def media_handler(_, message: Message): | |
| media, original_name, file_size = get_media_info(message) | |
| if not media: | |
| await message.reply_text("❌ No pude detectar ese archivo.") | |
| return | |
| if file_size and file_size > MAX_FILE_MB * 1024 * 1024: | |
| await message.reply_text(f"❌ Archivo muy grande. Límite: {MAX_FILE_MB} MB.") | |
| return | |
| status = await message.reply_text("⏳ Descargando desde Telegram al servidor...") | |
| token = uuid.uuid4().hex | |
| path = DOWNLOAD_DIR / f"{token}_{original_name}" | |
| try: | |
| saved = await bot.download_media(message, file_name=str(path), progress=progress, progress_args=(status, time.time(), {"last": 0}, "⬇️ Descargando al servidor...")) | |
| if saved and Path(saved) != path: | |
| path = Path(saved) | |
| except Exception as exc: | |
| log.exception("Error descargando Telegram") | |
| await status.edit_text(f"❌ Error descargando:\n`{exc}`") | |
| return | |
| if not path.exists(): | |
| await status.edit_text("❌ La descarga falló o no se guardó.") | |
| return | |
| size = path.stat().st_size | |
| link = public_link(token, original_name) | |
| 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.") | |
| async def text_fallback(_, message: Message): | |
| await message.reply_text("✅ El bot está leyendo mensajes. Envíame un archivo/media o un link de MediaFire.") | |
| async def any_fallback(_, message: Message): | |
| if not message.text and not message.media: | |
| await message.reply_text("✅ Te leí, pero ese tipo de mensaje no lo puedo convertir.") | |
| def filename_from_headers_or_url(headers, url: str, fallback: str = "mediafire_file") -> str: | |
| cd = headers.get("Content-Disposition", "") if headers else "" | |
| content_type = headers.get("Content-Type", "").split(";", 1)[0].strip() if headers else "" | |
| if cd: | |
| msg = EmailMessage(); msg["content-disposition"] = cd | |
| filename = msg.get_filename() | |
| if filename: | |
| return ensure_extension(filename, content_type) | |
| name = Path(unquote(urlparse(str(url)).path)).name | |
| if not name or name.lower() in {"download", "file"}: | |
| name = fallback | |
| return ensure_extension(name, content_type) | |
| async def get_mediafire_direct_url(session: ClientSession, mediafire_url: str) -> str: | |
| async with session.get(mediafire_url, allow_redirects=True) as resp: | |
| text = await resp.text(errors="ignore") | |
| if resp.status >= 400: | |
| raise RuntimeError(f"MediaFire respondió HTTP {resp.status}") | |
| patterns = [ | |
| r'id=["\']downloadButton["\'][^>]+href=["\']([^"\']+)', | |
| r'href=["\'](https?://download[^"\']+mediafire[^"\']+)["\']', | |
| r'href=["\'](https?://[^"\']*mediafire\.com/[^"\']*/[^"\']+)["\']', | |
| ] | |
| for pat in patterns: | |
| m = re.search(pat, text, flags=re.I | re.S) | |
| if m: | |
| return html.unescape(m.group(1)) | |
| raise RuntimeError("No encontré el botón de descarga. Puede ser carpeta, privado o protegido.") | |
| async def download_mediafire(url: str, status: Message) -> Tuple[Path, str, int]: | |
| timeout = ClientTimeout(total=None, connect=45, sock_read=180) | |
| max_bytes = MAX_FILE_MB * 1024 * 1024 | |
| async with ClientSession(timeout=timeout, headers={"User-Agent": "Mozilla/5.0"}) as session: | |
| direct = await get_mediafire_direct_url(session, url) | |
| async with session.get(direct, allow_redirects=True) as resp: | |
| if resp.status >= 400: | |
| raise RuntimeError(f"HTTP {resp.status}") | |
| total = int(resp.headers.get("Content-Length", "0") or 0) | |
| if total and total > max_bytes: | |
| raise RuntimeError(f"Archivo demasiado grande. Límite: {MAX_FILE_MB} MB") | |
| original_name = filename_from_headers_or_url(resp.headers, str(resp.url), "mediafire_file") | |
| token = uuid.uuid4().hex | |
| path = DOWNLOAD_DIR / f"{token}_{original_name}" | |
| downloaded = 0; started = time.time(); state = {"last": 0} | |
| with path.open("wb") as f: | |
| async for chunk in resp.content.iter_chunked(1024 * 1024): | |
| if not chunk: | |
| continue | |
| downloaded += len(chunk) | |
| if downloaded > max_bytes: | |
| path.unlink(missing_ok=True) | |
| raise RuntimeError(f"Archivo demasiado grande. Límite: {MAX_FILE_MB} MB") | |
| f.write(chunk) | |
| await progress(downloaded, total, status, started, state, "⬇️ Descargando desde MediaFire...") | |
| return path, original_name, path.stat().st_size | |
| async def cleanup_loop(): | |
| while True: | |
| try: | |
| cutoff = time.time() - KEEP_HOURS * 3600 | |
| for p in DOWNLOAD_DIR.glob("*"): | |
| if p.is_file() and p.stat().st_mtime < cutoff: | |
| p.unlink(missing_ok=True) | |
| except Exception: | |
| log.exception("Error limpiando archivos") | |
| await asyncio.sleep(1800) | |
| _cleanup_task = None | |
| async def start_bot(): | |
| global _cleanup_task | |
| me = await bot.get_me() if bot.is_connected else None | |
| await bot.start() | |
| me = await bot.get_me() | |
| log.info("✅ Bot iniciado como @%s id=%s", me.username, me.id) | |
| _cleanup_task = asyncio.create_task(cleanup_loop()) | |
| async def stop_bot(): | |
| global _cleanup_task | |
| if _cleanup_task: | |
| _cleanup_task.cancel() | |
| if bot.is_connected: | |
| await bot.stop() | |
| log.info("Bot detenido") | |