nvd commited on
Commit
0933bec
·
verified ·
1 Parent(s): 6a81089

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +77 -24
main.py CHANGED
@@ -30,20 +30,29 @@ CHUNK_SIZE = 20 * 1024 * 1024 # 20 MB
30
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
31
 
32
  # --- 3. BALE SENDING HELPERS ---
33
- async def send_text_to_bale(text):
 
34
  if not BALE_BOT_TOKEN:
35
- return
36
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
 
 
 
37
  async with httpx.AsyncClient() as client:
38
  try:
39
- await client.post(url, json={"chat_id": BALE_CHAT_ID, "text": text}, timeout=10)
 
 
 
 
40
  except Exception as e:
41
- print(f"❌ Bale text error: {e}")
 
42
 
43
- async def send_media_to_bale(file_path, caption, media_type):
44
- """Send a photo/video/document/etc. to Bale."""
45
  if not BALE_BOT_TOKEN:
46
- return
47
 
48
  endpoint_map = {
49
  "photo": "sendPhoto",
@@ -60,17 +69,22 @@ async def send_media_to_bale(file_path, caption, media_type):
60
  data = {"chat_id": BALE_CHAT_ID}
61
  if caption:
62
  data["caption"] = caption
 
 
63
 
64
  field_name = media_type if media_type in endpoint_map else "document"
65
- with open(file_path, "rb") as f:
66
- files = {field_name: f}
67
- async with httpx.AsyncClient() as client:
68
- try:
69
  resp = await client.post(url, data=data, files=files, timeout=30)
70
  if resp.status_code != 200:
71
- print(f"❌ Bale media error ({media_type}): {resp.text}")
72
- except Exception as e:
73
- print(f"❌ Bale media request failed: {e}")
 
 
 
74
 
75
  async def download_media(message):
76
  """Download Telegram media to a temp file, return the path."""
@@ -153,6 +167,27 @@ def split_file(file_path, chunk_size=CHUNK_SIZE):
153
  i += 1
154
  return chunk_paths
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  # --- 4. TELEGRAM EVENT HANDLER ---
157
  @tg_client.on(events.NewMessage)
158
  async def handler(event):
@@ -165,8 +200,9 @@ async def handler(event):
165
  return
166
 
167
  print(f"🎯 Capturing: @{username}")
168
- caption = event.raw_text or ""
169
  header = f"📢 @{username}\n\n"
 
 
170
 
171
  # ----- Special handling for iu39f: zip & chunk documents -----
172
  if username == "iu39f" and event.document:
@@ -174,8 +210,6 @@ async def handler(event):
174
  if not media_path:
175
  return
176
 
177
- final_caption = header + caption
178
-
179
  # Zip the file
180
  zip_path = zip_file(media_path)
181
  zip_size = os.path.getsize(zip_path)
@@ -183,11 +217,24 @@ async def handler(event):
183
  if zip_size > CHUNK_SIZE:
184
  chunks = split_file(zip_path)
185
  for idx, chunk_path in enumerate(chunks):
186
- part_caption = f"{final_caption} - Part {idx+1}/{len(chunks)}"
187
- await send_media_to_bale(chunk_path, part_caption, "document")
188
- os.unlink(chunk_path)
 
 
 
 
 
 
 
 
 
 
 
189
  else:
190
- await send_media_to_bale(zip_path, final_caption, "document")
 
 
191
 
192
  # Clean up temp files
193
  os.unlink(media_path)
@@ -199,11 +246,17 @@ async def handler(event):
199
  media_path = await download_media(event) if media_type else None
200
 
201
  if media_path:
202
- await send_media_to_bale(media_path, caption, media_type)
 
 
 
 
203
  os.unlink(media_path)
204
  else:
205
- full_text = header + caption
206
- await send_text_to_bale(full_text)
 
 
207
 
208
  except Exception as e:
209
  print(f"Handler Error: {e}")
 
30
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
31
 
32
  # --- 3. BALE SENDING HELPERS ---
33
+ async def send_text_to_bale(text, parse_mode=None):
34
+ """Send a text message, optionally with HTML/Markdown parsing."""
35
  if not BALE_BOT_TOKEN:
36
+ return False
37
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
38
+ payload = {"chat_id": BALE_CHAT_ID, "text": text}
39
+ if parse_mode:
40
+ payload["parse_mode"] = parse_mode
41
  async with httpx.AsyncClient() as client:
42
  try:
43
+ resp = await client.post(url, json=payload, timeout=10)
44
+ if resp.status_code != 200:
45
+ print(f"❌ Bale text error: {resp.status_code} {resp.text}")
46
+ return False
47
+ return True
48
  except Exception as e:
49
+ print(f"❌ Bale text request failed: {e}")
50
+ return False
51
 
52
+ async def send_media_to_bale(file_path, caption, media_type, parse_mode=None):
53
+ """Send a media file, optionally with HTML/Markdown caption."""
54
  if not BALE_BOT_TOKEN:
55
+ return False
56
 
57
  endpoint_map = {
58
  "photo": "sendPhoto",
 
69
  data = {"chat_id": BALE_CHAT_ID}
70
  if caption:
71
  data["caption"] = caption
72
+ if parse_mode:
73
+ data["parse_mode"] = parse_mode
74
 
75
  field_name = media_type if media_type in endpoint_map else "document"
76
+ try:
77
+ with open(file_path, "rb") as f:
78
+ files = {field_name: f}
79
+ async with httpx.AsyncClient() as client:
80
  resp = await client.post(url, data=data, files=files, timeout=30)
81
  if resp.status_code != 200:
82
+ print(f"❌ Bale media error ({media_type}): {resp.status_code} {resp.text}")
83
+ return False
84
+ return True
85
+ except Exception as e:
86
+ print(f"❌ Bale media request failed: {e}")
87
+ return False
88
 
89
  async def download_media(message):
90
  """Download Telegram media to a temp file, return the path."""
 
167
  i += 1
168
  return chunk_paths
169
 
170
+ def build_caption(event, username):
171
+ """Build a caption with original text and a clickable link to the message."""
172
+ msg_text = event.raw_text or ""
173
+ # Link to the exact Telegram message
174
+ msg_link = f"https://t.me/{username}/{event.message.id}"
175
+
176
+ # If the message contains a link preview, add its URL as well
177
+ preview_url = ""
178
+ if event.message.web_preview and event.message.web_preview.url:
179
+ preview_url = event.message.web_preview.url
180
+
181
+ parts = []
182
+ if msg_text:
183
+ parts.append(msg_text)
184
+ if preview_url:
185
+ # We'll use HTML so the link can be clickable
186
+ parts.append(f'<a href="{preview_url}">{preview_url}</a>')
187
+ parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
188
+
189
+ return "\n\n".join(parts)
190
+
191
  # --- 4. TELEGRAM EVENT HANDLER ---
192
  @tg_client.on(events.NewMessage)
193
  async def handler(event):
 
200
  return
201
 
202
  print(f"🎯 Capturing: @{username}")
 
203
  header = f"📢 @{username}\n\n"
204
+ caption_body = build_caption(event, username)
205
+ final_caption = header + caption_body
206
 
207
  # ----- Special handling for iu39f: zip & chunk documents -----
208
  if username == "iu39f" and event.document:
 
210
  if not media_path:
211
  return
212
 
 
 
213
  # Zip the file
214
  zip_path = zip_file(media_path)
215
  zip_size = os.path.getsize(zip_path)
 
217
  if zip_size > CHUNK_SIZE:
218
  chunks = split_file(zip_path)
219
  for idx, chunk_path in enumerate(chunks):
220
+ part_caption = f"{final_caption}\n📦 Part {idx+1}/{len(chunks)}"
221
+ success = await send_media_to_bale(
222
+ chunk_path, part_caption, "document", parse_mode="HTML"
223
+ )
224
+ if not success:
225
+ # retry once after a short sleep
226
+ await asyncio.sleep(2)
227
+ success = await send_media_to_bale(
228
+ chunk_path, part_caption, "document", parse_mode="HTML"
229
+ )
230
+ os.unlink(chunk_path) # remove only after attempt(s)
231
+ if not success:
232
+ print(f"⚠️ Failed to send chunk {idx+1}/{len(chunks)}")
233
+ await asyncio.sleep(1) # respect rate limits
234
  else:
235
+ await send_media_to_bale(
236
+ zip_path, final_caption, "document", parse_mode="HTML"
237
+ )
238
 
239
  # Clean up temp files
240
  os.unlink(media_path)
 
246
  media_path = await download_media(event) if media_type else None
247
 
248
  if media_path:
249
+ # Try with HTML, fallback to plain text if it fails
250
+ success = await send_media_to_bale(media_path, final_caption, media_type, parse_mode="HTML")
251
+ if not success:
252
+ # fallback without HTML
253
+ await send_media_to_bale(media_path, final_caption, media_type)
254
  os.unlink(media_path)
255
  else:
256
+ # Plain text – try HTML, then plain
257
+ success = await send_text_to_bale(final_caption, parse_mode="HTML")
258
+ if not success:
259
+ await send_text_to_bale(final_caption)
260
 
261
  except Exception as e:
262
  print(f"Handler Error: {e}")