o7c1 commited on
Commit
00a0c99
·
verified ·
1 Parent(s): 396aa78

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +794 -317
main.py CHANGED
@@ -4,150 +4,222 @@ import tempfile
4
  import zipfile
5
  import httpx
6
  import shutil
 
 
 
 
 
 
 
7
  from telethon import TelegramClient, events
8
  from telethon.sessions import StringSession
 
 
9
  from fastapi import FastAPI
10
  import uvicorn
11
- from contextlib import asynccontextmanager
 
 
 
12
 
13
- # --- 1. CONFIGURATION ---
14
  def get_env(name):
15
  return os.getenv(name)
16
 
 
 
 
17
  TG_API_ID = int(get_env("TG_API_ID") or 0)
18
  TG_API_HASH = get_env("TG_API_HASH")
19
  TG_SESSION_STRING = get_env("TG_SESSION_STRING")
20
 
21
- BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
22
- BALE_CHAT_ID = get_env("BALE_CHAT_ID")
23
- BALE_LOG_CHAT_ID = get_env("BALE_LOG_CHAT_ID") or BALE_CHAT_ID
 
 
 
24
 
25
- env_channels = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
26
- TARGET_CHANNELS = list(set(env_channels + [""]))
27
 
28
- CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB
29
- MAX_TEXT_LEN = 4000 # Bale maximum message length
 
 
 
 
 
 
 
30
 
31
- LARGE_FILE_SEMAPHORE = asyncio.Semaphore(2)
32
- BALE_API_SEMAPHORE = asyncio.Semaphore(3)
33
 
34
- # --- 2. TELEGRAM CLIENT ---
35
- tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
36
 
37
- # --- 3. BALE HELPERS (with retries & splitting) ---
 
38
 
39
- async def send_text_to_bale(text, parse_mode=None, retries=3, log_error=True):
40
- if not BALE_BOT_TOKEN:
41
- return False
42
- url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
43
- payload = {"chat_id": BALE_CHAT_ID, "text": text}
44
- if parse_mode:
45
- payload["parse_mode"] = parse_mode
46
 
