Download main.py from o7c1/tgtobl1: direct link, hf CLI and curl.
- Browser
- Download file 36.6 kB
-
https://huggingface.co/spaces/o7c1/tgtobl1/resolve/main/main.py
- Command line
-
hf download hf://spaces/o7c1/tgtobl1/main.py
-
curl -L -o main.py https://huggingface.co/spaces/o7c1/tgtobl1/resolve/main/main.py
36.6 kB
| import os | |
| import asyncio | |
| import tempfile | |
| import zipfile | |
| import httpx | |
| import shutil | |
| import re | |
| import secrets | |
| import html | |
| from datetime import datetime | |
| from collections import deque | |
| from contextlib import asynccontextmanager | |
| from telethon import TelegramClient, events | |
| from telethon.sessions import StringSession | |
| from telethon.errors import AuthKeyDuplicatedError | |
| from fastapi import FastAPI | |
| import uvicorn | |
| import gradio as gr | |
| # Disable Gradio SSR proxying | |
| os.environ["GRADIO_SSR_MODE"] = "false" | |
| def get_env(name): | |
| return os.getenv(name) | |
| # ========================================== | |
| # 1. COMMON TELEGRAM CONFIGURATION | |
| # ========================================== | |
| TG_API_ID = int(get_env("TG_API_ID") or 0) | |
| TG_API_HASH = get_env("TG_API_HASH") | |
| TG_SESSION_STRING = get_env("TG_SESSION_STRING") | |
| # ========================================== | |
| # 2. BOT 1 CONFIGURATION (Standard Relay) | |
| # ========================================== | |
| BALE_BOT_TOKEN_1 = get_env("BALE_BOT_TOKEN") | |
| BALE_CHAT_ID_1 = get_env("BALE_CHAT_ID") | |
| BALE_LOG_CHAT_ID_1 = get_env("BALE_LOG_CHAT_ID") or BALE_CHAT_ID_1 | |
| env_channels_1 = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()] | |
| TARGET_CHANNELS_1 = list(set(env_channels_1)) | |
| # ========================================== | |
| # 3. BOT 2 CONFIGURATION (Filtered/Obfuscated) | |
| # ========================================== | |
| BALE_BOT_TOKEN_2 = get_env("BALE_BOT_TOKEN_2") | |
| bale_ids_raw_2 = get_env("BALE_CHAT_IDS") or get_env("BALE_CHAT_ID_2") | |
| if bale_ids_raw_2: | |
| BALE_CHAT_IDS_2 = [x.strip() for x in bale_ids_raw_2.split(",") if x.strip()] | |
| else: | |
| BALE_CHAT_IDS_2 = [] | |
| BALE_LOG_CHAT_ID_2 = get_env("BALE_LOG_CHAT_ID_2") or (BALE_CHAT_IDS_2[0] if BALE_CHAT_IDS_2 else None) | |
| env_channels_2 = [c.strip().lower() for c in (get_env("TARGET_CHANNELS_2") or "").split(",") if c.strip()] | |
| TARGET_CHANNELS_2 = list(set(env_channels_2 + ["iu39f", "tirexnet", "xsfilterrnet"])) | |
| FILTER_EXPR = get_env("FILTER_EXPR") or "" | |
| REMOVE_WORDS = [w.strip().lower() for w in (get_env("REMOVE_WORDS") or "").split(",") if w.strip()] | |
| # Constants | |
| CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB | |
| MAX_TEXT_LEN = 4000 | |
| DUMMY_BYTE_COUNT = 64 | |
| LARGE_FILE_SEMAPHORE = asyncio.Semaphore(2) | |
| BALE_API_SEMAPHORE = asyncio.Semaphore(4) | |
| LOG_BUFFER = deque(maxlen=250) | |
| TELEGRAM_STATUS = "Stopped" | |
| TELEGRAM_ERROR = None | |
| def add_log(msg: str): | |
| timestamp = datetime.now().strftime("%H:%M:%S") | |
| entry = f"[{timestamp}] {msg}" | |
| LOG_BUFFER.append(entry) | |
| print(entry) | |
| # ========================================== | |
| # 4. FILTER EXPRESSION PARSER (For Bot 2) | |
| # ========================================== | |
| class FilterExpr: | |
| def __init__(self, expr_str: str): | |
| self.ast = None | |
| if not expr_str.strip(): | |
| return | |
| try: | |
| tokens = self._tokenize(expr_str) | |
| tokens = self._insert_and_operators(tokens) | |
| self.ast = self._parse(tokens) | |
| except Exception as e: | |
| add_log(f"Invalid FILTER_EXPR: {e}") | |
| self.ast = None | |
| def _tokenize(self, s): | |
| token_re = re.compile(r'\(|\)|!|\||"[^"]*"|[^\s()!|"]+') | |
| raw_tokens = token_re.findall(s) | |
| typed = [] | |
| for t in raw_tokens: | |
| if t == '(': | |
| typed.append(('LPAREN', t)) | |
| elif t == ')': | |
| typed.append(('RPAREN', t)) | |
| elif t == '!': | |
| typed.append(('NOT', t)) | |
| elif t == '|': | |
| typed.append(('OR', t)) | |
| elif t.startswith('"') and t.endswith('"'): | |
| typed.append(('WORD', t[1:-1].lower())) | |
| else: | |
| typed.append(('WORD', t.lower())) | |
| return typed | |
| def _insert_and_operators(self, tokens): | |
| if not tokens: | |
| return [] | |
| terminators = {'WORD', 'RPAREN'} | |
| starters = {'WORD', 'LPAREN', 'NOT'} | |
| result = [tokens[0]] | |
| for i in range(1, len(tokens)): | |
| prev = tokens[i-1] | |
| curr = tokens[i] | |
| if prev[0] in terminators and curr[0] in starters: | |
| result.append(('AND', '&')) | |
| result.append(curr) | |
| return result | |
| def _parse(self, tokens): | |
| self._pos = 0 | |
| self._tokens = tokens | |
| ast = self._expr() | |
| if self._pos != len(self._tokens): | |
| raise ValueError(f"Unexpected token: {self._current()}") | |
| return ast | |
| def _current(self): | |
| return self._tokens[self._pos] if self._pos < len(self._tokens) else None | |
| def _advance(self): | |
| self._pos += 1 | |
| def _expr(self): | |
| left = self._term() | |
| while self._current() and self._current()[0] == 'OR': | |
| self._advance() | |
| right = self._term() | |
| left = ('OR', left, right) | |
| return left | |
| def _term(self): | |
| left = self._factor() | |
| while self._current() and self._current()[0] == 'AND': | |
| self._advance() | |
| right = self._factor() | |
| left = ('AND', left, right) | |
| return left | |
| def _factor(self): | |
| if self._current() and self._current()[0] == 'NOT': | |
| self._advance() | |
| child = self._factor() | |
| return ('NOT', child) | |
| return self._atom() | |
| def _atom(self): | |
| tok = self._current() | |
| if not tok: | |
| raise ValueError("Unexpected end of expression") | |
| if tok[0] == 'LPAREN': | |
| self._advance() | |
| node = self._expr() | |
| if not self._current() or self._current()[0] != 'RPAREN': | |
| raise ValueError("Missing )") | |
| self._advance() | |
| return node | |
| elif tok[0] == 'WORD': | |
| self._advance() | |
| return ('WORD', tok[1]) | |
| else: | |
| raise ValueError(f"Unexpected token: {tok}") | |
| def evaluate(self, text: str) -> bool: | |
| if self.ast is None: | |
| return True | |
| return self._eval_node(self.ast, text.lower()) | |
| def _eval_node(self, node, text): | |
| node_type = node[0] | |
| if node_type == 'WORD': | |
| return node[1] in text | |
| elif node_type == 'AND': | |
| return self._eval_node(node[1], text) and self._eval_node(node[2], text) | |
| elif node_type == 'OR': | |
| return self._eval_node(node[1], text) or self._eval_node(node[2], text) | |
| elif node_type == 'NOT': | |
| return not self._eval_node(node[1], text) | |
| return False | |
| msg_filter = FilterExpr(FILTER_EXPR) | |
| def remove_words(text: str, words: list) -> str: | |
| if not words or not text: | |
| return text | |
| for w in words: | |
| text = re.sub(re.escape(w), '', text, flags=re.IGNORECASE) | |
| return text | |
| # ========================================== | |
| # 5. GENERAL FILE & TEXT HELPERS | |
| # ========================================== | |
| def split_long_text(text, max_len=MAX_TEXT_LEN): | |
| if len(text) <= max_len: | |
| return [text] | |
| chunks = [] | |
| while text: | |
| if len(text) <= max_len: | |
| chunks.append(text) | |
| break | |
| split_at = text.rfind('\n', 0, max_len) | |
| if split_at == -1: | |
| split_at = text.rfind(' ', 0, max_len) | |
| if split_at == -1: | |
| split_at = max_len | |
| chunk = text[:split_at].rstrip() | |
| text = text[split_at:].lstrip() | |
| if not chunk: | |
| chunk = text[:max_len] | |
| text = text[max_len:] | |
| chunks.append(chunk) | |
| return chunks | |
| def create_temp_dir(): | |
| return tempfile.mkdtemp(prefix="tg2bale_") | |
| def cleanup_temp_dir(temp_dir): | |
| try: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| except Exception: | |
| pass | |
| def zip_file_sync(file_path, zip_path): | |
| with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: | |
| zf.write(file_path, arcname=os.path.basename(file_path)) | |
| return zip_path | |
| async def zip_file(file_path, zip_path): | |
| return await asyncio.to_thread(zip_file_sync, file_path, zip_path) | |
| def split_file_sync(file_path, chunk_size=CHUNK_SIZE, suffix=".dat"): | |
| chunk_paths = [] | |
| base = file_path + ".part" | |
| with open(file_path, "rb") as f: | |
| i = 0 | |
| while True: | |
| chunk_data = f.read(chunk_size) | |
| if not chunk_data: | |
| break | |
| chunk_path = f"{base}{i:03d}{suffix}" | |
| with open(chunk_path, "wb") as chunk_file: | |
| chunk_file.write(chunk_data) | |
| chunk_paths.append(chunk_path) | |
| i += 1 | |
| return chunk_paths | |
| async def split_file(file_path, chunk_size=CHUNK_SIZE, suffix=".dat"): | |
| return await asyncio.to_thread(split_file_sync, file_path, chunk_size, suffix) | |
| async def download_media(message, temp_dir): | |
| if not message.media: | |
| return None | |
| try: | |
| suffix = "" | |
| if message.photo: | |
| suffix = ".jpg" | |
| elif message.video: | |
| suffix = ".mp4" | |
| elif getattr(message, 'document', None): | |
| for attr in message.document.attributes: | |
| if hasattr(attr, 'file_name') and '.' in attr.file_name: | |
| suffix = f".{attr.file_name.split('.')[-1]}" | |
| break | |
| if not suffix and message.document.mime_type and '/' in message.document.mime_type: | |
| suffix = f".{message.document.mime_type.split('/')[-1]}" | |
| elif message.audio: | |
| suffix = ".mp3" | |
| elif message.voice: | |
| suffix = ".ogg" | |
| elif message.sticker: | |
| suffix = ".webp" | |
| elif message.video_note: | |
| suffix = ".mp4" | |
| file_path = os.path.join(temp_dir, f"media{suffix}") | |
| await message.download_media(file=file_path) | |
| return file_path | |
| except Exception as e: | |
| add_log(f"Media download error: {e}") | |
| return None | |
| def get_message_link(event, chat): | |
| username = getattr(chat, 'username', None) | |
| if username: | |
| return f"https://t.me/{username}/{event.message.id}" | |
| if getattr(chat, 'id', None): | |
| return f"https://t.me/c/{abs(chat.id)}/{event.message.id}" | |
| return "" | |
| # ========================================== | |
| # 6. UNIVERSAL BALE SENDER FUNCTIONS | |
| # ========================================== | |
| async def send_text_to_bale_targets(bot_token, chat_ids, text, parse_mode=None, retries=3): | |
| if not bot_token or not chat_ids: | |
| return False | |
| overall = True | |
| for chat_id in chat_ids: | |
| url = f"https://tapi.bale.ai/bot{bot_token}/sendMessage" | |
| payload = {"chat_id": chat_id, "text": text} | |
| if parse_mode: | |
| payload["parse_mode"] = parse_mode | |
| sent = False | |
| for attempt in range(1, retries + 1): | |
| try: | |
| async with BALE_API_SEMAPHORE: | |
| async with httpx.AsyncClient() as client: | |
| resp = await client.post(url, json=payload, timeout=10) | |
| if resp.status_code == 200: | |
| sent = True | |
| break | |
| if attempt < retries: | |
| await asyncio.sleep(2 ** (attempt - 1)) | |
| except Exception: | |
| if attempt < retries: | |
| await asyncio.sleep(2 ** (attempt - 1)) | |
| if not sent: | |
| overall = False | |
| return overall | |
| async def send_media_to_bale_targets(bot_token, chat_ids, file_path, caption, media_type, parse_mode=None, upload_filename=None, retries=3): | |
| if not bot_token or not chat_ids: | |
| return False | |
| endpoint_map = { | |
| "photo": "sendPhoto", | |
| "video": "sendVideo", | |
| "document": "sendDocument", | |
| "audio": "sendAudio", | |
| "voice": "sendVoice", | |
| "sticker": "sendSticker", | |
| "video_note": "sendVideoNote", | |
| } | |
| endpoint = endpoint_map.get(media_type, "sendDocument") | |
| field_name = media_type if media_type in endpoint_map else "document" | |
| overall = True | |
| for chat_id in chat_ids: | |
| url = f"https://tapi.bale.ai/bot{bot_token}/{endpoint}" | |
| data = {"chat_id": chat_id} | |
| if caption: | |
| data["caption"] = caption | |
| if parse_mode: | |
| data["parse_mode"] = parse_mode | |
| sent = False | |
| for attempt in range(1, retries + 1): | |
| try: | |
| cur_filename = upload_filename | |
| if cur_filename and attempt > 1 and '/' in cur_filename: | |
| cur_filename = cur_filename.replace('/', '-') | |
| with open(file_path, "rb") as f: | |
| files = {field_name: (cur_filename, f)} if cur_filename else {field_name: f} | |
| async with BALE_API_SEMAPHORE: | |
| async with httpx.AsyncClient() as client: | |
| resp = await client.post(url, data=data, files=files, timeout=30) | |
| if resp.status_code == 200: | |
| sent = True | |
| break | |
| if attempt < retries: | |
| await asyncio.sleep(2 ** (attempt - 1)) | |
| except Exception: | |
| if attempt < retries: | |
| await asyncio.sleep(2 ** (attempt - 1)) | |
| if not sent: | |
| overall = False | |
| return overall | |
| async def send_text_or_caption_bale(bot_token, chat_ids, text, parse_mode="HTML", is_caption=False, max_len=MAX_TEXT_LEN): | |
| if not text: | |
| return ("" if is_caption else True) | |
| if len(text) > max_len and parse_mode: | |
| parse_mode = None | |
| chunks = split_long_text(text, max_len) | |
| total = len(chunks) | |
| if is_caption: | |
| first_chunk = chunks[0] | |
| if total == 1: | |
| return first_chunk, True | |
| first_chunk = first_chunk + f"\n⦠(1/{total})" | |
| success = True | |
| for i in range(1, total): | |
| chunk_text = f"{chunks[i]}\n⦠({i+1}/{total})" | |
| ok = await send_text_to_bale_targets(bot_token, chat_ids, chunk_text, parse_mode=None) | |
| if not ok: | |
| success = False | |
| await asyncio.sleep(0.5) | |
| return first_chunk, success | |
| success = True | |
| for i, chunk in enumerate(chunks, 1): | |
| if total > 1: | |
| chunk = f"{chunk}\n⦠({i}/{total})" | |
| ok = await send_text_to_bale_targets(bot_token, chat_ids, chunk, parse_mode=parse_mode) | |
| if not ok: | |
| success = False | |
| if i < total: | |
| await asyncio.sleep(0.5) | |
| return success | |
| async def log_to_bale(bot_token, log_chat_id, message, bot_tag="Bot"): | |
| add_log(f"[{bot_tag}] {message}") | |
| if not bot_token or not log_chat_id: | |
| return | |
| url = f"https://tapi.bale.ai/bot{bot_token}/sendMessage" | |
| payload = {"chat_id": log_chat_id, "text": f"π§ [{bot_tag} Log]:\n{message}"} | |
| try: | |
| async with httpx.AsyncClient() as client: | |
| await client.post(url, json=payload, timeout=5) | |
| except Exception: | |
| pass | |
| # ========================================== | |
| # 7. BOT 1 HANDLERS (Standard) | |
| # ========================================== | |
| def detect_media_type_bot1(event): | |
| if event.photo: return "photo" | |
| if event.video: return "video" | |
| if event.audio: return "audio" | |
| if event.voice: return "voice" | |
| if event.sticker: return "sticker" | |
| if event.video_note: return "video_note" | |
| if event.document: return "document" | |
| return None | |
| def get_media_size_bot1(event): | |
| try: | |
| if event.photo: return event.photo.sizes[-1].size | |
| if event.video: return event.video.size | |
| if event.audio: return event.audio.size | |
| if event.voice: return event.voice.size | |
| if event.video_note: return event.video_note.size | |
| if event.sticker: return getattr(event.sticker, 'size', None) | |
| if event.document: return event.document.size | |
| except Exception: | |
| pass | |
| return None | |
| def build_caption_bot1(event, chat): | |
| msg_text = event.raw_text or "" | |
| msg_link = get_message_link(event, chat) | |
| preview_url = "" | |
| if event.message and event.message.web_preview and event.message.web_preview.url: | |
| preview_url = event.message.web_preview.url | |
| parts = [] | |
| if msg_text: | |
| parts.append(msg_text) | |
| if preview_url: | |
| parts.append(f'<a href="{preview_url}">{preview_url}</a>') | |
| if msg_link: | |
| parts.append(f'<a href="{msg_link}">π Open in Telegram</a>') | |
| return "\n\n".join(parts) | |
| async def handle_large_document_bot1(event, media_path, final_caption, temp_dir): | |
| file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0 | |
| await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"Large file: {os.path.basename(media_path)}, size={file_size/(1024*1024):.1f} MB", "Bot-1") | |
| zip_path = os.path.join(temp_dir, "media.zip") | |
| await zip_file(media_path, zip_path) | |
| zip_size = os.path.getsize(zip_path) | |
| chat_ids = [BALE_CHAT_ID_1] | |
| if zip_size > CHUNK_SIZE: | |
| chunks = await split_file(zip_path, CHUNK_SIZE, suffix=".zip") | |
| total = len(chunks) | |
| await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"ZIP split into {total} chunks", "Bot-1") | |
| for idx, chunk_path in enumerate(chunks, start=1): | |
| part_caption = f"{final_caption}\nπ¦ Part {idx}/{total}" | |
| first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, part_caption, parse_mode="HTML", is_caption=True) | |
| success = await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, chunk_path, first_part, "document", parse_mode="HTML") | |
| if not success: | |
| await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, chunk_path, first_part, "document", parse_mode=None) | |
| await asyncio.sleep(1.5) | |
| else: | |
| first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML", is_caption=True) | |
| await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, zip_path, first_part, "document", parse_mode="HTML") | |
| async def process_bot1(event, chat, username): | |
| header = f"π’ @{username}\n\n" if username else f"π’ {chat.title}\n\n" | |
| caption_body = build_caption_bot1(event, chat) | |
| final_caption = header + caption_body | |
| media_type = detect_media_type_bot1(event) | |
| chat_ids = [BALE_CHAT_ID_1] | |
| if not media_type: | |
| await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML") | |
| return | |
| media_size = get_media_size_bot1(event) | |
| if media_size and media_size > CHUNK_SIZE: | |
| async with LARGE_FILE_SEMAPHORE: | |
| temp_dir = create_temp_dir() | |
| try: | |
| await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"Large {media_type} from {username or chat.title}: {media_size/(1024*1024):.1f} MB", "Bot-1") | |
| media_path = await download_media(event, temp_dir) | |
| if media_path: | |
| await handle_large_document_bot1(event, media_path, final_caption, temp_dir) | |
| finally: | |
| cleanup_temp_dir(temp_dir) | |
| return | |
| temp_dir = create_temp_dir() | |
| try: | |
| media_path = await download_media(event, temp_dir) | |
| if media_path: | |
| first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML", is_caption=True) | |
| success = await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, media_path, first_caption, media_type, parse_mode="HTML") | |
| if not success: | |
| zip_path = os.path.join(temp_dir, "fallback.zip") | |
| await zip_file(media_path, zip_path) | |
| await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, zip_path, first_caption, "document", parse_mode=None) | |
| finally: | |
| cleanup_temp_dir(temp_dir) | |
| # ========================================== | |
| # 8. BOT 2 HANDLERS (Filtering & Obfuscation) | |
| # ========================================== | |
| def is_audio_or_video_bot2(event) -> bool: | |
| if event.video or event.audio or event.voice or event.video_note: | |
| return True | |
| if event.document: | |
| mime = getattr(event.document, 'mime_type', '') or '' | |
| if mime.startswith('video/') or mime.startswith('audio/'): | |
| return True | |
| for attr in getattr(event.document, 'attributes', []): | |
| fname = getattr(attr, 'file_name', '') | |
| if fname: | |
| ext = fname.lower().split('.')[-1] | |
| if ext in {'mp4', 'mkv', 'avi', 'mov', 'flv', 'wmv', 'webm', '3gp', | |
| 'mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'opus'}: | |
| return True | |
| return False | |
| def is_image_bot2(event) -> bool: | |
| if event.photo or event.sticker: | |
| return True | |
| if event.document: | |
| mime = getattr(event.document, 'mime_type', '') or '' | |
| if mime.startswith('image/'): | |
| return True | |
| for attr in getattr(event.document, 'attributes', []): | |
| fname = getattr(attr, 'file_name', '') | |
| if fname: | |
| ext = fname.lower().split('.')[-1] | |
| if ext in {'jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'svg', 'ico'}: | |
| return True | |
| return False | |
| def obfuscate_suffix(suffix: str) -> str: | |
| clean = suffix.lstrip('.').strip().lower() | |
| if not clean: | |
| clean = "bin" | |
| if len(clean) == 1: | |
| return f"*{clean}/" | |
| elif len(clean) == 2: | |
| return f"{clean[0]}*/{clean[1]}" | |
| else: | |
| res = [] | |
| for i, c in enumerate(clean): | |
| res.append(c) | |
| if i < len(clean) - 1: | |
| res.append('*' if i % 2 == 0 else '/') | |
| s = "".join(res) | |
| if '/' not in s: s += "/" | |
| if '*' not in s: s = "*" + s | |
| return s | |
| def inject_dummy_bytes(src_path: str, dst_path: str, count: int = DUMMY_BYTE_COUNT): | |
| dummy = os.urandom(count) | |
| with open(src_path, "rb") as f_in, open(dst_path, "wb") as f_out: | |
| f_out.write(dummy) | |
| shutil.copyfileobj(f_in, f_out) | |
| def get_original_file_info(event): | |
| orig_name = None | |
| orig_ext = "" | |
| if getattr(event, 'document', None): | |
| for attr in event.document.attributes: | |
| if hasattr(attr, 'file_name') and attr.file_name: | |
| orig_name = attr.file_name | |
| break | |
| if orig_name and '.' in orig_name: | |
| orig_ext = orig_name.rsplit('.', 1)[-1] | |
| elif event.document.mime_type and '/' in event.document.mime_type: | |
| orig_ext = event.document.mime_type.split('/')[-1] | |
| if not orig_ext: | |
| orig_ext = "bin" | |
| return orig_name, orig_ext.lower() | |
| def extract_hyperlinks(event, text: str = "") -> list: | |
| urls = [] | |
| seen = set() | |
| def add_url(u): | |
| u = u.strip() | |
| if u and u not in seen: | |
| seen.add(u) | |
| urls.append(u) | |
| if event.message and event.message.entities: | |
| for ent in event.message.entities: | |
| if hasattr(ent, 'url') and ent.url: | |
| add_url(ent.url) | |
| elif ent.__class__.__name__ == 'MessageEntityUrl': | |
| raw = event.raw_text or "" | |
| u = raw[ent.offset: ent.offset + ent.length] | |
| add_url(u) | |
| if event.message and event.message.web_preview and event.message.web_preview.url: | |
| add_url(event.message.web_preview.url) | |
| if text: | |
| for u in re.findall(r'(https?://[^\s<>"\']+)', text): | |
| add_url(u) | |
| return urls | |
| def build_full_caption_bot2(event, chat, cleaned_text: str = None, deobf_info: str = None) -> str: | |
| parts = [] | |
| username = getattr(chat, 'username', None) | |
| title = getattr(chat, 'title', None) | |
| if username: | |
| parts.append(f"π’ <b>Channel:</b> @{username}\nπ https://t.me/{username}") | |
| elif title: | |
| parts.append(f"π’ <b>Channel:</b> {html.escape(title)}") | |
| body = cleaned_text if cleaned_text is not None else (event.raw_text or "") | |
| if body.strip(): | |
| parts.append(html.escape(body.strip())) | |
| urls = extract_hyperlinks(event, body) | |
| post_link = get_message_link(event, chat) | |
| link_lines = [] | |
| if post_link and post_link not in urls: | |
| link_lines.append(f'β’ <a href="{post_link}">π Open in Telegram</a>') | |
| for u in urls: | |
| escaped_u = html.escape(u) | |
| link_lines.append(f'β’ <a href="{escaped_u}">{escaped_u}</a>') | |
| if link_lines: | |
| parts.append("π <b>Links:</b>\n" + "\n".join(link_lines)) | |
| if deobf_info: | |
| parts.append(deobf_info) | |
| return "\n\n".join(parts) | |
| def build_deobfuscation_instructions(original_ext: str, obfuscated_suffix: str) -> str: | |
| return ( | |
| f"π <b>Deobfuscation Instructions:</b>\n" | |
| f"β’ <b>Original Extension:</b> <code>.{original_ext}</code> (Obfuscated: <code>{obfuscated_suffix}</code>)\n" | |
| f"β’ <b>Restore Steps:</b>\n" | |
| f" 1. Remove first {DUMMY_BYTE_COUNT} dummy bytes.\n" | |
| f" 2. Rename suffix <code>{obfuscated_suffix}</code> back to <code>.{original_ext}</code>\n" | |
| f"β’ <i>One-line command (Linux/Mac/Python):</i>\n" | |
| f"<code>python -c \"open('restored.{original_ext}','wb').write(open('INPUT_FILE','rb').read()[{DUMMY_BYTE_COUNT}:])\"</code>" | |
| ) | |
| async def handle_large_document_bot2(event, media_path, final_caption, temp_dir, upload_filename=None): | |
| file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0 | |
| display_name = upload_filename or os.path.basename(media_path) | |
| await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Large file: {display_name}, size={file_size/(1024*1024):.1f} MB", "Bot-2") | |
| target_path = media_path | |
| target_size = os.path.getsize(target_path) | |
| if target_size > CHUNK_SIZE: | |
| chunks = await split_file(target_path, CHUNK_SIZE, suffix=".dat") | |
| total = len(chunks) | |
| await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Split into {total} parts", "Bot-2") | |
| for idx, chunk_path in enumerate(chunks, start=1): | |
| chunk_display_name = f"{display_name}.part{idx:03d}" | |
| part_caption = f"{final_caption}\n\nπ¦ <b>Part {idx}/{total}</b>" | |
| first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, part_caption, parse_mode="HTML", is_caption=True) | |
| success = await send_media_to_bale_targets( | |
| BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, chunk_path, first_part, "document", | |
| parse_mode="HTML", upload_filename=chunk_display_name | |
| ) | |
| if not success: | |
| await send_media_to_bale_targets( | |
| BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, chunk_path, first_part, "document", | |
| parse_mode=None, upload_filename=chunk_display_name.replace('/', '-') | |
| ) | |
| await asyncio.sleep(1.5) | |
| else: | |
| first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, final_caption, parse_mode="HTML", is_caption=True) | |
| await send_media_to_bale_targets( | |
| BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, target_path, first_part, "document", | |
| parse_mode="HTML", upload_filename=display_name | |
| ) | |
| async def process_bot2(event, chat, username): | |
| if not msg_filter.evaluate(event.raw_text or ""): | |
| return | |
| # 1. Block audio/video | |
| if is_audio_or_video_bot2(event): | |
| await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Blocked audio/video from @{username or 'channel'}", "Bot-2") | |
| return | |
| cleaned_text = remove_words(event.raw_text or "", REMOVE_WORDS) | |
| # 2. Text only | |
| if not event.media: | |
| caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text) | |
| await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML") | |
| return | |
| # 3. Images (intact) | |
| if is_image_bot2(event): | |
| temp_dir = create_temp_dir() | |
| try: | |
| media_path = await download_media(event, temp_dir) | |
| if media_path: | |
| caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text) | |
| media_size = os.path.getsize(media_path) | |
| if media_size > CHUNK_SIZE: | |
| await handle_large_document_bot2(event, media_path, caption, temp_dir) | |
| else: | |
| first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML", is_caption=True) | |
| m_type = "photo" if event.photo else "document" | |
| success = await send_media_to_bale_targets(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, media_path, first_caption, m_type, parse_mode="HTML") | |
| if not success: | |
| await send_media_to_bale_targets(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, media_path, first_caption, "document", parse_mode=None) | |
| finally: | |
| cleanup_temp_dir(temp_dir) | |
| return | |
| # 4. Other files (Dummy bytes + obfuscation) | |
| orig_name, orig_ext = get_original_file_info(event) | |
| rand_name = f"file_{secrets.token_hex(4)}" | |
| obf_suffix = obfuscate_suffix(orig_ext) | |
| upload_filename = f"{rand_name}.{obf_suffix}" | |
| deobf_info = build_deobfuscation_instructions(orig_ext, obf_suffix) | |
| caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text, deobf_info=deobf_info) | |
| temp_dir = create_temp_dir() | |
| try: | |
| raw_media_path = await download_media(event, temp_dir) | |
| if not raw_media_path: | |
| return | |
| obf_media_path = os.path.join(temp_dir, f"{rand_name}.dat") | |
| inject_dummy_bytes(raw_media_path, obf_media_path, DUMMY_BYTE_COUNT) | |
| file_size = os.path.getsize(obf_media_path) | |
| if file_size > CHUNK_SIZE: | |
| async with LARGE_FILE_SEMAPHORE: | |
| await handle_large_document_bot2(event, obf_media_path, caption, temp_dir, upload_filename=upload_filename) | |
| else: | |
| first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML", is_caption=True) | |
| success = await send_media_to_bale_targets( | |
| BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, obf_media_path, first_caption, "document", | |
| parse_mode="HTML", upload_filename=upload_filename | |
| ) | |
| if not success: | |
| await send_media_to_bale_targets( | |
| BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, obf_media_path, first_caption, "document", | |
| parse_mode=None, upload_filename=upload_filename.replace('/', '-') | |
| ) | |
| finally: | |
| cleanup_temp_dir(temp_dir) | |
| # ========================================== | |
| # 9. CENTRAL TELEGRAM EVENT DISPATCHER | |
| # ========================================== | |
| tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH) | |
| async def unified_handler(event): | |
| if not event.is_channel: | |
| return | |
| chat = None | |
| username = None | |
| try: | |
| chat = await event.get_chat() | |
| username = (getattr(chat, 'username', '') or '').lower() | |
| is_bot1 = username in TARGET_CHANNELS_1 if username else False | |
| is_bot2 = username in TARGET_CHANNELS_2 if username else False | |
| if not is_bot1 and not is_bot2: | |
| return | |
| # Route to Bot 1 if matched | |
| if is_bot1 and BALE_BOT_TOKEN_1: | |
| try: | |
| await process_bot1(event, chat, username) | |
| except Exception as e: | |
| await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"Bot 1 Handler error (@{username}): {e}", "Bot-1") | |
| # Route to Bot 2 if matched | |
| if is_bot2 and BALE_BOT_TOKEN_2: | |
| try: | |
| await process_bot2(event, chat, username) | |
| except Exception as e: | |
| await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Bot 2 Handler error (@{username}): {e}", "Bot-2") | |
| except Exception as e: | |
| add_log(f"Global Router Exception: {e}") | |
| # ========================================== | |
| # 10. GRADIO DASHBOARD & FILE DEOBFUSCATOR | |
| # ========================================== | |
| def get_status_info(): | |
| status_icon = "π’" if TELEGRAM_STATUS == "Connected" else ("π‘" if "Connecting" in TELEGRAM_STATUS else "π΄") | |
| status_text = f"{status_icon} **Telegram Status:** {TELEGRAM_STATUS}" | |
| if TELEGRAM_ERROR: | |
| status_text += f"\n*Details:* {TELEGRAM_ERROR}" | |
| channels_text = "**Bot 1 Channels:**\n" + ("\n".join([f"β’ `@{c}`" for c in TARGET_CHANNELS_1]) if TARGET_CHANNELS_1 else "None") | |
| channels_text += "\n\n**Bot 2 Channels:**\n" + ("\n".join([f"β’ `@{c}`" for c in TARGET_CHANNELS_2]) if TARGET_CHANNELS_2 else "None") | |
| return status_text, channels_text | |
| def get_logs(): | |
| return "\n".join(LOG_BUFFER) if LOG_BUFFER else "No logs recorded yet." | |
| def deobfuscate_uploaded_file(file_obj, desired_ext): | |
| if file_obj is None: | |
| return None, "Please upload a file first." | |
| try: | |
| clean_ext = desired_ext.lstrip('.').strip() if desired_ext else "bin" | |
| out_path = os.path.join(tempfile.gettempdir(), f"restored_{secrets.token_hex(3)}.{clean_ext}") | |
| with open(file_obj.name, "rb") as f_in, open(out_path, "wb") as f_out: | |
| f_in.seek(DUMMY_BYTE_COUNT) | |
| shutil.copyfileobj(f_in, f_out) | |
| return out_path, f"Done! Stripped first {DUMMY_BYTE_COUNT} bytes. Saved as .{clean_ext}" | |
| except Exception as e: | |
| return None, f"Error: {e}" | |
| with gr.Blocks(title="Telegram Relay & Deobfuscator") as demo: | |
| gr.Markdown("# Unified Telegram to Bale Relay Dashboard") | |
| with gr.Tabs(): | |
| with gr.TabItem("Status & Live Logs"): | |
| with gr.Row(): | |
| status_box = gr.Markdown() | |
| channels_box = gr.Markdown() | |
| with gr.Row(): | |
| refresh_btn = gr.Button("Refresh Status & Logs", variant="primary") | |
| log_output = gr.Code(label="Live Bot Logs (Auto-refreshes every 3s)", language="shell") | |
| timer = gr.Timer(value=3) | |
| timer.tick(fn=get_status_info, outputs=[status_box, channels_box]) | |
| timer.tick(fn=get_logs, outputs=[log_output]) | |
| refresh_btn.click(fn=get_status_info, outputs=[status_box, channels_box]) | |
| refresh_btn.click(fn=get_logs, outputs=[log_output]) | |
| with gr.TabItem("File Deobfuscator Tool"): | |
| gr.Markdown( | |
| "### Restore files obfuscated by Bot 2\n" | |
| f"Upload any file received from Bale to trim the first {DUMMY_BYTE_COUNT} dummy bytes." | |
| ) | |
| with gr.Row(): | |
| file_input = gr.File(label="Upload Obfuscated File") | |
| target_ext = gr.Textbox(label="Original Extension", placeholder="e.g. zip, apk, conf, json", value="zip") | |
| restore_btn = gr.Button("Deobfuscate & Restore", variant="primary") | |
| result_status = gr.Markdown() | |
| file_output = gr.File(label="Download Clean Restored File") | |
| restore_btn.click( | |
| fn=deobfuscate_uploaded_file, | |
| inputs=[file_input, target_ext], | |
| outputs=[file_output, result_status] | |
| ) | |
| # ========================================== | |
| # 11. FASTAPI LIFECYCLE & SERVER | |
| # ========================================== | |
| async def lifespan(app: FastAPI): | |
| global TELEGRAM_STATUS, TELEGRAM_ERROR | |
| TELEGRAM_STATUS = "Connecting..." | |
| add_log("Telegram connecting...") | |
| try: | |
| await tg_client.connect() | |
| if not await tg_client.is_user_authorized(): | |
| TELEGRAM_STATUS = "Unauthorized" | |
| TELEGRAM_ERROR = "Session string unauthorized." | |
| add_log("β TELEGRAM NOT AUTHORIZED!") | |
| else: | |
| TELEGRAM_STATUS = "Connected" | |
| add_log("β Telegram Connected successfully!") | |
| asyncio.create_task(tg_client.run_until_disconnected()) | |
| except AuthKeyDuplicatedError: | |
| TELEGRAM_STATUS = "Session Revoked" | |
| TELEGRAM_ERROR = "Session duplicated/revoked." | |
| add_log("β Telegram Session Revoked.") | |
| except Exception as e: | |
| TELEGRAM_STATUS = "Error" | |
| TELEGRAM_ERROR = str(e) | |
| add_log(f"Connection error: {e}") | |
| yield | |
| await tg_client.disconnect() | |
| TELEGRAM_STATUS = "Stopped" | |
| add_log("Telegram disconnected") | |
| app = FastAPI(lifespan=lifespan) | |
| async def health(): | |
| return { | |
| "status": TELEGRAM_STATUS, | |
| "bot1_channels": TARGET_CHANNELS_1, | |
| "bot2_channels": TARGET_CHANNELS_2 | |
| } | |
| # Mount Gradio onto the root of FastAPI | |
| app = gr.mount_gradio_app(app, demo, path="/") | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |