nvd commited on
Commit
add1ba6
·
verified ·
1 Parent(s): 0f42019

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +62 -39
main.py CHANGED
@@ -34,12 +34,9 @@ BALE_API_SEMAPHORE = asyncio.Semaphore(3)
34
  # --- 2. TELEGRAM CLIENT ---
35
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
36
 
37
- # --- 3. BALE HELPERS (with retry & splitting) ---
38
 
39
  async def send_text_to_bale(text, parse_mode=None, retries=3, log_error=True):
40
- """
41
- Send a single text message to Bale (no splitting). Used internally.
42
- """
43
  if not BALE_BOT_TOKEN:
44
  return False
45
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
@@ -141,10 +138,7 @@ async def send_log_to_bale(message):
141
 
142
 
143
  def split_long_text(text, max_len=MAX_TEXT_LEN):
144
- """
145
- Split a long text into chunks of max_len characters.
146
- Attempts to split at newlines or spaces, falling back to hard cuts.
147
- """
148
  if len(text) <= max_len:
149
  return [text]
150
 
@@ -153,8 +147,7 @@ def split_long_text(text, max_len=MAX_TEXT_LEN):
153
  if len(text) <= max_len:
154
  chunks.append(text)
155
  break
156
-
157
- # Try to split at a newline
158
  split_at = text.rfind('\n', 0, max_len)
159
  if split_at == -1:
160
  split_at = text.rfind(' ', 0, max_len)
@@ -171,18 +164,14 @@ def split_long_text(text, max_len=MAX_TEXT_LEN):
171
 
172
  async def send_text_or_caption(text, parse_mode="HTML", is_caption=False, max_len=MAX_TEXT_LEN):
173
  """
174
- Send a text (or caption) that may exceed max length by splitting it into
175
- multiple messages. For captions (used with media), the first chunk is
176
- returned so it can be attached to the media, and the remaining chunks
177
- are sent as separate text messages.
178
- Returns:
179
- - For non-captions: bool (success status)
180
- - For captions: (str, bool) -> (first_part_of_caption, overall_success)
181
  """
182
  if not text:
183
  return ("" if is_caption else True)
184
 
185
- # Turn off HTML when splitting because it would break tags
186
  if len(text) > max_len and parse_mode:
187
  parse_mode = None
188
 
@@ -190,12 +179,10 @@ async def send_text_or_caption(text, parse_mode="HTML", is_caption=False, max_le
190
  total = len(chunks)
191
 
192
  if is_caption:
193
- # For media: return the first chunk, and send the rest as text messages
194
  first_chunk = chunks[0]
195
  if total == 1:
196
  return first_chunk, True
197
 
198
- # Add continuation marker to the first chunk (so user knows it's split)
199
  first_chunk = first_chunk + f"\n… (1/{total})"
200
  success = True
201
  for i in range(1, total):
@@ -207,7 +194,7 @@ async def send_text_or_caption(text, parse_mode="HTML", is_caption=False, max_le
207
  await asyncio.sleep(0.5)
208
  return first_chunk, success
209
 
210
- # Non-caption (pure text message) – send all parts
211
  success = True
212
  for i, chunk in enumerate(chunks, 1):
213
  if total > 1:
@@ -220,7 +207,8 @@ async def send_text_or_caption(text, parse_mode="HTML", is_caption=False, max_le
220
  await asyncio.sleep(0.5)
221
  return success
222
 
223
- # --- 4. SAFE TEMP DIRECTORY HELPERS ---
 
224
  def create_temp_dir():
225
  return tempfile.mkdtemp(prefix="tg2bale_")
226
 
@@ -230,6 +218,8 @@ def cleanup_temp_dir(temp_dir):
230
  except Exception:
231
  pass
232
 
 
 
233
  async def download_media(message, temp_dir):
234
  if not message.media:
235
  return None
@@ -266,6 +256,7 @@ async def download_media(message, temp_dir):
266
  await send_log_to_bale(f"Media download error: {e}")
267
  return None
268
 
 
269
  def zip_file_sync(file_path, zip_path):
270
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
271
  zf.write(file_path, arcname=os.path.basename(file_path))
@@ -274,6 +265,7 @@ def zip_file_sync(file_path, zip_path):
274
  async def zip_file(file_path, zip_path):
275
  return await asyncio.to_thread(zip_file_sync, file_path, zip_path)
276
 
 
277
  def split_file_sync(file_path, chunk_size=CHUNK_SIZE):
278
  chunk_paths = []
279
  base = file_path + ".part"
@@ -293,6 +285,8 @@ def split_file_sync(file_path, chunk_size=CHUNK_SIZE):
293
  async def split_file(file_path, chunk_size=CHUNK_SIZE):
294
  return await asyncio.to_thread(split_file_sync, file_path, chunk_size)
295
 
 
 
296
  def detect_media_type(event):
297
  if event.photo:
298
  return "photo"
@@ -330,9 +324,21 @@ def get_media_size(event):
330
  pass
331
  return None
332
 
333
- def build_caption(event, username):
 
 
 
 
 
 
 
 
 
 
 
 
334
  msg_text = event.raw_text or ""
335
- msg_link = f"https://t.me/{username}/{event.message.id}"
336
 
337
  preview_url = ""
338
  if event.message.web_preview and event.message.web_preview.url:
@@ -343,9 +349,11 @@ def build_caption(event, username):
343
  parts.append(msg_text)
344
  if preview_url:
345
  parts.append(f'<a href="{preview_url}">{preview_url}</a>')
346
- parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
 
347
  return "\n\n".join(parts)
348
 
 
349
  async def handle_large_document(event, media_path, final_caption, temp_dir):
350
  file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
351
  await send_log_to_bale(
@@ -364,7 +372,6 @@ async def handle_large_document(event, media_path, final_caption, temp_dir):
364
  chunk_size_mb = os.path.getsize(chunk_path) / (1024 * 1024)
365
  part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
366
 
367
- # Split caption if too long for this chunk as well
368
  first_part, _ = await send_text_or_caption(part_caption, parse_mode="HTML", is_caption=True)
369
  success = await send_media_to_bale(chunk_path, first_part, "document", parse_mode="HTML")
370
  if not success:
@@ -379,25 +386,31 @@ async def handle_large_document(event, media_path, final_caption, temp_dir):
379
  first_part, _ = await send_text_or_caption(final_caption, parse_mode="HTML", is_caption=True)
380
  await send_media_to_bale(zip_path, first_part, "document", parse_mode="HTML")
381
 
382
- # --- 6. TELEGRAM EVENT HANDLER ---
 
383
  @tg_client.on(events.NewMessage)
384
  async def handler(event):
385
  if not event.is_channel:
386
  return
 
 
387
  try:
388
  chat = await event.get_chat()
389
- username = getattr(chat, 'username', '').lower()
390
- if username not in TARGET_CHANNELS:
391
- return
392
 
393
- print(f"🎯 Capturing: @{username}")
394
- header = f"📢 @{username}\n\n"
395
- caption_body = build_caption(event, username)
 
 
 
 
 
396
  final_caption = header + caption_body
397
 
398
  media_type = detect_media_type(event)
399
  if not media_type:
400
- # Plain text – automatically split if needed
401
  await send_text_or_caption(final_caption, parse_mode="HTML")
402
  return
403
 
@@ -407,7 +420,7 @@ async def handler(event):
407
  async with LARGE_FILE_SEMAPHORE:
408
  temp_dir = create_temp_dir()
409
  try:
410
- await send_log_to_bale(f"Large {media_type} from @{username}: {media_size/(1024*1024):.1f} MB")
411
  media_path = await download_media(event, temp_dir)
412
  if media_path:
413
  await handle_large_document(event, media_path, final_caption, temp_dir)
@@ -415,20 +428,30 @@ async def handler(event):
415
  cleanup_temp_dir(temp_dir)
416
  return
417
 
418
- # Small media – send with possibly split caption
419
  temp_dir = create_temp_dir()
420
  try:
421
  media_path = await download_media(event, temp_dir)
422
  if media_path:
423
  first_caption, _ = await send_text_or_caption(final_caption, parse_mode="HTML", is_caption=True)
424
- await send_media_to_bale(media_path, first_caption, media_type, parse_mode="HTML")
 
 
 
 
 
 
 
 
425
  finally:
426
  cleanup_temp_dir(temp_dir)
427
 
428
  except Exception as e:
429
- await send_log_to_bale(f"Handler Error (@{username if 'username' in dir() else '?'}): {e}")
 
 
430
 
431
- # --- 7. SERVER LIFESPAN ---
432
  @asynccontextmanager
433
  async def lifespan(app: FastAPI):
434
  await send_log_to_bale("Bot starting...")
 
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"
 
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
 
 
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)
 
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
 
 
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):
 
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:
 
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
  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
 
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))
 
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"
 
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"
 
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:
 