47
- for attempt in range(1, retries + 1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  try:
49
- async with BALE_API_SEMAPHORE:
50
- async with httpx.AsyncClient() as client:
51
- resp = await client.post(url, json=payload, timeout=10)
52
- if resp.status_code == 200:
53
- return True
54
- else:
55
- if attempt < retries:
56
- await asyncio.sleep(2 ** (attempt - 1))
57
- continue
58
- if log_error:
59
- await send_log_to_bale(
60
- f"send_text_to_bale failed after {retries} attempts: "
61
- f"{resp.status_code} {resp.text[:200]}"
62
- )
63
- return False
64
  except Exception as e:
65
- if attempt < retries:
66
- await asyncio.sleep(2 ** (attempt - 1))
67
- continue
68
- if log_error:
69
- await send_log_to_bale(f"send_text_to_bale exception after {retries} attempts: {e}")
70
- return False
71
- return False
72
-
73
-
74
- async def send_media_to_bale(file_path, caption, media_type, parse_mode=None, retries=3):
75
- if not BALE_BOT_TOKEN:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  return False
77
 
78
- endpoint_map = {
79
- "photo": "sendPhoto",
80
- "video": "sendVideo",
81
- "document": "sendDocument",
82
- "audio": "sendAudio",
83
- "voice": "sendVoice",
84
- "sticker": "sendSticker",
85
- "video_note": "sendVideoNote",
86
- }
87
- endpoint = endpoint_map.get(media_type, "sendDocument")
88
- url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/{endpoint}"
89
 
90
- data = {"chat_id": BALE_CHAT_ID}
91
- if caption:
92
- data["caption"] = caption
93
- if parse_mode:
94
- data["parse_mode"] = parse_mode
95
-
96
- field_name = media_type if media_type in endpoint_map else "document"
97
-
98
- for attempt in range(1, retries + 1):
99
- try:
100
- with open(file_path, "rb") as f:
101
- files = {field_name: f}
102
- async with BALE_API_SEMAPHORE:
103
- async with httpx.AsyncClient() as client:
104
- resp = await client.post(url, data=data, files=files, timeout=30)
105
- if resp.status_code == 200:
106
- return True
107
- else:
108
- if attempt < retries:
109
- await asyncio.sleep(2 ** (attempt - 1))
110
- continue
111
- await send_log_to_bale(
112
- f"send_media_to_bale failed after {retries} attempts ({media_type}): "
113
- f"{resp.status_code} {resp.text[:300]}\nFile: {os.path.basename(file_path)}"
114
- )
115
- return False
116
- except Exception as e:
117
- if attempt < retries:
118
- await asyncio.sleep(2 ** (attempt - 1))
119
- continue
120
- await send_log_to_bale(
121
- f"send_media_to_bale exception after {retries} attempts ({media_type}): {e}\n"
122
- f"File: {os.path.basename(file_path)}"
123
- )
124
- return False
125
- return False
126
-
127
-
128
- async def send_log_to_bale(message):
129
- if not BALE_BOT_TOKEN or not BALE_LOG_CHAT_ID:
130
- return
131
- url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
132
- payload = {"chat_id": BALE_LOG_CHAT_ID, "text": f"🔧 Bot Log:\n{message}"}
133
- try:
134
- async with httpx.AsyncClient() as client:
135
- await client.post(url, json=payload, timeout=5)
136
- except Exception:
137
- pass
138
 
139
 
 
 
 
140
  def split_long_text(text, max_len=MAX_TEXT_LEN):
141
- """Split a long text into chunks of max_len characters."""
142
  if len(text) <= max_len:
143
  return [text]
144
-
145
  chunks = []
146
  while text:
147
  if len(text) <= max_len:
148
  chunks.append(text)
149
  break
150
- # Try to split at newline, then space
151
  split_at = text.rfind('\n', 0, max_len)
152
  if split_at == -1:
153
  split_at = text.rfind(' ', 0, max_len)
@@ -161,54 +233,6 @@ def split_long_text(text, max_len=MAX_TEXT_LEN):
161
  chunks.append(chunk)
162
  return chunks
163
 
164
-
165
- async def send_text_or_caption(text, parse_mode="HTML", is_caption=False, max_len=MAX_TEXT_LEN):
166
- """
167
- Send/caption-split long text.
168
- For captions: returns (first_part, success)
169
- For plain text: returns success (bool)
170
- """
171
- if not text:
172
- return ("" if is_caption else True)
173
-
174
- # HTML may break if split, so fall back to plain text when splitting
175
- if len(text) > max_len and parse_mode:
176
- parse_mode = None
177
-
178
- chunks = split_long_text(text, max_len)
179
- total = len(chunks)
180
-
181
- if is_caption:
182
- first_chunk = chunks[0]
183
- if total == 1:
184
- return first_chunk, True
185
-
186
- first_chunk = first_chunk + f"\n… (1/{total})"
187
- success = True
188
- for i in range(1, total):
189
- chunk_text = f"{chunks[i]}\n… ({i+1}/{total})"
190
- ok = await send_text_to_bale(chunk_text, parse_mode=None, log_error=False)
191
- if not ok:
192
- await send_log_to_bale(f"Failed to send caption part {i+1}/{total}")
193
- success = False
194
- await asyncio.sleep(0.5)
195
- return first_chunk, success
196
-
197
- # Plain text (no media)
198
- success = True
199
- for i, chunk in enumerate(chunks, 1):
200
- if total > 1:
201
- chunk = f"{chunk}\n… ({i}/{total})"
202
- ok = await send_text_to_bale(chunk, parse_mode=parse_mode, log_error=False)
203
- if not ok:
204
- await send_log_to_bale(f"Failed to send text part {i}/{total}")
205
- success = False
206
- if i < total:
207
- await asyncio.sleep(0.5)
208
- return success
209
-
210
-
211
- # --- 4. TEMP DIRECTORY HELPERS ---
212
  def create_temp_dir():
213
  return tempfile.mkdtemp(prefix="tg2bale_")
214
 
@@ -218,8 +242,33 @@ def cleanup_temp_dir(temp_dir):
218
  except Exception:
219
  pass
220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
- # --- 5. FILE OPERATIONS (threaded) ---
223
  async def download_media(message, temp_dir):
224
  if not message.media:
225
  return None
@@ -230,16 +279,12 @@ async def download_media(message, temp_dir):
230
  elif message.video:
231
  suffix = ".mp4"
232
  elif getattr(message, 'document', None):
233
- attrs = message.document.attributes
234
- for attr in attrs:
235
- if hasattr(attr, 'file_name'):
236
- if '.' in attr.file_name:
237
- suffix = f".{attr.file_name.split('.')[-1]}"
238
  break
239
- if not suffix:
240
- mime = message.document.mime_type
241
- if mime and '/' in mime:
242
- suffix = f".{mime.split('/')[-1]}"
243
  elif message.audio:
244
  suffix = ".mp3"
245
  elif message.voice:
@@ -253,95 +298,179 @@ async def download_media(message, temp_dir):
253
  await message.download_media(file=file_path)
254
  return file_path
255
  except Exception as e:
256
- await send_log_to_bale(f"Media download error: {e}")
257
  return None
258
 
 
 
 
 
 
 
 
259
 
260
- def zip_file_sync(file_path, zip_path):
261
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
262
- zf.write(file_path, arcname=os.path.basename(file_path))
263
- return zip_path
264
 
265
- async def zip_file(file_path, zip_path):
266
- return await asyncio.to_thread(zip_file_sync, file_path, zip_path)
 
 
 
 
 
 
 
 
 
 
267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
- def split_file_sync(file_path, chunk_size=CHUNK_SIZE):
270
- chunk_paths = []
271
- base = file_path + ".part"
272
- with open(file_path, "rb") as f:
273
- i = 0
274
- while True:
275
- chunk_data = f.read(chunk_size)
276
- if not chunk_data:
277
- break
278
- chunk_path = f"{base}{i:03d}.zip"
279
- with open(chunk_path, "wb") as chunk_file:
280
- chunk_file.write(chunk_data)
281
- chunk_paths.append(chunk_path)
282
- i += 1
283
- return chunk_paths
284
 
285
- async def split_file(file_path, chunk_size=CHUNK_SIZE):
286
- return await asyncio.to_thread(split_file_sync, file_path, chunk_size)
287
-
288
-
289
- # --- 6. MEDIA DETECTION / SIZE ---
290
- def detect_media_type(event):
291
- if event.photo:
292
- return "photo"
293
- if event.video:
294
- return "video"
295
- if event.audio:
296
- return "audio"
297
- if event.voice:
298
- return "voice"
299
- if event.sticker:
300
- return "sticker"
301
- if event.video_note:
302
- return "video_note"
303
- if event.document:
304
- return "document"
305
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
 
307
- def get_media_size(event):
 
 
 
 
 
308
  try:
309
- if event.photo:
310
- return event.photo.sizes[-1].size
311
- if event.video:
312
- return event.video.size
313
- if event.audio:
314
- return event.audio.size
315
- if event.voice:
316
- return event.voice.size
317
- if event.video_note:
318
- return event.video_note.size
319
- if event.sticker:
320
- return event.sticker.size if hasattr(event.sticker, 'size') else None
321
- if event.document:
322
- return event.document.size
323
  except Exception:
324
  pass
325
- return None
326
 
327
 
328
- def get_message_link(event, chat):
329
- """Return a clickable t.me link for the message."""
330
- username = getattr(chat, 'username', None)
331
- if username:
332
- return f"https://t.me/{username}/{event.message.id}"
333
- # Private channel / supergroup without username
334
- if getattr(chat, 'id', None):
335
- return f"https://t.me/c/{abs(chat.id)}/{event.message.id}"
336
- return ""
 
 
 
337
 
 
 
 
 
 
 
 
 
 
 
 
 
338
 
339
- def build_caption(event, chat):
340
  msg_text = event.raw_text or ""
341
  msg_link = get_message_link(event, chat)
342
 
343
  preview_url = ""
344
- if event.message.web_preview and event.message.web_preview.url:
345
  preview_url = event.message.web_preview.url
346
 
347
  parts = []
@@ -353,128 +482,476 @@ def build_caption(event, chat):
353
  parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
354
  return "\n\n".join(parts)
355
 
356
-
357
- async def handle_large_document(event, media_path, final_caption, temp_dir):
358
  file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
359
- await send_log_to_bale(
360
- f"Processing large file: {os.path.basename(media_path)}, size={file_size/(1024*1024):.1f} MB"
361
- )
362
 
363
  zip_path = os.path.join(temp_dir, "media.zip")
364
  await zip_file(media_path, zip_path)
365
  zip_size = os.path.getsize(zip_path)
366
 
 
367
  if zip_size > CHUNK_SIZE:
368
- chunks = await split_file(zip_path)
369
  total = len(chunks)
370
- await send_log_to_bale(f"ZIP {zip_size/(1024*1024):.1f} MB split into {total} chunks")
371
  for idx, chunk_path in enumerate(chunks, start=1):
372
- chunk_size_mb = os.path.getsize(chunk_path) / (1024 * 1024)
373
  part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
 
 
 
 
 
 
 
 
 
 
 
 
 
374
 
375
- first_part, _ = await send_text_or_caption(part_caption, parse_mode="HTML", is_caption=True)
376
- success = await send_media_to_bale(chunk_path, first_part, "document", parse_mode="HTML")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  if not success:
378
- success = await send_media_to_bale(chunk_path, first_part, "document", parse_mode=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  if not success:
380
- await send_log_to_bale(f"❌ Chunk {idx}/{total} FAILED permanently")
381
- else:
382
- await send_log_to_bale(f"✅ Chunk {idx}/{total} sent ({chunk_size_mb:.1f} MB)")
 
383
  await asyncio.sleep(1.5)
384
  else:
385
- await send_log_to_bale(f"ZIP size {zip_size/(1024*1024):.1f} MB, sending whole")
386
- first_part, _ = await send_text_or_caption(final_caption, parse_mode="HTML", is_caption=True)
387
- await send_media_to_bale(zip_path, first_part, "document", parse_mode="HTML")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
 
389
 
390
- # --- 7. TELEGRAM EVENT HANDLER (main logic) ---
 
 
 
 
391
  @tg_client.on(events.NewMessage)
392
- async def handler(event):
393
  if not event.is_channel:
394
  return
395
  chat = None
396
  username = None
397
  try:
398
  chat = await event.get_chat()
399
- username = getattr(chat, 'username', None)
400
 
401
- # Only process channels with a username that is in the target list
402
- if not username or username.lower() not in TARGET_CHANNELS:
 
 
403
  return
404
 
405
- # Build header
406
- header = f"📢 @{username}\n\n" if username else f"📢 {chat.title}\n\n"
407
- caption_body = build_caption(event, chat)
408
- final_caption = header + caption_body
 
 
409
 
410
- media_type = detect_media_type(event)
411
- if not media_type:
412
- # Plain text
413
- await send_text_or_caption(final_caption, parse_mode="HTML")
414
- return
 
415
 
416
- # Media message
417
- media_size = get_media_size(event)
418
- if media_size and media_size > CHUNK_SIZE:
419
- async with LARGE_FILE_SEMAPHORE:
420
- temp_dir = create_temp_dir()
421
- try:
422
- await send_log_to_bale(f"Large {media_type} from {username or chat.title}: {media_size/(1024*1024):.1f} MB")
423
- media_path = await download_media(event, temp_dir)
424
- if media_path:
425
- await handle_large_document(event, media_path, final_caption, temp_dir)
426
- finally:
427
- cleanup_temp_dir(temp_dir)
428
- return
429
 
430
- # Small media
431
- temp_dir = create_temp_dir()
432
- try:
433
- media_path = await download_media(event, temp_dir)
434
- if media_path:
435
- first_caption, _ = await send_text_or_caption(final_caption, parse_mode="HTML", is_caption=True)
436
- success = await send_media_to_bale(media_path, first_caption, media_type, parse_mode="HTML")
437
- if not success:
438
- # Fallback: zip and send as document
439
- await send_log_to_bale(f"Direct send failed for {media_type}, trying as document...")
440
- zip_path = os.path.join(temp_dir, "fallback.zip")
441
- await zip_file(media_path, zip_path)
442
- success = await send_media_to_bale(zip_path, first_caption, "document", parse_mode=None)
443
- if not success:
444
- await send_log_to_bale(f"Fallback also failed for {media_type}")
445
- finally:
446
- cleanup_temp_dir(temp_dir)
447
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  except Exception as e:
449
- name = username if username else getattr(chat, 'title', '?') if chat else '?'
450
- await send_log_to_bale(f"Handler Error (@{name}): {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
 
452
 
453
- # --- 8. SERVER LIFESPAN ---
 
 
454
  @asynccontextmanager
455
  async def lifespan(app: FastAPI):
456
- await send_log_to_bale("Bot starting...")
457
- print("Connecting to Telegram...")
458
- await tg_client.connect()
459
- if not await tg_client.is_user_authorized():
460
- msg = "❌ TELEGRAM NOT AUTHORIZED!"
461
- print(msg)
462
- await send_log_to_bale(msg)
463
- else:
464
- msg = "✅ Telegram Connected!"
465
- print(msg)
466
- await send_log_to_bale(msg)
467
- asyncio.create_task(tg_client.run_until_disconnected())
 
 
 
 
 
 
 
 
 
468
 
469
  yield
 
470
  await tg_client.disconnect()
471
- await send_log_to_bale("Bot disconnected")
 
472
 
473
  app = FastAPI(lifespan=lifespan)
474
 
475
- @app.get("/")
476
  async def health():
477
- return {"status": "running", "monitoring": TARGET_CHANNELS}
 
 
 
 
 
 
 
478
 
479
  if __name__ == "__main__":
480
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
4
  import zipfile
5
  import httpx
6
  import shutil
7
+ import re
8
+ import secrets
9
+ import html
10
+ from datetime import datetime
11
+ from collections import deque
12
+ from contextlib import asynccontextmanager
13
+
14
  from telethon import TelegramClient, events
15
  from telethon.sessions import StringSession
16
+ from telethon.errors import AuthKeyDuplicatedError
17
+
18
  from fastapi import FastAPI
19
  import uvicorn
20
+ import gradio as gr
21
+
22
+ # Disable Gradio SSR proxying
23
+ os.environ["GRADIO_SSR_MODE"] = "false"
24
 
 
25
  def get_env(name):
26
  return os.getenv(name)
27
 
28
+ # ==========================================
29
+ # 1. COMMON TELEGRAM CONFIGURATION
30
+ # ==========================================
31
  TG_API_ID = int(get_env("TG_API_ID") or 0)
32
  TG_API_HASH = get_env("TG_API_HASH")
33
  TG_SESSION_STRING = get_env("TG_SESSION_STRING")
34
 
35
+ # ==========================================
36
+ # 2. BOT 1 CONFIGURATION (Standard Relay)
37
+ # ==========================================
38
+ BALE_BOT_TOKEN_1 = get_env("BALE_BOT_TOKEN")
39
+ BALE_CHAT_ID_1 = get_env("BALE_CHAT_ID")
40
+ BALE_LOG_CHAT_ID_1 = get_env("BALE_LOG_CHAT_ID") or BALE_CHAT_ID_1
41
 
42
+ env_channels_1 = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
43
+ TARGET_CHANNELS_1 = list(set(env_channels_1))
44
 
45
+ # ==========================================
46
+ # 3. BOT 2 CONFIGURATION (Filtered/Obfuscated)
47
+ # ==========================================
48
+ BALE_BOT_TOKEN_2 = get_env("BALE_BOT_TOKEN_2")
49
+ bale_ids_raw_2 = get_env("BALE_CHAT_IDS") or get_env("BALE_CHAT_ID_2")
50
+ if bale_ids_raw_2:
51
+ BALE_CHAT_IDS_2 = [x.strip() for x in bale_ids_raw_2.split(",") if x.strip()]
52
+ else:
53
+ BALE_CHAT_IDS_2 = []
54
 
55
+ 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)
 
56
 
57
+ env_channels_2 = [c.strip().lower() for c in (get_env("TARGET_CHANNELS_2") or "").split(",") if c.strip()]
58
+ TARGET_CHANNELS_2 = list(set(env_channels_2 + ["iu39f", "tirexnet", "xsfilterrnet"]))
59
 
60
+ FILTER_EXPR = get_env("FILTER_EXPR") or ""
61
+ REMOVE_WORDS = [w.strip().lower() for w in (get_env("REMOVE_WORDS") or "").split(",") if w.strip()]
62
 
63
+ # Constants
64
+ CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB
65
+ MAX_TEXT_LEN = 4000
66
+ DUMMY_BYTE_COUNT = 64
 
 
 
67
 
68
+ LARGE_FILE_SEMAPHORE = asyncio.Semaphore(2)
69
+ BALE_API_SEMAPHORE = asyncio.Semaphore(4)
70
+
71
+ LOG_BUFFER = deque(maxlen=250)
72
+ TELEGRAM_STATUS = "Stopped"
73
+ TELEGRAM_ERROR = None
74
+
75
+ def add_log(msg: str):
76
+ timestamp = datetime.now().strftime("%H:%M:%S")
77
+ entry = f"[{timestamp}] {msg}"
78
+ LOG_BUFFER.append(entry)
79
+ print(entry)
80
+
81
+
82
+ # ==========================================
83
+ # 4. FILTER EXPRESSION PARSER (For Bot 2)
84
+ # ==========================================
85
+ class FilterExpr:
86
+ def __init__(self, expr_str: str):
87
+ self.ast = None
88
+ if not expr_str.strip():
89
+ return
90
  try:
91
+ tokens = self._tokenize(expr_str)
92
+ tokens = self._insert_and_operators(tokens)
93
+ self.ast = self._parse(tokens)
 
 
 
 
 
 
 
 
 
 
 
 
94
  except Exception as e:
95
+ add_log(f"Invalid FILTER_EXPR: {e}")
96
+ self.ast = None
97
+
98
+ def _tokenize(self, s):
99
+ token_re = re.compile(r'\(|\)|!|\||"[^"]*"|[^\s()!|"]+')
100
+ raw_tokens = token_re.findall(s)
101
+ typed = []
102
+ for t in raw_tokens:
103
+ if t == '(':
104
+ typed.append(('LPAREN', t))
105
+ elif t == ')':
106
+ typed.append(('RPAREN', t))
107
+ elif t == '!':
108
+ typed.append(('NOT', t))
109
+ elif t == '|':
110
+ typed.append(('OR', t))
111
+ elif t.startswith('"') and t.endswith('"'):
112
+ typed.append(('WORD', t[1:-1].lower()))
113
+ else:
114
+ typed.append(('WORD', t.lower()))
115
+ return typed
116
+
117
+ def _insert_and_operators(self, tokens):
118
+ if not tokens:
119
+ return []
120
+ terminators = {'WORD', 'RPAREN'}
121
+ starters = {'WORD', 'LPAREN', 'NOT'}
122
+ result = [tokens[0]]
123
+ for i in range(1, len(tokens)):
124
+ prev = tokens[i-1]
125
+ curr = tokens[i]
126
+ if prev[0] in terminators and curr[0] in starters:
127
+ result.append(('AND', '&'))
128
+ result.append(curr)
129
+ return result
130
+
131
+ def _parse(self, tokens):
132
+ self._pos = 0
133
+ self._tokens = tokens
134
+ ast = self._expr()
135
+ if self._pos != len(self._tokens):
136
+ raise ValueError(f"Unexpected token: {self._current()}")
137
+ return ast
138
+
139
+ def _current(self):
140
+ return self._tokens[self._pos] if self._pos < len(self._tokens) else None
141
+
142
+ def _advance(self):
143
+ self._pos += 1
144
+
145
+ def _expr(self):
146
+ left = self._term()
147
+ while self._current() and self._current()[0] == 'OR':
148
+ self._advance()
149
+ right = self._term()
150
+ left = ('OR', left, right)
151
+ return left
152
+
153
+ def _term(self):
154
+ left = self._factor()
155
+ while self._current() and self._current()[0] == 'AND':
156
+ self._advance()
157
+ right = self._factor()
158
+ left = ('AND', left, right)
159
+ return left
160
+
161
+ def _factor(self):
162
+ if self._current() and self._current()[0] == 'NOT':
163
+ self._advance()
164
+ child = self._factor()
165
+ return ('NOT', child)
166
+ return self._atom()
167
+
168
+ def _atom(self):
169
+ tok = self._current()
170
+ if not tok:
171
+ raise ValueError("Unexpected end of expression")
172
+ if tok[0] == 'LPAREN':
173
+ self._advance()
174
+ node = self._expr()
175
+ if not self._current() or self._current()[0] != 'RPAREN':
176
+ raise ValueError("Missing )")
177
+ self._advance()
178
+ return node
179
+ elif tok[0] == 'WORD':
180
+ self._advance()
181
+ return ('WORD', tok[1])
182
+ else:
183
+ raise ValueError(f"Unexpected token: {tok}")
184
+
185
+ def evaluate(self, text: str) -> bool:
186
+ if self.ast is None:
187
+ return True
188
+ return self._eval_node(self.ast, text.lower())
189
+
190
+ def _eval_node(self, node, text):
191
+ node_type = node[0]
192
+ if node_type == 'WORD':
193
+ return node[1] in text
194
+ elif node_type == 'AND':
195
+ return self._eval_node(node[1], text) and self._eval_node(node[2], text)
196
+ elif node_type == 'OR':
197
+ return self._eval_node(node[1], text) or self._eval_node(node[2], text)
198
+ elif node_type == 'NOT':
199
+ return not self._eval_node(node[1], text)
200
  return False
201
 
202
+ msg_filter = FilterExpr(FILTER_EXPR)
 
 
 
 
 
 
 
 
 
 
203
 
204
+ def remove_words(text: str, words: list) -> str:
205
+ if not words or not text:
206
+ return text
207
+ for w in words:
208
+ text = re.sub(re.escape(w), '', text, flags=re.IGNORECASE)
209
+ return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
 
211
 
212
+ # ==========================================
213
+ # 5. GENERAL FILE & TEXT HELPERS
214
+ # ==========================================
215
  def split_long_text(text, max_len=MAX_TEXT_LEN):
 
216
  if len(text) <= max_len:
217
  return [text]
 
218
  chunks = []
219
  while text:
220
  if len(text) <= max_len:
221
  chunks.append(text)
222
  break
 
223
  split_at = text.rfind('\n', 0, max_len)
224
  if split_at == -1:
225
  split_at = text.rfind(' ', 0, max_len)
 
233
  chunks.append(chunk)
234
  return chunks
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  def create_temp_dir():
237
  return tempfile.mkdtemp(prefix="tg2bale_")
238
 
 
242
  except Exception:
243
  pass
244
 
245
+ def zip_file_sync(file_path, zip_path):
246
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
247
+ zf.write(file_path, arcname=os.path.basename(file_path))
248
+ return zip_path
249
+
250
+ async def zip_file(file_path, zip_path):
251
+ return await asyncio.to_thread(zip_file_sync, file_path, zip_path)
252
+
253
+ def split_file_sync(file_path, chunk_size=CHUNK_SIZE, suffix=".dat"):
254
+ chunk_paths = []
255
+ base = file_path + ".part"
256
+ with open(file_path, "rb") as f:
257
+ i = 0
258
+ while True:
259
+ chunk_data = f.read(chunk_size)
260
+ if not chunk_data:
261
+ break
262
+ chunk_path = f"{base}{i:03d}{suffix}"
263
+ with open(chunk_path, "wb") as chunk_file:
264
+ chunk_file.write(chunk_data)
265
+ chunk_paths.append(chunk_path)
266
+ i += 1
267
+ return chunk_paths
268
+
269
+ async def split_file(file_path, chunk_size=CHUNK_SIZE, suffix=".dat"):
270
+ return await asyncio.to_thread(split_file_sync, file_path, chunk_size, suffix)
271
 
 
272
  async def download_media(message, temp_dir):
273
  if not message.media:
274
  return None
 
279
  elif message.video:
280
  suffix = ".mp4"
281
  elif getattr(message, 'document', None):
282
+ for attr in message.document.attributes:
283
+ if hasattr(attr, 'file_name') and '.' in attr.file_name:
284
+ suffix = f".{attr.file_name.split('.')[-1]}"
 
 
285
  break
286
+ if not suffix and message.document.mime_type and '/' in message.document.mime_type:
287
+ suffix = f".{message.document.mime_type.split('/')[-1]}"
 
 
288
  elif message.audio:
289
  suffix = ".mp3"
290
  elif message.voice:
 
298
  await message.download_media(file=file_path)
299
  return file_path
300
  except Exception as e:
301
+ add_log(f"Media download error: {e}")
302
  return None
303
 
304
+ def get_message_link(event, chat):
305
+ username = getattr(chat, 'username', None)
306
+ if username:
307
+ return f"https://t.me/{username}/{event.message.id}"
308
+ if getattr(chat, 'id', None):
309
+ return f"https://t.me/c/{abs(chat.id)}/{event.message.id}"
310
+ return ""
311
 
 
 
 
 
312
 
313
+ # ==========================================
314
+ # 6. UNIVERSAL BALE SENDER FUNCTIONS
315
+ # ==========================================
316
+ async def send_text_to_bale_targets(bot_token, chat_ids, text, parse_mode=None, retries=3):
317
+ if not bot_token or not chat_ids:
318
+ return False
319
+ overall = True
320
+ for chat_id in chat_ids:
321
+ url = f"https://tapi.bale.ai/bot{bot_token}/sendMessage"
322
+ payload = {"chat_id": chat_id, "text": text}
323
+ if parse_mode:
324
+ payload["parse_mode"] = parse_mode
325
 
326
+ sent = False
327
+ for attempt in range(1, retries + 1):
328
+ try:
329
+ async with BALE_API_SEMAPHORE:
330
+ async with httpx.AsyncClient() as client:
331
+ resp = await client.post(url, json=payload, timeout=10)
332
+ if resp.status_code == 200:
333
+ sent = True
334
+ break
335
+ if attempt < retries:
336
+ await asyncio.sleep(2 ** (attempt - 1))
337
+ except Exception:
338
+ if attempt < retries:
339
+ await asyncio.sleep(2 ** (attempt - 1))
340
+ if not sent:
341
+ overall = False
342
+ return overall
343
+
344
+ async def send_media_to_bale_targets(bot_token, chat_ids, file_path, caption, media_type, parse_mode=None, upload_filename=None, retries=3):
345
+ if not bot_token or not chat_ids:
346
+ return False
347
 
348
+ endpoint_map = {
349
+ "photo": "sendPhoto",
350
+ "video": "sendVideo",
351
+ "document": "sendDocument",
352
+ "audio": "sendAudio",
353
+ "voice": "sendVoice",
354
+ "sticker": "sendSticker",
355
+ "video_note": "sendVideoNote",
356
+ }
357
+ endpoint = endpoint_map.get(media_type, "sendDocument")
358
+ field_name = media_type if media_type in endpoint_map else "document"
 
 
 
 
359
 
360
+ overall = True
361
+ for chat_id in chat_ids:
362
+ url = f"https://tapi.bale.ai/bot{bot_token}/{endpoint}"
363
+ data = {"chat_id": chat_id}
364
+ if caption:
365
+ data["caption"] = caption
366
+ if parse_mode:
367
+ data["parse_mode"] = parse_mode
368
+
369
+ sent = False
370
+ for attempt in range(1, retries + 1):
371
+ try:
372
+ cur_filename = upload_filename
373
+ if cur_filename and attempt > 1 and '/' in cur_filename:
374
+ cur_filename = cur_filename.replace('/', '-')
375
+
376
+ with open(file_path, "rb") as f:
377
+ files = {field_name: (cur_filename, f)} if cur_filename else {field_name: f}
378
+ async with BALE_API_SEMAPHORE:
379
+ async with httpx.AsyncClient() as client:
380
+ resp = await client.post(url, data=data, files=files, timeout=30)
381
+ if resp.status_code == 200:
382
+ sent = True
383
+ break
384
+ if attempt < retries:
385
+ await asyncio.sleep(2 ** (attempt - 1))
386
+ except Exception:
387
+ if attempt < retries:
388
+ await asyncio.sleep(2 ** (attempt - 1))
389
+ if not sent:
390
+ overall = False
391
+ return overall
392
+
393
+ async def send_text_or_caption_bale(bot_token, chat_ids, text, parse_mode="HTML", is_caption=False, max_len=MAX_TEXT_LEN):
394
+ if not text:
395
+ return ("" if is_caption else True)
396
+
397
+ if len(text) > max_len and parse_mode:
398
+ parse_mode = None
399
+
400
+ chunks = split_long_text(text, max_len)
401
+ total = len(chunks)
402
+
403
+ if is_caption:
404
+ first_chunk = chunks[0]
405
+ if total == 1:
406
+ return first_chunk, True
407
+
408
+ first_chunk = first_chunk + f"\n… (1/{total})"
409
+ success = True
410
+ for i in range(1, total):
411
+ chunk_text = f"{chunks[i]}\n… ({i+1}/{total})"
412
+ ok = await send_text_to_bale_targets(bot_token, chat_ids, chunk_text, parse_mode=None)
413
+ if not ok:
414
+ success = False
415
+ await asyncio.sleep(0.5)
416
+ return first_chunk, success
417
+
418
+ success = True
419
+ for i, chunk in enumerate(chunks, 1):
420
+ if total > 1:
421
+ chunk = f"{chunk}\n… ({i}/{total})"
422
+ ok = await send_text_to_bale_targets(bot_token, chat_ids, chunk, parse_mode=parse_mode)
423
+ if not ok:
424
+ success = False
425
+ if i < total:
426
+ await asyncio.sleep(0.5)
427
+ return success
428
 
429
+ async def log_to_bale(bot_token, log_chat_id, message, bot_tag="Bot"):
430
+ add_log(f"[{bot_tag}] {message}")
431
+ if not bot_token or not log_chat_id:
432
+ return
433
+ url = f"https://tapi.bale.ai/bot{bot_token}/sendMessage"
434
+ payload = {"chat_id": log_chat_id, "text": f"🔧 [{bot_tag} Log]:\n{message}"}
435
  try:
436
+ async with httpx.AsyncClient() as client:
437
+ await client.post(url, json=payload, timeout=5)
 
 
 
 
 
 
 
 
 
 
 
 
438
  except Exception:
439
  pass
 
440
 
441
 
442
+ # ==========================================
443
+ # 7. BOT 1 HANDLERS (Standard)
444
+ # ==========================================
445
+ def detect_media_type_bot1(event):
446
+ if event.photo: return "photo"
447
+ if event.video: return "video"
448
+ if event.audio: return "audio"
449
+ if event.voice: return "voice"
450
+ if event.sticker: return "sticker"
451
+ if event.video_note: return "video_note"
452
+ if event.document: return "document"
453
+ return None
454
 
455
+ def get_media_size_bot1(event):
456
+ try:
457
+ if event.photo: return event.photo.sizes[-1].size
458
+ if event.video: return event.video.size
459
+ if event.audio: return event.audio.size
460
+ if event.voice: return event.voice.size
461
+ if event.video_note: return event.video_note.size
462
+ if event.sticker: return getattr(event.sticker, 'size', None)
463
+ if event.document: return event.document.size
464
+ except Exception:
465
+ pass
466
+ return None
467
 
468
+ def build_caption_bot1(event, chat):
469
  msg_text = event.raw_text or ""
470
  msg_link = get_message_link(event, chat)
471
 
472
  preview_url = ""
473
+ if event.message and event.message.web_preview and event.message.web_preview.url:
474
  preview_url = event.message.web_preview.url
475
 
476
  parts = []
 
482
  parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
483
  return "\n\n".join(parts)
484
 
485
+ async def handle_large_document_bot1(event, media_path, final_caption, temp_dir):
 
486
  file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
487
+ 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")
 
 
488
 
489
  zip_path = os.path.join(temp_dir, "media.zip")
490
  await zip_file(media_path, zip_path)
491
  zip_size = os.path.getsize(zip_path)
492
 
493
+ chat_ids = [BALE_CHAT_ID_1]
494
  if zip_size > CHUNK_SIZE:
495
+ chunks = await split_file(zip_path, CHUNK_SIZE, suffix=".zip")
496
  total = len(chunks)
497
+ await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"ZIP split into {total} chunks", "Bot-1")
498
  for idx, chunk_path in enumerate(chunks, start=1):
 
499
  part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
500
+ first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, part_caption, parse_mode="HTML", is_caption=True)
501
+ success = await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, chunk_path, first_part, "document", parse_mode="HTML")
502
+ if not success:
503
+ await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, chunk_path, first_part, "document", parse_mode=None)
504
+ await asyncio.sleep(1.5)
505
+ else:
506
+ first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML", is_caption=True)
507
+ await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, zip_path, first_part, "document", parse_mode="HTML")
508
+
509
+ async def process_bot1(event, chat, username):
510
+ header = f"📢 @{username}\n\n" if username else f"📢 {chat.title}\n\n"
511
+ caption_body = build_caption_bot1(event, chat)
512
+ final_caption = header + caption_body
513
 
