nvd commited on
Commit
6965cce
·
verified ·
1 Parent(s): 0933bec

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +15 -25
main.py CHANGED
@@ -31,7 +31,6 @@ tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_H
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"
@@ -50,7 +49,6 @@ async def send_text_to_bale(text, parse_mode=None):
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
 
@@ -87,7 +85,6 @@ async def send_media_to_bale(file_path, caption, media_type, parse_mode=None):
87
  return False
88
 
89
  async def download_media(message):
90
- """Download Telegram media to a temp file, return the path."""
91
  if not message.media:
92
  return None
93
  try:
@@ -125,7 +122,6 @@ async def download_media(message):
125
  return None
126
 
127
  def detect_media_type(event):
128
- """Return the media type string based on event attributes."""
129
  if event.photo:
130
  return "photo"
131
  if event.video:
@@ -143,7 +139,6 @@ def detect_media_type(event):
143
  return None
144
 
145
  def zip_file(file_path, zip_path=None):
146
- """Create a ZIP archive containing the file."""
147
  if zip_path is None:
148
  zip_path = file_path + ".zip"
149
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
@@ -151,7 +146,7 @@ def zip_file(file_path, zip_path=None):
151
  return zip_path
152
 
153
  def split_file(file_path, chunk_size=CHUNK_SIZE):
154
- """Split a file into chunks, returns list of chunk file paths."""
155
  chunk_paths = []
156
  base = file_path + ".part"
157
  with open(file_path, "rb") as f:
@@ -160,7 +155,7 @@ def split_file(file_path, chunk_size=CHUNK_SIZE):
160
  chunk_data = f.read(chunk_size)
161
  if not chunk_data:
162
  break
163
- chunk_path = f"{base}{i:03d}"
164
  with open(chunk_path, "wb") as chunk_file:
165
  chunk_file.write(chunk_data)
166
  chunk_paths.append(chunk_path)
@@ -168,12 +163,9 @@ def split_file(file_path, chunk_size=CHUNK_SIZE):
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
@@ -182,10 +174,8 @@ def build_caption(event, username):
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 ---
@@ -210,50 +200,50 @@ async def handler(event):
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)
216
 
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)
241
  os.unlink(zip_path)
242
  return
243
 
244
- # ----- Normal behaviour for other channels / non‑document media -----
245
  media_type = detect_media_type(event)
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)
 
31
 
32
  # --- 3. BALE SENDING HELPERS ---
33
  async def send_text_to_bale(text, parse_mode=None):
 
34
  if not BALE_BOT_TOKEN:
35
  return False
36
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
 
49
  return False
50
 
51
  async def send_media_to_bale(file_path, caption, media_type, parse_mode=None):
 
52
  if not BALE_BOT_TOKEN:
53
  return False
54
 
 
85
  return False
86
 
87
  async def download_media(message):
 
88
  if not message.media:
89
  return None
90
  try:
 
122
  return None
123
 
124
  def detect_media_type(event):
 
125
  if event.photo:
126
  return "photo"
127
  if event.video:
 
139
  return None
140
 
141
  def zip_file(file_path, zip_path=None):
 
142
  if zip_path is None:
143
  zip_path = file_path + ".zip"
144
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
 
146
  return zip_path
147
 
148
  def split_file(file_path, chunk_size=CHUNK_SIZE):
149
+ """Split a file into chunks, each named with a .zip extension for Bale."""
150
  chunk_paths = []
151
  base = file_path + ".part"
152
  with open(file_path, "rb") as f:
 
155
  chunk_data = f.read(chunk_size)
156
  if not chunk_data:
157
  break
158
+ chunk_path = f"{base}{i:03d}.zip"
159
  with open(chunk_path, "wb") as chunk_file:
160
  chunk_file.write(chunk_data)
161
  chunk_paths.append(chunk_path)
 
163
  return chunk_paths
164
 
165
  def build_caption(event, username):
 
166
  msg_text = event.raw_text or ""
 
167
  msg_link = f"https://t.me/{username}/{event.message.id}"
168
 
 
169
  preview_url = ""
170
  if event.message.web_preview and event.message.web_preview.url:
171
  preview_url = event.message.web_preview.url
 
174
  if msg_text:
175
  parts.append(msg_text)
176
  if preview_url:
 
177
  parts.append(f'<a href="{preview_url}">{preview_url}</a>')
178
  parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
 
179
  return "\n\n".join(parts)
180
 
181
  # --- 4. TELEGRAM EVENT HANDLER ---
 
200
  if not media_path:
201
  return
202
 
 
203
  zip_path = zip_file(media_path)
204
  zip_size = os.path.getsize(zip_path)
205
 
206
  if zip_size > CHUNK_SIZE:
207
  chunks = split_file(zip_path)
208
+ total = len(chunks)
209
+ for idx, chunk_path in enumerate(chunks, start=1):
210
+ part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
211
+
212
+ # Try HTML, then fallback to plain text
213
  success = await send_media_to_bale(
214
  chunk_path, part_caption, "document", parse_mode="HTML"
215
  )
216
  if not success:
 
217
  await asyncio.sleep(2)
218
  success = await send_media_to_bale(
219
+ chunk_path, part_caption, "document", parse_mode=None
220
  )
221
+
222
+ os.unlink(chunk_path)
223
  if not success:
224
+ print(f"❌ Failed to send chunk {idx}/{total}")
225
+ else:
226
+ print(f"✅ Sent chunk {idx}/{total}")
227
+ await asyncio.sleep(1.5)
228
  else:
229
  await send_media_to_bale(
230
  zip_path, final_caption, "document", parse_mode="HTML"
231
  )
232
 
 
233
  os.unlink(media_path)
234
  os.unlink(zip_path)
235
  return
236
 
237
+ # ----- Normal channels / non‑document media -----
238
  media_type = detect_media_type(event)
239
  media_path = await download_media(event) if media_type else None
240
 
241
  if media_path:
 
242
  success = await send_media_to_bale(media_path, final_caption, media_type, parse_mode="HTML")
243
  if not success:
 
244
  await send_media_to_bale(media_path, final_caption, media_type)
245
  os.unlink(media_path)
246
  else:
 
247
  success = await send_text_to_bale(final_caption, parse_mode="HTML")
248
  if not success:
249
  await send_text_to_bale(final_caption)