Spaces:
Paused
Paused
Download modules/linkpack.py from saske560/userbotsaske: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/spaces/saske560/userbotsaske/resolve/main/modules/linkpack.py
- Command line
-
hf download hf://spaces/saske560/userbotsaske/modules/linkpack.py
-
curl -L -o linkpack.py https://huggingface.co/spaces/saske560/userbotsaske/resolve/main/modules/linkpack.py
16.8 kB
| import html | |
| import json | |
| import os | |
| import re | |
| import uuid | |
| from pathlib import Path | |
| from urllib.parse import urlparse | |
| BASE_TMP = Path(__file__).resolve().parent.parent / 'tmp' | |
| BASE_TMP.mkdir(parents=True, exist_ok=True) | |
| TG_LINK_RE = re.compile(r'(https?://t\.me/[^\s]+|t\.me/[^\s]+)', re.I) | |
| def _extract_link(text: str) -> str: | |
| if not text: | |
| return '' | |
| text = text.strip() | |
| match = TG_LINK_RE.search(text) | |
| return match.group(1) if match else text.split()[0] | |
| def _input_link(ctx) -> str: | |
| if ctx.args.strip(): | |
| return _extract_link(ctx.args.strip()) | |
| if ctx.reply: | |
| source = ctx.reply.text or ctx.reply.caption or '' | |
| return _extract_link(source) | |
| return '' | |
| def _normalize_url(link: str) -> str: | |
| link = (link or '').strip() | |
| if link and not link.startswith(('http://', 'https://')): | |
| link = 'https://' + link.lstrip('/') | |
| return link | |
| def _parse_message_link(link: str) -> dict: | |
| url = _normalize_url(link) | |
| parsed = urlparse(url) | |
| if parsed.netloc.lower() not in {'t.me', 'www.t.me'}: | |
| raise ValueError('El enlace no parece ser de Telegram.') | |
| parts = [p for p in parsed.path.split('/') if p] | |
| if not parts: | |
| raise ValueError('El enlace no contiene suficientes datos.') | |
| if parts[0] in {'joinchat', '+', 'addlist', 'proxy', 'socks'}: | |
| raise ValueError('Ese tipo de enlace no apunta a un mensaje concreto.') | |
| topic_id = None | |
| if parts[0] == 'c': | |
| if len(parts) < 3: | |
| raise ValueError('El enlace privado interno está incompleto.') | |
| internal_id = parts[1] | |
| if not internal_id.isdigit(): | |
| raise ValueError('No pude interpretar el ID interno del chat.') | |
| if len(parts) >= 4 and parts[2].isdigit() and parts[3].isdigit(): | |
| topic_id = int(parts[2]) | |
| message_id = int(parts[3]) | |
| else: | |
| message_id = int(parts[2]) | |
| chat_ref = int(f'-100{internal_id}') | |
| chat_hint = f'-100{internal_id}' | |
| access = 'interno' | |
| else: | |
| chat_ref = parts[0].lstrip('@') | |
| chat_hint = '@' + chat_ref | |
| if len(parts) < 2 or not parts[1].isdigit(): | |
| raise ValueError('Ese enlace no parece apuntar a un mensaje.') | |
| if len(parts) >= 3 and parts[1].isdigit() and parts[2].isdigit(): | |
| topic_id = int(parts[1]) | |
| message_id = int(parts[2]) | |
| else: | |
| message_id = int(parts[1]) | |
| access = 'público/username' | |
| return { | |
| 'url': url, | |
| 'chat_ref': chat_ref, | |
| 'chat_hint': chat_hint, | |
| 'message_id': message_id, | |
| 'topic_id': topic_id, | |
| 'access': access, | |
| } | |
| async def _resolve(ctx, link: str): | |
| meta = _parse_message_link(link) | |
| chat = await ctx.client.get_chat(meta['chat_ref']) | |
| msg = await ctx.client.get_messages(chat.id, meta['message_id']) | |
| if not msg: | |
| raise ValueError('No pude obtener ese mensaje con tu cuenta actual.') | |
| meta['chat'] = chat | |
| meta['message'] = msg | |
| return meta | |
| def _chat_name(chat) -> str: | |
| return chat.title or chat.first_name or chat.username or str(chat.id) | |
| def _sender_name(msg) -> str: | |
| if getattr(msg, 'from_user', None): | |
| full = ' '.join(x for x in [msg.from_user.first_name, msg.from_user.last_name] if x) | |
| return full or msg.from_user.username or str(msg.from_user.id) | |
| if getattr(msg, 'sender_chat', None): | |
| return msg.sender_chat.title or str(msg.sender_chat.id) | |
| return 'Desconocido' | |
| def _is_protected(chat, msg) -> bool: | |
| return bool( | |
| getattr(msg, 'has_protected_content', False) | |
| or getattr(chat, 'has_protected_content', False) | |
| or getattr(chat, 'noforwards', False) | |
| ) | |
| def _message_kind(msg) -> str: | |
| media = getattr(getattr(msg, 'media', None), 'value', None) | |
| return media or ('texto' if (msg.text or msg.caption) else 'servicio') | |
| def _message_text(msg) -> str: | |
| return (msg.text or msg.caption or '').strip() | |
| def _format_bytes(size) -> str: | |
| if not size: | |
| return '0 B' | |
| num = float(size) | |
| units = ['B', 'KB', 'MB', 'GB', 'TB'] | |
| for unit in units: | |
| if num < 1024 or unit == units[-1]: | |
| return f'{num:.2f} {unit}' if unit != 'B' else f'{int(num)} B' | |
| num /= 1024 | |
| return f'{int(size)} B' | |
| def _file_info(msg) -> dict: | |
| media_obj = None | |
| media_name = None | |
| for attr in ('document', 'video', 'audio', 'voice', 'animation', 'video_note', 'photo', 'sticker'): | |
| value = getattr(msg, attr, None) | |
| if value: | |
| media_obj = value | |
| media_name = attr | |
| break | |
| if not media_obj: | |
| return {'kind': _message_kind(msg), 'size': 0, 'name': None} | |
| return { | |
| 'kind': media_name, | |
| 'size': getattr(media_obj, 'file_size', 0) or 0, | |
| 'name': getattr(media_obj, 'file_name', None), | |
| 'mime': getattr(media_obj, 'mime_type', None), | |
| 'duration': getattr(media_obj, 'duration', None), | |
| 'width': getattr(media_obj, 'width', None), | |
| 'height': getattr(media_obj, 'height', None), | |
| } | |
| async def _send_downloaded(ctx, msg, src: str, caption: str): | |
| if msg.photo: | |
| await ctx.message.reply_photo(src, caption=caption or None, quote=False) | |
| elif msg.video: | |
| await ctx.message.reply_video(src, caption=caption or None, quote=False) | |
| elif msg.animation: | |
| await ctx.message.reply_animation(src, caption=caption or None, quote=False) | |
| elif msg.audio: | |
| await ctx.message.reply_audio(src, caption=caption or None, quote=False) | |
| elif msg.voice: | |
| await ctx.message.reply_voice(src, caption=caption or None, quote=False) | |
| elif msg.sticker: | |
| await ctx.message.reply_sticker(src, quote=False) | |
| if caption: | |
| await ctx.message.reply_text(caption, quote=False) | |
| elif msg.video_note: | |
| await ctx.message.reply_video_note(src, quote=False) | |
| if caption: | |
| await ctx.message.reply_text(caption, quote=False) | |
| else: | |
| await ctx.message.reply_document(src, caption=caption or None, quote=False) | |
| async def _cleanup(path): | |
| try: | |
| if path and Path(path).exists(): | |
| Path(path).unlink() | |
| except Exception: | |
| pass | |
| async def _need_resolve(ctx): | |
| raw = _input_link(ctx) | |
| if not raw: | |
| await ctx.respond('⚠️ Pásame un enlace de mensaje de Telegram o responde a uno.') | |
| return None | |
| try: | |
| return await _resolve(ctx, raw) | |
| except Exception as exc: | |
| await ctx.respond(f'⚠️ No pude resolver ese enlace.\n\n<code>{html.escape(str(exc))}</code>') | |
| return None | |
| def setup(registry): | |
| async def linkinfo_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| protected = _is_protected(chat, msg) | |
| body = _message_text(msg).replace('\n', ' ')[:180] or '[sin texto]' | |
| await ctx.respond( | |
| '🔗 <b>Info del enlace</b>\n\n' | |
| f'💬 <b>Chat:</b> {html.escape(_chat_name(chat))}\n' | |
| f'🆔 <b>Chat ID:</b> <code>{chat.id}</code>\n' | |
| f'📨 <b>Mensaje:</b> <code>{msg.id}</code>\n' | |
| f'🧵 <b>Tema:</b> <code>{data.get("topic_id")}</code>\n' | |
| f'📦 <b>Tipo:</b> <code>{html.escape(_message_kind(msg))}</code>\n' | |
| f'👤 <b>Autor:</b> {html.escape(_sender_name(msg))}\n' | |
| f'🔒 <b>Protegido:</b> <b>{"Sí" if protected else "No"}</b>\n' | |
| f'📝 <b>Vista previa:</b> {html.escape(body)}' | |
| ) | |
| async def linktext_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| if _is_protected(chat, msg): | |
| await ctx.respond('⛔ Ese mensaje pertenece a contenido protegido. No extraigo texto/caption desde ese enlace.') | |
| return | |
| text = _message_text(msg) | |
| if not text: | |
| await ctx.respond('🫥 Ese mensaje no trae texto ni caption.') | |
| return | |
| await ctx.respond(f'📝 <b>Texto del mensaje enlazado</b>\n\n<code>{html.escape(text[:3900])}</code>') | |
| async def linksave_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| if _is_protected(chat, msg): | |
| await ctx.respond('⛔ No copio mensajes protegidos a Guardados.') | |
| return | |
| await msg.copy('me') | |
| await ctx.respond('💾 <b>Mensaje enlazado copiado a Guardados</b>') | |
| async def linksend_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| if _is_protected(chat, msg): | |
| await ctx.respond('⛔ No copio mensajes protegidos al chat actual.') | |
| return | |
| await msg.copy(ctx.message.chat.id) | |
| await ctx.respond('📨 <b>Mensaje enlazado enviado en este chat</b>') | |
| async def linkdl_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| if _is_protected(chat, msg): | |
| await ctx.respond('⛔ El enlace apunta a contenido protegido. No lo descargo ni lo reenvío.') | |
| return | |
| if not getattr(msg, 'media', None): | |
| await ctx.respond('🫥 Ese mensaje no trae archivo ni media para descargar.') | |
| return | |
| tmp_name = str(BASE_TMP / f'link_{uuid.uuid4().hex}') | |
| src = await ctx.client.download_media(msg, file_name=tmp_name) | |
| caption = _message_text(msg) | |
| out_caption = f'📥 <b>Media obtenida desde enlace</b>' | |
| if caption: | |
| out_caption += f'\n\n{html.escape(caption[:900])}' | |
| try: | |
| await _send_downloaded(ctx, msg, src, out_caption) | |
| await ctx.respond('✅ <b>Media enviada desde el enlace</b>') | |
| finally: | |
| await _cleanup(src) | |
| async def linkmedia_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| info = _file_info(data['message']) | |
| await ctx.respond( | |
| '🎞️ <b>Media del enlace</b>\n\n' | |
| f'📦 <b>Tipo:</b> <code>{html.escape(str(info.get("kind")))}</code>\n' | |
| f'📛 <b>Nombre:</b> <code>{html.escape(str(info.get("name")))}</code>\n' | |
| f'🧪 <b>MIME:</b> <code>{html.escape(str(info.get("mime")))}</code>\n' | |
| f'⚖️ <b>Tamaño:</b> <code>{_format_bytes(info.get("size"))}</code>\n' | |
| f'⏱️ <b>Duración:</b> <code>{info.get("duration")}</code>\n' | |
| f'🖼️ <b>Resolución:</b> <code>{info.get("width")}x{info.get("height")}</code>' | |
| ) | |
| async def linkjson_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| payload = { | |
| 'chat_id': chat.id, | |
| 'chat_title': _chat_name(chat), | |
| 'message_id': msg.id, | |
| 'topic_id': data.get('topic_id'), | |
| 'sender': _sender_name(msg), | |
| 'kind': _message_kind(msg), | |
| 'protected': _is_protected(chat, msg), | |
| 'text': _message_text(msg), | |
| 'link': getattr(msg, 'link', None), | |
| 'media': _file_info(msg), | |
| } | |
| out = json.dumps(payload, ensure_ascii=False, indent=2)[:3900] | |
| await ctx.respond(f'🧩 <b>JSON del enlace</b>\n\n<code>{html.escape(out)}</code>') | |
| async def linkprotect_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| protected = _is_protected(chat, msg) | |
| await ctx.respond( | |
| '🔐 <b>Chequeo de protección</b>\n\n' | |
| f'💬 <b>Chat protegido:</b> <b>{"Sí" if (getattr(chat, "has_protected_content", False) or getattr(chat, "noforwards", False)) else "No"}</b>\n' | |
| f'📨 <b>Mensaje protegido:</b> <b>{"Sí" if getattr(msg, "has_protected_content", False) else "No"}</b>\n' | |
| f'🧷 <b>Resultado:</b> <b>{"PROTEGIDO" if protected else "VISIBLE"}</b>' | |
| ) | |
| async def linkauthor_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| msg = data['message'] | |
| sender = getattr(msg, 'from_user', None) | |
| sender_chat = getattr(msg, 'sender_chat', None) | |
| if sender: | |
| username = '@' + sender.username if sender.username else 'Sin username' | |
| name = ' '.join(x for x in [sender.first_name, sender.last_name] if x) or 'Sin nombre' | |
| await ctx.respond( | |
| '👤 <b>Autor del mensaje enlazado</b>\n\n' | |
| f'🧾 <b>Nombre:</b> {html.escape(name)}\n' | |
| f'🔗 <b>Username:</b> {html.escape(username)}\n' | |
| f'🆔 <b>ID:</b> <code>{sender.id}</code>' | |
| ) | |
| return | |
| if sender_chat: | |
| await ctx.respond( | |
| '📣 <b>Chat emisor del mensaje enlazado</b>\n\n' | |
| f'🧾 <b>Nombre:</b> {html.escape(sender_chat.title or "Sin nombre")}\n' | |
| f'🆔 <b>ID:</b> <code>{sender_chat.id}</code>' | |
| ) | |
| return | |
| await ctx.respond('🤷 No pude identificar un autor concreto para ese mensaje.') | |
| async def linktopic_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| msg = data['message'] | |
| top = getattr(msg, 'reply_to_top_message_id', None) | |
| await ctx.respond( | |
| '🧵 <b>Datos de tema/hilo</b>\n\n' | |
| f'🔗 <b>Tema del enlace:</b> <code>{data.get("topic_id")}</code>\n' | |
| f'📌 <b>reply_to_top_message_id:</b> <code>{top}</code>\n' | |
| f'📨 <b>Mensaje actual:</b> <code>{msg.id}</code>' | |
| ) | |
| async def linkfile_cmd(ctx): | |
| data = await _need_resolve(ctx) | |
| if not data: | |
| return | |
| chat = data['chat'] | |
| msg = data['message'] | |
| if _is_protected(chat, msg): | |
| await ctx.respond('⛔ Ese enlace apunta a contenido protegido. No preparo archivo externo desde ahí.') | |
| return | |
| payload = { | |
| 'chat_id': chat.id, | |
| 'message_id': msg.id, | |
| 'chat': _chat_name(chat), | |
| 'kind': _message_kind(msg), | |
| 'text': _message_text(msg), | |
| 'media': _file_info(msg), | |
| } | |
| out = BASE_TMP / f'linkmeta_{uuid.uuid4().hex}.json' | |
| out.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding='utf-8') | |
| try: | |
| await ctx.message.reply_document(str(out), caption='🗂️ <b>Metadatos del enlace</b>', quote=False) | |
| await ctx.respond('✅ <b>Archivo JSON del enlace enviado</b>') | |
| finally: | |
| await _cleanup(out) | |
| registry.add('linkinfo', linkinfo_cmd, 'Muestra info básica de un mensaje por enlace.', usage='.linkinfo https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linktext', linktext_cmd, 'Saca el texto/caption de un enlace accesible y no protegido.', usage='.linktext https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linksave', linksave_cmd, 'Copia a Guardados un mensaje enlazado no protegido.', usage='.linksave https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linksend', linksend_cmd, 'Envía al chat actual un mensaje enlazado no protegido.', usage='.linksend https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linkdl', linkdl_cmd, 'Descarga y reenvía la media de un enlace accesible y no protegido.', usage='.linkdl https://t.me/usuario/123', aliases=['getlink'], category='Telegram+') | |
| registry.add('linkmedia', linkmedia_cmd, 'Muestra datos técnicos de la media del enlace.', usage='.linkmedia https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linkjson', linkjson_cmd, 'Muestra JSON resumido del mensaje enlazado.', usage='.linkjson https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linkprotect', linkprotect_cmd, 'Revisa si un enlace apunta a contenido protegido.', usage='.linkprotect https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linkauthor', linkauthor_cmd, 'Muestra el autor/chat emisor del mensaje enlazado.', usage='.linkauthor https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linktopic', linktopic_cmd, 'Muestra datos del tema/hilo de un enlace.', usage='.linktopic https://t.me/usuario/123', category='Telegram+') | |
| registry.add('linkfile', linkfile_cmd, 'Genera un JSON descargable con metadatos del enlace.', usage='.linkfile https://t.me/usuario/123', category='Telegram+') | |