514
+ media_type = detect_media_type_bot1(event)
515
+ chat_ids = [BALE_CHAT_ID_1]
516
+
517
+ if not media_type:
518
+ await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML")
519
+ return
520
+
521
+ media_size = get_media_size_bot1(event)
522
+ if media_size and media_size > CHUNK_SIZE:
523
+ async with LARGE_FILE_SEMAPHORE:
524
+ temp_dir = create_temp_dir()
525
+ try:
526
+ 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")
527
+ media_path = await download_media(event, temp_dir)
528
+ if media_path:
529
+ await handle_large_document_bot1(event, media_path, final_caption, temp_dir)
530
+ finally:
531
+ cleanup_temp_dir(temp_dir)
532
+ return
533
+
534
+ temp_dir = create_temp_dir()
535
+ try:
536
+ media_path = await download_media(event, temp_dir)
537
+ if media_path:
538
+ first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML", is_caption=True)
539
+ success = await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, media_path, first_caption, media_type, parse_mode="HTML")
540
  if not success:
541
+ zip_path = os.path.join(temp_dir, "fallback.zip")
542
+ await zip_file(media_path, zip_path)
543
+ await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, zip_path, first_caption, "document", parse_mode=None)
544
+ finally:
545
+ cleanup_temp_dir(temp_dir)
546
+
547
+
548
+ # ==========================================
549
+ # 8. BOT 2 HANDLERS (Filtering & Obfuscation)
550
+ # ==========================================
551
+ def is_audio_or_video_bot2(event) -> bool:
552
+ if event.video or event.audio or event.voice or event.video_note:
553
+ return True
554
+ if event.document:
555
+ mime = getattr(event.document, 'mime_type', '') or ''
556
+ if mime.startswith('video/') or mime.startswith('audio/'):
557
+ return True
558
+ for attr in getattr(event.document, 'attributes', []):
559
+ fname = getattr(attr, 'file_name', '')
560
+ if fname:
561
+ ext = fname.lower().split('.')[-1]
562
+ if ext in {'mp4', 'mkv', 'avi', 'mov', 'flv', 'wmv', 'webm', '3gp',
563
+ 'mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'opus'}:
564
+ return True
565
+ return False
566
+
567
+ def is_image_bot2(event) -> bool:
568
+ if event.photo or event.sticker:
569
+ return True
570
+ if event.document:
571
+ mime = getattr(event.document, 'mime_type', '') or ''
572
+ if mime.startswith('image/'):
573
+ return True
574
+ for attr in getattr(event.document, 'attributes', []):
575
+ fname = getattr(attr, 'file_name', '')
576
+ if fname:
577
+ ext = fname.lower().split('.')[-1]
578
+ if ext in {'jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'svg', 'ico'}:
579
+ return True
580
+ return False
581
+
582
+ def obfuscate_suffix(suffix: str) -> str:
583
+ clean = suffix.lstrip('.').strip().lower()
584
+ if not clean:
585
+ clean = "bin"
586
+ if len(clean) == 1:
587
+ return f"*{clean}/"
588
+ elif len(clean) == 2:
589
+ return f"{clean[0]}*/{clean[1]}"
590
+ else:
591
+ res = []
592
+ for i, c in enumerate(clean):
593
+ res.append(c)
594
+ if i < len(clean) - 1:
595
+ res.append('*' if i % 2 == 0 else '/')
596
+ s = "".join(res)
597
+ if '/' not in s: s += "/"
598
+ if '*' not in s: s = "*" + s
599
+ return s
600
+
601
+ def inject_dummy_bytes(src_path: str, dst_path: str, count: int = DUMMY_BYTE_COUNT):
602
+ dummy = os.urandom(count)
603
+ with open(src_path, "rb") as f_in, open(dst_path, "wb") as f_out:
604
+ f_out.write(dummy)
605
+ shutil.copyfileobj(f_in, f_out)
606
+
607
+ def get_original_file_info(event):
608
+ orig_name = None
609
+ orig_ext = ""
610
+ if getattr(event, 'document', None):
611
+ for attr in event.document.attributes:
612
+ if hasattr(attr, 'file_name') and attr.file_name:
613
+ orig_name = attr.file_name
614
+ break
615
+ if orig_name and '.' in orig_name:
616
+ orig_ext = orig_name.rsplit('.', 1)[-1]
617
+ elif event.document.mime_type and '/' in event.document.mime_type:
618
+ orig_ext = event.document.mime_type.split('/')[-1]
619
+
620
+ if not orig_ext:
621
+ orig_ext = "bin"
622
+ return orig_name, orig_ext.lower()
623
+
624
+ def extract_hyperlinks(event, text: str = "") -> list:
625
+ urls = []
626
+ seen = set()
627
+
628
+ def add_url(u):
629
+ u = u.strip()
630
+ if u and u not in seen:
631
+ seen.add(u)
632
+ urls.append(u)
633
+
634
+ if event.message and event.message.entities:
635
+ for ent in event.message.entities:
636
+ if hasattr(ent, 'url') and ent.url:
637
+ add_url(ent.url)
638
+ elif ent.__class__.__name__ == 'MessageEntityUrl':
639
+ raw = event.raw_text or ""
640
+ u = raw[ent.offset: ent.offset + ent.length]
641
+ add_url(u)
642
+
643
+ if event.message and event.message.web_preview and event.message.web_preview.url:
644
+ add_url(event.message.web_preview.url)
645
+
646
+ if text:
647
+ for u in re.findall(r'(https?://[^\s<>"\']+)', text):
648
+ add_url(u)
649
+
650
+ return urls
651
+
652
+ def build_full_caption_bot2(event, chat, cleaned_text: str = None, deobf_info: str = None) -> str:
653
+ parts = []
654
+ username = getattr(chat, 'username', None)
655
+ title = getattr(chat, 'title', None)
656
+ if username:
657
+ parts.append(f"📢 <b>Channel:</b> @{username}\n🔗 https://t.me/{username}")
658
+ elif title:
659
+ parts.append(f"📢 <b>Channel:</b> {html.escape(title)}")
660
+
661
+ body = cleaned_text if cleaned_text is not None else (event.raw_text or "")
662
+ if body.strip():
663
+ parts.append(html.escape(body.strip()))
664
+
665
+ urls = extract_hyperlinks(event, body)
666
+ post_link = get_message_link(event, chat)
667
+ link_lines = []
668
+ if post_link and post_link not in urls:
669
+ link_lines.append(f'• <a href="{post_link}">📎 Open in Telegram</a>')
670
+ for u in urls:
671
+ escaped_u = html.escape(u)
672
+ link_lines.append(f'• <a href="{escaped_u}">{escaped_u}</a>')
673
+ if link_lines:
674
+ parts.append("🔗 <b>Links:</b>\n" + "\n".join(link_lines))
675
+
676
+ if deobf_info:
677
+ parts.append(deobf_info)
678
+
679
+ return "\n\n".join(parts)
680
+
681
+ def build_deobfuscation_instructions(original_ext: str, obfuscated_suffix: str) -> str:
682
+ return (
683
+ f"🛠 <b>Deobfuscation Instructions:</b>\n"
684
+ f"• <b>Original Extension:</b> <code>.{original_ext}</code> (Obfuscated: <code>{obfuscated_suffix}</code>)\n"
685
+ f"• <b>Restore Steps:</b>\n"
686
+ f" 1. Remove first {DUMMY_BYTE_COUNT} dummy bytes.\n"
687
+ f" 2. Rename suffix <code>{obfuscated_suffix}</code> back to <code>.{original_ext}</code>\n"
688
+ f"• <i>One-line command (Linux/Mac/Python):</i>\n"
689
+ f"<code>python -c \"open('restored.{original_ext}','wb').write(open('INPUT_FILE','rb').read()[{DUMMY_BYTE_COUNT}:])\"</code>"
690
+ )
691
+
692
+ async def handle_large_document_bot2(event, media_path, final_caption, temp_dir, upload_filename=None):
693
+ file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
694
+ display_name = upload_filename or os.path.basename(media_path)
695
+ 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")
696
+
697
+ target_path = media_path
698
+ target_size = os.path.getsize(target_path)
699
+
700
+ if target_size > CHUNK_SIZE:
701
+ chunks = await split_file(target_path, CHUNK_SIZE, suffix=".dat")
702
+ total = len(chunks)
703
+ await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Split into {total} parts", "Bot-2")
704
+ for idx, chunk_path in enumerate(chunks, start=1):
705
+ chunk_display_name = f"{display_name}.part{idx:03d}"
706
+ part_caption = f"{final_caption}\n\n📦 <b>Part {idx}/{total}</b>"
707
+
708
+ first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, part_caption, parse_mode="HTML", is_caption=True)
709
+ success = await send_media_to_bale_targets(
710
+ BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, chunk_path, first_part, "document",
711
+ parse_mode="HTML", upload_filename=chunk_display_name
712
+ )
713
  if not success:
714
+ await send_media_to_bale_targets(
715
+ BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, chunk_path, first_part, "document",
716
+ parse_mode=None, upload_filename=chunk_display_name.replace('/', '-')
717
+ )
718
  await asyncio.sleep(1.5)
719
  else:
720
+ first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, final_caption, parse_mode="HTML", is_caption=True)
721
+ await send_media_to_bale_targets(
722
+ BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, target_path, first_part, "document",
723
+ parse_mode="HTML", upload_filename=display_name
724
+ )
725
+
726
+ async def process_bot2(event, chat, username):
727
+ if not msg_filter.evaluate(event.raw_text or ""):
728
+ return
729
+
730
+ # 1. Block audio/video
731
+ if is_audio_or_video_bot2(event):
732
+ await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Blocked audio/video from @{username or 'channel'}", "Bot-2")
733
+ return
734
+
735
+ cleaned_text = remove_words(event.raw_text or "", REMOVE_WORDS)
736
+
737
+ # 2. Text only
738
+ if not event.media:
739
+ caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text)
740
+ await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML")
741
+ return
742
+
743
+ # 3. Images (intact)
744
+ if is_image_bot2(event):
745
+ temp_dir = create_temp_dir()
746
+ try:
747
+ media_path = await download_media(event, temp_dir)
748
+ if media_path:
749
+ caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text)
750
+ media_size = os.path.getsize(media_path)
751
+ if media_size > CHUNK_SIZE:
752
+ await handle_large_document_bot2(event, media_path, caption, temp_dir)
753
+ else:
754
+ first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML", is_caption=True)
755
+ m_type = "photo" if event.photo else "document"
756
+ success = await send_media_to_bale_targets(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, media_path, first_caption, m_type, parse_mode="HTML")
757
+ if not success:
758
+ await send_media_to_bale_targets(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, media_path, first_caption, "document", parse_mode=None)
759
+ finally:
760
+ cleanup_temp_dir(temp_dir)
761
+ return
762
+
763
+ # 4. Other files (Dummy bytes + obfuscation)
764
+ orig_name, orig_ext = get_original_file_info(event)
765
+ rand_name = f"file_{secrets.token_hex(4)}"
766
+ obf_suffix = obfuscate_suffix(orig_ext)
767
+ upload_filename = f"{rand_name}.{obf_suffix}"
768
+
769
+ deobf_info = build_deobfuscation_instructions(orig_ext, obf_suffix)
770
+ caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text, deobf_info=deobf_info)
771
+
772
+ temp_dir = create_temp_dir()
773
+ try:
774
+ raw_media_path = await download_media(event, temp_dir)
775
+ if not raw_media_path:
776
+ return
777
+
778
+ obf_media_path = os.path.join(temp_dir, f"{rand_name}.dat")
779
+ inject_dummy_bytes(raw_media_path, obf_media_path, DUMMY_BYTE_COUNT)
780
+
781
+ file_size = os.path.getsize(obf_media_path)
782
+ if file_size > CHUNK_SIZE:
783
+ async with LARGE_FILE_SEMAPHORE:
784
+ await handle_large_document_bot2(event, obf_media_path, caption, temp_dir, upload_filename=upload_filename)
785
+ else:
786
+ first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML", is_caption=True)
787
+ success = await send_media_to_bale_targets(
788
+ BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, obf_media_path, first_caption, "document",
789
+ parse_mode="HTML", upload_filename=upload_filename
790
+ )
791
+ if not success:
792
+ await send_media_to_bale_targets(
793
+ BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, obf_media_path, first_caption, "document",
794
+ parse_mode=None, upload_filename=upload_filename.replace('/', '-')
795
+ )
796
+ finally:
797
+ cleanup_temp_dir(temp_dir)
798
 
