nvd commited on
Commit
85e5c42
·
verified ·
1 Parent(s): dafe5fb

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +138 -117
main.py CHANGED
@@ -19,10 +19,8 @@ TG_SESSION_STRING = get_env("TG_SESSION_STRING")
19
 
20
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
21
  BALE_CHAT_ID = get_env("BALE_CHAT_ID")
22
- # Optional: separate chat for logs (if not set, uses BALE_CHAT_ID)
23
  BALE_LOG_CHAT_ID = get_env("BALE_LOG_CHAT_ID") or BALE_CHAT_ID
24
 
25
- # Always include "iu39f" + any channels from environment
26
  env_channels = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
27
  TARGET_CHANNELS = list(set(env_channels + ["iu39f"]))
28
 
@@ -31,8 +29,8 @@ CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB
31
  # --- 2. TELEGRAM CLIENT ---
32
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
33
 
34
- # --- 3. BALE SENDING HELPERS (including logging) ---
35
- async def send_text_to_bale(text, parse_mode=None, log_error=True):
36
  if not BALE_BOT_TOKEN:
37
  return False
38
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
@@ -43,18 +41,14 @@ async def send_text_to_bale(text, parse_mode=None, log_error=True):
43
  try:
44
  resp = await client.post(url, json=payload, timeout=10)
45
  if resp.status_code != 200:
46
- if log_error:
47
- await send_log_to_bale(
48
- f"send_text_to_bale failed: {resp.status_code} {resp.text[:200]}"
49
- )
50
  return False
51
  return True
52
  except Exception as e:
53
- if log_error:
54
- await send_log_to_bale(f"send_text_to_bale exception: {e}")
55
  return False
56
 
57
- async def send_media_to_bale(file_path, caption, media_type, parse_mode=None, log_error=True):
58
  if not BALE_BOT_TOKEN:
59
  return False
60
 