349
  parts.append(msg_text)
350
  if preview_url:
351
  parts.append(f'<a href="{preview_url}">{preview_url}</a>')
352
+ if msg_link:
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(
 
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:
 
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
+ # If the chat has a username, apply channel filter; otherwise process anyway
402
+ if username:
403
+ if username.lower() not in TARGET_CHANNELS:
404
+ return
405
+
406
+ # Build header
407
+ header = f"📢 @{username}\n\n" if username else f"📢 {chat.title}\n\n"
408
+ caption_body = build_caption(event, chat)
409
  final_caption = header + caption_body
410
 
411
  media_type = detect_media_type(event)
412
  if not media_type:
413
+ # Plain text
414
  await send_text_or_caption(final_caption, parse_mode="HTML")
415
  return
416
 
 
420
  async with LARGE_FILE_SEMAPHORE:
421
  temp_dir = create_temp_dir()
422
  try:
423
+ await send_log_to_bale(f"Large {media_type} from {username or chat.title}: {media_size/(1024*1024):.1f} MB")
424
  media_path = await download_media(event, temp_dir)
425
  if media_path:
426
  await handle_large_document(event, media_path, final_caption, temp_dir)
 
428
  cleanup_temp_dir(temp_dir)
429
  return
430
 
431
+ # Small media
432
  temp_dir = create_temp_dir()
433
  try:
434
  media_path = await download_media(event, temp_dir)
435
  if media_path:
436
  first_caption, _ = await send_text_or_caption(final_caption, parse_mode="HTML", is_caption=True)
437
+ success = await send_media_to_bale(media_path, first_caption, media_type, parse_mode="HTML")
438
+ if not success:
439
+ # Fallback: zip and send as document
440
+ await send_log_to_bale(f"Direct send failed for {media_type}, trying as document...")
441
+ zip_path = os.path.join(temp_dir, "fallback.zip")
442
+ await zip_file(media_path, zip_path)
443
+ success = await send_media_to_bale(zip_path, first_caption, "document", parse_mode=None)
444
+ if not success:
445
+ await send_log_to_bale(f"Fallback also failed for {media_type}")
446
  finally:
447
  cleanup_temp_dir(temp_dir)
448
 
449
  except Exception as e:
450
+ name = username if username else getattr(chat, 'title', '?') if chat else '?'
451
+ await send_log_to_bale(f"Handler Error (@{name}): {e}")
452
+
453
 
454
+ # --- 8. SERVER LIFESPAN ---
455
  @asynccontextmanager
456
  async def lifespan(app: FastAPI):
457
  await send_log_to_bale("Bot starting...")