799
 
800
+ # ==========================================
801
+ # 9. CENTRAL TELEGRAM EVENT DISPATCHER
802
+ # ==========================================
803
+ tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
804
+
805
  @tg_client.on(events.NewMessage)
806
+ async def unified_handler(event):
807
  if not event.is_channel:
808
  return
809
  chat = None
810
  username = None
811
  try:
812
  chat = await event.get_chat()
813
+ username = (getattr(chat, 'username', '') or '').lower()
814
 
815
+ is_bot1 = username in TARGET_CHANNELS_1 if username else False
816
+ is_bot2 = username in TARGET_CHANNELS_2 if username else False
817
+
818
+ if not is_bot1 and not is_bot2:
819
  return
820
 
821
+ # Route to Bot 1 if matched
822
+ if is_bot1 and BALE_BOT_TOKEN_1:
823
+ try:
824
+ await process_bot1(event, chat, username)
825
+ except Exception as e:
826
+ await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"Bot 1 Handler error (@{username}): {e}", "Bot-1")
827
 
828
+ # Route to Bot 2 if matched
829
+ if is_bot2 and BALE_BOT_TOKEN_2:
830
+ try:
831
+ await process_bot2(event, chat, username)
832
+ except Exception as e:
833
+ await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Bot 2 Handler error (@{username}): {e}", "Bot-2")
834
 