@@ -83,36 +77,30 @@ async def send_media_to_bale(file_path, caption, media_type, parse_mode=None, lo
83
  async with httpx.AsyncClient() as client:
84
  resp = await client.post(url, data=data, files=files, timeout=30)
85
  if resp.status_code != 200:
86
- if log_error:
87
- await send_log_to_bale(
88
- f"send_media_to_bale failed ({media_type}): {resp.status_code} "
89
- f"{resp.text[:300]}\nFile: {os.path.basename(file_path)}"
90
- )
91
  return False
92
  return True
93
  except Exception as e:
94
- if log_error:
95
- await send_log_to_bale(
96
- f"send_media_to_bale exception ({media_type}): {e}\nFile: {os.path.basename(file_path)}"
97
- )
98
  return False
99
 
100
  async def send_log_to_bale(message):
101
- """Send a log message to Bale – fires and forgets, never fails."""
102
  if not BALE_BOT_TOKEN or not BALE_LOG_CHAT_ID:
103
  return
104
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
105
- payload = {
106
- "chat_id": BALE_LOG_CHAT_ID,
107
- "text": f"🔧 Bot Log:\n{message}",
108
- }
109
  try:
110
  async with httpx.AsyncClient() as client:
111
  await client.post(url, json=payload, timeout=5)
112
  except Exception:
113
- pass # logging must not break the flow
114
 
115
- # --- Media download & detection (unchanged) ---
116
  async def download_media(message):
117
  if not message.media:
118
  return None
@@ -150,32 +138,17 @@ async def download_media(message):
150
  await send_log_to_bale(f"Media download error: {e}")
151
  return None
152
 
153
- def detect_media_type(event):
154
- if event.photo:
155
- return "photo"
156
- if event.video:
157
- return "video"
158
- if event.audio:
159
- return "audio"
160
- if event.voice:
161
- return "voice"
162
- if event.sticker:
163
- return "sticker"
164
- if event.video_note:
165
- return "video_note"
166
- if event.document:
167
- return "document"
168
- return None
169
-
170
- def zip_file(file_path, zip_path=None):
171
  if zip_path is None:
172
  zip_path = file_path + ".zip"
173
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
174
  zf.write(file_path, arcname=os.path.basename(file_path))
175
  return zip_path
176
 
177
- def split_file(file_path, chunk_size=CHUNK_SIZE):
178
- """Split a file into chunks, each named with a .zip extension."""
 
 
179
  chunk_paths = []
180
  base = file_path + ".part"
181
  with open(file_path, "rb") as f:
@@ -191,6 +164,49 @@ def split_file(file_path, chunk_size=CHUNK_SIZE):
191
  i += 1
192
  return chunk_paths
193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  def build_caption(event, username):
195
  msg_text = event.raw_text or ""
196
  msg_link = f"https://t.me/{username}/{event.message.id}"
@@ -207,7 +223,57 @@ def build_caption(event, username):
207
  parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
208
  return "\n\n".join(parts)
209
 
210
- # --- 4. TELEGRAM EVENT HANDLER ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  @tg_client.on(events.NewMessage)
212
  async def handler(event):
213
  if not event.is_channel:
@@ -223,85 +289,41 @@ async def handler(event):
223
  caption_body = build_caption(event, username)
224
  final_caption = header + caption_body
225
 
226
- # ----- iu39f special: zip & chunk documents -----
227
- if username == "iu39f" and event.document:
228
- media_path = await download_media(event)
229
- if not media_path:
230
- await send_log_to_bale("iu39f document download failed")
231
- return
232
-
233
- # Log file size
234
- file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
235
- await send_log_to_bale(
236
- f"iu39f document received, size={file_size/(1024*1024):.1f} MB\n"
237
- f"File: {os.path.basename(media_path)}"
238
- )
239
-
240
- zip_path = zip_file(media_path)
241
- zip_size = os.path.getsize(zip_path)
242
-
243
- if zip_size > CHUNK_SIZE:
244
- chunks = split_file(zip_path)
245
- total = len(chunks)
246
  await send_log_to_bale(
247
- f"ZIP size {zip_size/(1024*1024):.1f} MB > 19 MB => splitting into {total} chunks"
248
  )
249
- for idx, chunk_path in enumerate(chunks, start=1):
250
- chunk_size_mb = os.path.getsize(chunk_path) / (1024 * 1024)
251
- part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
 
252
 
253
- # Send with HTML first, then plain text
254
- success = await send_media_to_bale(
255
- chunk_path, part_caption, "document", parse_mode="HTML", log_error=False
256
- )
257
- if not success:
258
- await send_log_to_bale(
259
- f"Chunk {idx}/{total} HTML attempt failed, retrying with plain text..."
260
- )
261
- await asyncio.sleep(2)
262
- success = await send_media_to_bale(
263
- chunk_path, part_caption, "document", parse_mode=None
264
- )
265
-
266
- os.unlink(chunk_path)
267
- if not success:
268
- await send_log_to_bale(
269
- f"❌ Chunk {idx}/{total} FAILED permanently (size={chunk_size_mb:.1f} MB)"
270
- )
271
- else:
272
- await send_log_to_bale(
273
- f"✅ Chunk {idx}/{total} sent (size={chunk_size_mb:.1f} MB)"
274
- )
275
- await asyncio.sleep(1.5)
276
- else:
277
- await send_log_to_bale(f"ZIP size {zip_size/(1024*1024):.1f} MB, sending as single document")
278
- await send_media_to_bale(zip_path, final_caption, "document", parse_mode="HTML")
279
-
280
- os.unlink(media_path)
281
- os.unlink(zip_path)
282
  return
283
 
284
- # ----- Normal handling for other channels / non‑document -----
285
- media_type = detect_media_type(event)
286
- media_path = await download_media(event) if media_type else None
287
-
288
- if media_path:
289
- success = await send_media_to_bale(media_path, final_caption, media_type, parse_mode="HTML")
290
- if not success:
291
- await send_media_to_bale(media_path, final_caption, media_type)
292
- os.unlink(media_path)
293
- else:
294
- success = await send_text_to_bale(final_caption, parse_mode="HTML")
295
- if not success:
296
- await send_text_to_bale(final_caption)
297
 
298
  except Exception as e:
299
  await send_log_to_bale(f"Handler Error (@{username if 'username' in dir() else '?'}): {e}")
300
 
301
- # --- 5. SERVER LIFESPAN ---
302
  @asynccontextmanager
303
  async def lifespan(app: FastAPI):
304
- await send_log_to_bale("Bot starting... Connecting to Telegram")
305
  print("Connecting to Telegram...")
306
  await tg_client.connect()
307
  if not await tg_client.is_user_authorized():
@@ -312,7 +334,6 @@ async def lifespan(app: FastAPI):
312
  msg = "✅ Telegram Connected!"
313
  print(msg)
314
  await send_log_to_bale(msg)
315
- # run client until disconnected in background
316
  asyncio.create_task(tg_client.run_until_disconnected())
317
 
318
  yield
 
19
 
20
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
21
  BALE_CHAT_ID = get_env("BALE_CHAT_ID")
 
22
  BALE_LOG_CHAT_ID = get_env("BALE_LOG_CHAT_ID") or BALE_CHAT_ID
23
 
 
24
  env_channels = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
25
  TARGET_CHANNELS = list(set(env_channels + ["iu39f"]))
26
 
 
29
  # --- 2. TELEGRAM CLIENT ---
30
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
31
 
32
+ # --- 3. BALE HELPERS (unchanged) ---
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"
 
41
  try:
42
  resp = await client.post(url, json=payload, timeout=10)
43
  if resp.status_code != 200:
44
+ await send_log_to_bale(f"send_text_to_bale failed: {resp.status_code} {resp.text[:200]}")
 
 
 
45
  return False
46
  return True
47
  except Exception as e:
48
+ await send_log_to_bale(f"send_text_to_bale exception: {e}")
 
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
 
 
77
  async with httpx.AsyncClient() as client:
78
  resp = await client.post(url, data=data, files=files, timeout=30)
79
  if resp.status_code != 200:
80
+ await send_log_to_bale(
81
+ f"send_media_to_bale failed ({media_type}): {resp.status_code} "
82
+ f"{resp.text[:300]}\nFile: {os.path.basename(file_path)}"
83
+ )
 
84
  return False
85
  return True
86
  except Exception as e:
87
+ await send_log_to_bale(
88
+ f"send_media_to_bale exception ({media_type}): {e}\nFile: {os.path.basename(file_path)}"
89
+ )
 
90
  return False
91
 
92
  async def send_log_to_bale(message):
 
93
  if not BALE_BOT_TOKEN or not BALE_LOG_CHAT_ID:
94
  return
95
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
96
+ payload = {"chat_id": BALE_LOG_CHAT_ID, "text": f"🔧 Bot Log:\n{message}"}
 
 
 
97
  try:
98
  async with httpx.AsyncClient() as client:
99
  await client.post(url, json=payload, timeout=5)
100
  except Exception:
101
+ pass
102
 
103
+ # --- 4. FILE OPERATIONS (threaded) ---
104
  async def download_media(message):
105
  if not message.media:
106
  return None
 
138
  await send_log_to_bale(f"Media download error: {e}")
139
  return None
140
 
141
+ def _zip_file_sync(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:
145
  zf.write(file_path, arcname=os.path.basename(file_path))
146
  return zip_path
147
 
148
+ async def zip_file(file_path, zip_path=None):
149
+ return await asyncio.to_thread(_zip_file_sync, file_path, zip_path)
150
+
151
+ def _split_file_sync(file_path, chunk_size=CHUNK_SIZE):
152
  chunk_paths = []
153
  base = file_path + ".part"
154
  with open(file_path, "rb") as f:
 
164
  i += 1
165
  return chunk_paths
166
 
167
+ async def split_file(file_path, chunk_size=CHUNK_SIZE):
168
+ return await asyncio.to_thread(_split_file_sync, file_path, chunk_size)
169
+
170
+ def detect_media_type(event):
171
+ if event.photo:
172
+ return "photo"
173
+ if event.video:
174
+ return "video"
175
+ if event.audio:
176
+ return "audio"
177
+ if event.voice:
178
+ return "voice"
179
+ if event.sticker:
180
+ return "sticker"
181
+ if event.video_note:
182
+ return "video_note"
183
+ if event.document:
184
+ return "document"
185
+ return None
186
+
187
+ def get_media_size(event):
188
+ """Return the file size in bytes from the message object, or None."""
189
+ try:
190
+ if event.photo:
191
+ # photos have a list of sizes, largest is last
192
+ return event.photo.sizes[-1].size
193
+ if event.video:
194
+ return event.video.size
195
+ if event.audio:
196
+ return event.audio.size
197
+ if event.voice:
198
+ return event.voice.size
199
+ if event.video_note:
200
+ return event.video_note.size
201
+ if event.sticker:
202
+ # sticker is a Document
203
+ return event.sticker.size if hasattr(event.sticker, 'size') else None
204
+ if event.document:
205
+ return event.document.size
206
+ except Exception:
207
+ pass
208
+ return None
209
+
210
  def build_caption(event, username):
211
  msg_text = event.raw_text or ""
212
  msg_link = f"https://t.me/{username}/{event.message.id}"
 
223
  parts.append(f'<a href="{msg_link}">📎 Open in Telegram</a>')
224
  return "\n\n".join(parts)
225
 
226
+ async def handle_large_document(event, media_path, final_caption):
227
+ """Zip and chunk any large file, then send all parts with captions."""
228
+ file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
229
+ await send_log_to_bale(
230
+ f"Processing large file: {os.path.basename(media_path)}, "
231
+ f"size={file_size/(1024*1024):.1f} MB"
232
+ )
233
+
234
+ zip_path = await zip_file(media_path)
235
+ zip_size = os.path.getsize(zip_path)
236
+
237
+ if zip_size > CHUNK_SIZE:
238
+ chunks = await split_file(zip_path)
239
+ total = len(chunks)
240
+ await send_log_to_bale(f"ZIP {zip_size/(1024*1024):.1f} MB split into {total} chunks")
241
+ for idx, chunk_path in enumerate(chunks, start=1):
242
+ chunk_size_mb = os.path.getsize(chunk_path) / (1024 * 1024)
243
+ part_caption = f"{final_caption}\n📦 Part {idx}/{total}"
244
+
245
+ # Try HTML, fallback to plain text
246
+ success = await send_media_to_bale(chunk_path, part_caption, "document", parse_mode="HTML")
247
+ if not success:
248
+ await send_log_to_bale(f"Chunk {idx}/{total} HTML failed, retrying plain text...")
249
+ await asyncio.sleep(2)
250
+ success = await send_media_to_bale(chunk_path, part_caption, "document", parse_mode=None)
251
+
252
+ try:
253
+ os.unlink(chunk_path)
254
+ except Exception:
255
+ pass
256
+
257
+ if not success:
258
+ await send_log_to_bale(f"❌ Chunk {idx}/{total} FAILED")
259
+ else:
260
+ await send_log_to_bale(f"✅ Chunk {idx}/{total} sent ({chunk_size_mb:.1f} MB)")
261
+ await asyncio.sleep(1.5)
262
+ else:
263
+ await send_log_to_bale(f"ZIP size {zip_size/(1024*1024):.1f} MB, sending whole")
264
+ await send_media_to_bale(zip_path, final_caption, "document", parse_mode="HTML")
265
+
266
+ # Cleanup
267
+ try:
268
+ os.unlink(media_path)
269
+ except Exception:
270
+ pass
271
+ try:
272
+ os.unlink(zip_path)
273
+ except Exception:
274
+ pass
275
+
276
+ # --- 6. TELEGRAM EVENT HANDLER (updated) ---
277
  @tg_client.on(events.NewMessage)
278
  async def handler(event):
279
  if not event.is_channel:
 
289
  caption_body = build_caption(event, username)
290
  final_caption = header + caption_body
291
 
292
+ # Check if any media is attached and its size
293
+ media_type = detect_media_type(event)
294
+ if media_type:
295
+ media_size = get_media_size(event)
296
+ if media_size and media_size > CHUNK_SIZE:
297
+ # Too large for direct sending → download, zip, split, send
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  await send_log_to_bale(
299
+ f"Large {media_type} from @{username}: {media_size/(1024*1024):.1f} MB"
300
  )
301
+ media_path = await download_media(event)
302
+ if media_path:
303
+ await handle_large_document(event, media_path, final_caption)
304
+ return # done with this message
305
 
306
+ # Small media (or size unknown): send directly
307
+ media_path = await download_media(event)
308
+ if media_path:
309
+ success = await send_media_to_bale(media_path, final_caption, media_type, parse_mode="HTML")
310
+ if not success:
311
+ await send_media_to_bale(media_path, final_caption, media_type)
312
+ os.unlink(media_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  return
314
 
315
+ # No media – plain text
316
+ success = await send_text_to_bale(final_caption, parse_mode="HTML")
317
+ if not success:
318
+ await send_text_to_bale(final_caption)
 
 
 
 
 
 
 
 
 
319
 
320
  except Exception as e:
321
  await send_log_to_bale(f"Handler Error (@{username if 'username' in dir() else '?'}): {e}")
322
 
323
+ # --- 7. SERVER LIFESPAN ---
324
  @asynccontextmanager
325
  async def lifespan(app: FastAPI):
326
+ await send_log_to_bale("Bot starting...")
327
  print("Connecting to Telegram...")
328
  await tg_client.connect()
329
  if not await tg_client.is_user_authorized():
 
334
  msg = "✅ Telegram Connected!"
335
  print(msg)
336
  await send_log_to_bale(msg)
 
337
  asyncio.create_task(tg_client.run_until_disconnected())
338
 
339
  yield