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

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +75 -21
main.py CHANGED
@@ -19,6 +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
 
23
  # Always include "iu39f" + any channels from environment
24
  env_channels = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
@@ -29,8 +31,8 @@ CHUNK_SIZE = 20 * 1024 * 1024 # 20 MB
29
  # --- 2. TELEGRAM CLIENT ---
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
  if not BALE_BOT_TOKEN:
35
  return False
36
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
@@ -41,14 +43,18 @@ async def send_text_to_bale(text, parse_mode=None):
41
  try:
42
  resp = await client.post(url, json=payload, timeout=10)
43
  if resp.status_code != 200:
44
- print(f"❌ Bale text error: {resp.status_code} {resp.text}")
 
 
 
45
  return False
46
  return True
47
  except Exception as e:
48
- print(f"❌ Bale text request failed: {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,13 +83,36 @@ async def send_media_to_bale(file_path, caption, media_type, parse_mode=None):
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
- print(f"❌ Bale media error ({media_type}): {resp.status_code} {resp.text}")
 
 
 
 
81
  return False
82
  return True
83
  except Exception as e:
84
- print(f"❌ Bale media request failed: {e}")
 
 
 
85
  return False
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  async def download_media(message):
88
  if not message.media:
89
  return None
@@ -118,7 +147,7 @@ async def download_media(message):
118
  await message.download_media(file=path)
119
  return path
120
  except Exception as e:
121
- print(f"❌ Media download error: {e}")
122
  return None
123
 
124
  def detect_media_type(event):
@@ -146,7 +175,7 @@ def zip_file(file_path, zip_path=None):
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:
@@ -194,26 +223,41 @@ async def handler(event):
194
  caption_body = build_caption(event, username)
195
  final_caption = header + caption_body
196
 
197
- # ----- Special handling for iu39f: zip & chunk documents -----
198
  if username == "iu39f" and event.document:
199
  media_path = await download_media(event)
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
@@ -221,20 +265,23 @@ async def handler(event):
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
 
@@ -249,21 +296,28 @@ async def handler(event):
249
  await send_text_to_bale(final_caption)
250
 
251
  except Exception as e:
252
- print(f"Handler Error: {e}")
253
 
254
  # --- 5. SERVER LIFESPAN ---
255
  @asynccontextmanager
256
  async def lifespan(app: FastAPI):
 
257
  print("Connecting to Telegram...")
258
  await tg_client.connect()
259
  if not await tg_client.is_user_authorized():
260
- print("❌ TELEGRAM NOT AUTHORIZED!")
 
 
261
  else:
262
- print("✅ Telegram Connected!")
 
 
 
263
  asyncio.create_task(tg_client.run_until_disconnected())
264
 
265
  yield
266
  await tg_client.disconnect()
 
267
 
268
  app = FastAPI(lifespan=lifespan)
269
 
 
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()]
 
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
  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
  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
 
147
  await message.download_media(file=path)
148
  return path
149
  except Exception as e:
150
+ await send_log_to_bale(f"Media download error: {e}")
151
  return None
152
 
153
  def detect_media_type(event):
 
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:
 
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 > 20 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
 
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
 
 
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():
308
+ msg = "❌ TELEGRAM NOT AUTHORIZED!"
309
+ print(msg)
310
+ await send_log_to_bale(msg)
311
  else:
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
319
  await tg_client.disconnect()
320
+ await send_log_to_bale("Bot disconnected")
321
 
322
  app = FastAPI(lifespan=lifespan)
323