835
+ except Exception as e:
836
+ add_log(f"Global Router Exception: {e}")
 
 
 
 
 
 
 
 
 
 
 
837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838
 
839
+ # ==========================================
840
+ # 10. GRADIO DASHBOARD & FILE DEOBFUSCATOR
841
+ # ==========================================
842
+ def get_status_info():
843
+ status_icon = "🟢" if TELEGRAM_STATUS == "Connected" else ("🟡" if "Connecting" in TELEGRAM_STATUS else "🔴")
844
+ status_text = f"{status_icon} **Telegram Status:** {TELEGRAM_STATUS}"
845
+ if TELEGRAM_ERROR:
846
+ status_text += f"\n*Details:* {TELEGRAM_ERROR}"
847
+
848
+ channels_text = "**Bot 1 Channels:**\n" + ("\n".join([f"• `@{c}`" for c in TARGET_CHANNELS_1]) if TARGET_CHANNELS_1 else "None")
849
+ channels_text += "\n\n**Bot 2 Channels:**\n" + ("\n".join([f"• `@{c}`" for c in TARGET_CHANNELS_2]) if TARGET_CHANNELS_2 else "None")
850
+ return status_text, channels_text
851
+
852
+ def get_logs():
853
+ return "\n".join(LOG_BUFFER) if LOG_BUFFER else "No logs recorded yet."
854
+
855
+ def deobfuscate_uploaded_file(file_obj, desired_ext):
856
+ if file_obj is None:
857
+ return None, "Please upload a file first."
858
+ try:
859
+ clean_ext = desired_ext.lstrip('.').strip() if desired_ext else "bin"
860
+ out_path = os.path.join(tempfile.gettempdir(), f"restored_{secrets.token_hex(3)}.{clean_ext}")
861
+
862
+ with open(file_obj.name, "rb") as f_in, open(out_path, "wb") as f_out:
863
+ f_in.seek(DUMMY_BYTE_COUNT)
864
+ shutil.copyfileobj(f_in, f_out)
865
+
866
+ return out_path, f"Done! Stripped first {DUMMY_BYTE_COUNT} bytes. Saved as .{clean_ext}"
867
  except Exception as e:
868
+ return None, f"Error: {e}"
869
+
870
+ with gr.Blocks(title="Telegram Relay & Deobfuscator") as demo:
871
+ gr.Markdown("# Unified Telegram to Bale Relay Dashboard")
872
+
873
+ with gr.Tabs():
874
+ with gr.TabItem("Status & Live Logs"):
875
+ with gr.Row():
876
+ status_box = gr.Markdown()
877
+ channels_box = gr.Markdown()
878
+
879
+ with gr.Row():
880
+ refresh_btn = gr.Button("Refresh Status & Logs", variant="primary")
881
+
882
+ log_output = gr.Code(label="Live Bot Logs (Auto-refreshes every 3s)", language="shell")
883
+
884
+ timer = gr.Timer(value=3)
885
+ timer.tick(fn=get_status_info, outputs=[status_box, channels_box])
886
+ timer.tick(fn=get_logs, outputs=[log_output])
887
+ refresh_btn.click(fn=get_status_info, outputs=[status_box, channels_box])
888
+ refresh_btn.click(fn=get_logs, outputs=[log_output])
889
+
890
+ with gr.TabItem("File Deobfuscator Tool"):
891
+ gr.Markdown(
892
+ "### Restore files obfuscated by Bot 2\n"
893
+ f"Upload any file received from Bale to trim the first {DUMMY_BYTE_COUNT} dummy bytes."
894
+ )
895
+ with gr.Row():
896
+ file_input = gr.File(label="Upload Obfuscated File")
897
+ target_ext = gr.Textbox(label="Original Extension", placeholder="e.g. zip, apk, conf, json", value="zip")
898
+
899
+ restore_btn = gr.Button("Deobfuscate & Restore", variant="primary")
900
+ result_status = gr.Markdown()
901
+ file_output = gr.File(label="Download Clean Restored File")
902
+
903
+ restore_btn.click(
904
+ fn=deobfuscate_uploaded_file,
905
+ inputs=[file_input, target_ext],
906
+ outputs=[file_output, result_status]
907
+ )
908
 
909
 
910
+ # ==========================================
911
+ # 11. FASTAPI LIFECYCLE & SERVER
912
+ # ==========================================
913
  @asynccontextmanager
914
  async def lifespan(app: FastAPI):
915
+ global TELEGRAM_STATUS, TELEGRAM_ERROR
916
+ TELEGRAM_STATUS = "Connecting..."
917
+ add_log("Telegram connecting...")
918
+ try:
919
+ await tg_client.connect()
920
+ if not await tg_client.is_user_authorized():
921
+ TELEGRAM_STATUS = "Unauthorized"
922
+ TELEGRAM_ERROR = "Session string unauthorized."
923
+ add_log("❌ TELEGRAM NOT AUTHORIZED!")
924
+ else:
925
+ TELEGRAM_STATUS = "Connected"
926
+ add_log("✅ Telegram Connected successfully!")
927
+ asyncio.create_task(tg_client.run_until_disconnected())
928
+ except AuthKeyDuplicatedError:
929
+ TELEGRAM_STATUS = "Session Revoked"
930
+ TELEGRAM_ERROR = "Session duplicated/revoked."
931
+ add_log("❌ Telegram Session Revoked.")
932
+ except Exception as e:
933
+ TELEGRAM_STATUS = "Error"
934
+ TELEGRAM_ERROR = str(e)
935
+ add_log(f"Connection error: {e}")
936
 
937
  yield
938
+
939
  await tg_client.disconnect()
940
+ TELEGRAM_STATUS = "Stopped"
941
+ add_log("Telegram disconnected")
942
 
943
  app = FastAPI(lifespan=lifespan)
944
 
945
+ @app.get("/health")
946
  async def health():
947
+ return {
948
+ "status": TELEGRAM_STATUS,
949
+ "bot1_channels": TARGET_CHANNELS_1,
950
+ "bot2_channels": TARGET_CHANNELS_2
951
+ }
952
+
953
+ # Mount Gradio onto the root of FastAPI
954
+ app = gr.mount_gradio_app(app, demo, path="/")
955
 
956
  if __name__ == "__main__":
957
  uvicorn.run(app, host="0.0.0.0", port=7860)