nvd commited on
Commit
ca7f6fc
·
verified ·
1 Parent(s): 0ed05eb

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +244 -94
main.py CHANGED
@@ -4,6 +4,7 @@ import tempfile
4
  import zipfile
5
  import httpx
6
  import shutil
 
7
  from telethon import TelegramClient, events
8
  from telethon.sessions import StringSession
9
  from fastapi import FastAPI
@@ -19,8 +20,14 @@ TG_API_HASH = get_env("TG_API_HASH")
19
  TG_SESSION_STRING = get_env("TG_SESSION_STRING")
20
 
21
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
22
- BALE_CHAT_ID = get_env("BALE_CHAT_ID")
23
- BALE_LOG_CHAT_ID = get_env("BALE_LOG_CHAT_ID") or BALE_CHAT_ID
 
 
 
 
 
 
24
 
25
  env_channels = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
26
  TARGET_CHANNELS = list(set(env_channels + ["iu39f", "TirexNet", "xsfilterrnet"]))
@@ -31,48 +38,192 @@ MAX_TEXT_LEN = 4000 # Bale maximum message length
31
  LARGE_FILE_SEMAPHORE = asyncio.Semaphore(2)
32
  BALE_API_SEMAPHORE = asyncio.Semaphore(3)
33
 
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"
43
- payload = {"chat_id": BALE_CHAT_ID, "text": text}
44
- if parse_mode:
45
- payload["parse_mode"] = parse_mode
 
 
46
 
47
- for attempt in range(1, retries + 1):
48
- try:
49
- async with BALE_API_SEMAPHORE:
50
- async with httpx.AsyncClient() as client:
51
- resp = await client.post(url, json=payload, timeout=10)
52
- if resp.status_code == 200:
53
- return True
54
- else:
55
- if attempt < retries:
56
- await asyncio.sleep(2 ** (attempt - 1))
57
- continue
58
- if log_error:
59
- await send_log_to_bale(
60
- f"send_text_to_bale failed after {retries} attempts: "
61
- f"{resp.status_code} {resp.text[:200]}"
62
- )
63
- return False
64
- except Exception as e:
65
- if attempt < retries:
66
- await asyncio.sleep(2 ** (attempt - 1))
67
- continue
68
- if log_error:
69
- await send_log_to_bale(f"send_text_to_bale exception after {retries} attempts: {e}")
70
- return False
71
- return False
 
 
 
 
72
 
73
 
74
  async def send_media_to_bale(file_path, caption, media_type, parse_mode=None, retries=3):
75
- if not BALE_BOT_TOKEN:
76
  return False
77
 
78
  endpoint_map = {
@@ -85,44 +236,48 @@ async def send_media_to_bale(file_path, caption, media_type, parse_mode=None, re
85
  "video_note": "sendVideoNote",
86
  }
87
  endpoint = endpoint_map.get(media_type, "sendDocument")
88
- url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/{endpoint}"
89
-
90
- data = {"chat_id": BALE_CHAT_ID}
91
- if caption:
92
- data["caption"] = caption
93
- if parse_mode:
94
- data["parse_mode"] = parse_mode
95
-
96
  field_name = media_type if media_type in endpoint_map else "document"
97
 
98
- for attempt in range(1, retries + 1):
99
- try:
100
- with open(file_path, "rb") as f:
101
- files = {field_name: f}
102
- async with BALE_API_SEMAPHORE:
103
- async with httpx.AsyncClient() as client:
104
- resp = await client.post(url, data=data, files=files, timeout=30)
105
- if resp.status_code == 200:
106
- return True
107
- else:
108
- if attempt < retries:
109
- await asyncio.sleep(2 ** (attempt - 1))
110
- continue
111
- await send_log_to_bale(
112
- f"send_media_to_bale failed after {retries} attempts ({media_type}): "
113
- f"{resp.status_code} {resp.text[:300]}\nFile: {os.path.basename(file_path)}"
114
- )
115
- return False
116
- except Exception as e:
117
- if attempt < retries:
118
- await asyncio.sleep(2 ** (attempt - 1))
119
- continue
120
- await send_log_to_bale(
121
- f"send_media_to_bale exception after {retries} attempts ({media_type}): {e}\n"
122
- f"File: {os.path.basename(file_path)}"
123
- )
124
- return False
125
- return False
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
 
128
  async def send_log_to_bale(message):
@@ -147,7 +302,6 @@ def split_long_text(text, max_len=MAX_TEXT_LEN):
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)
@@ -163,17 +317,12 @@ def split_long_text(text, max_len=MAX_TEXT_LEN):
163
 
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
 
178
  chunks = split_long_text(text, max_len)
179
  total = len(chunks)
@@ -208,7 +357,7 @@ async def send_text_or_caption(text, parse_mode="HTML", is_caption=False, max_le
208
  return success
209
 
210
 
211
- # --- 4. TEMP DIRECTORY HELPERS ---
212
  def create_temp_dir():
213
  return tempfile.mkdtemp(prefix="tg2bale_")
214
 
@@ -219,7 +368,7 @@ def cleanup_temp_dir(temp_dir):
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
@@ -286,7 +435,7 @@ 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"
@@ -326,18 +475,16 @@ def get_media_size(event):
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 = ""
@@ -387,7 +534,7 @@ async def handle_large_document(event, media_path, final_caption, temp_dir):
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:
@@ -398,22 +545,26 @@ async def handler(event):
398
  chat = await event.get_chat()
399
  username = getattr(chat, 'username', None)
400
 
401
- # Only process channels with a username that is in the target list
402
  if not username or username.lower() not in TARGET_CHANNELS:
403
  return
404
 
405
- # Build header
 
 
406
  header = f"📢 @{username}\n\n" if username else f"📢 {chat.title}\n\n"
407
- caption_body = build_caption(event, chat)
408
  final_caption = header + caption_body
409
 
 
 
 
 
 
410
  media_type = detect_media_type(event)
411
  if not media_type:
412
- # Plain text
413
  await send_text_or_caption(final_caption, parse_mode="HTML")
414
  return
415
 
416
- # Media message
417
  media_size = get_media_size(event)
418
  if media_size and media_size > CHUNK_SIZE:
419
  async with LARGE_FILE_SEMAPHORE:
@@ -435,7 +586,6 @@ async def handler(event):
435
  first_caption, _ = await send_text_or_caption(final_caption, parse_mode="HTML", is_caption=True)
436
  success = await send_media_to_bale(media_path, first_caption, media_type, parse_mode="HTML")
437
  if not success:
438
- # Fallback: zip and send as document
439
  await send_log_to_bale(f"Direct send failed for {media_type}, trying as document...")
440
  zip_path = os.path.join(temp_dir, "fallback.zip")
441
  await zip_file(media_path, zip_path)
@@ -450,7 +600,7 @@ async def handler(event):
450
  await send_log_to_bale(f"Handler Error (@{name}): {e}")
451
 
452
 
453
- # --- 8. SERVER LIFESPAN ---
454
  @asynccontextmanager
455
  async def lifespan(app: FastAPI):
456
  await send_log_to_bale("Bot starting...")
 
4
  import zipfile
5
  import httpx
6
  import shutil
7
+ import re
8
  from telethon import TelegramClient, events
9
  from telethon.sessions import StringSession
10
  from fastapi import FastAPI
 
20
  TG_SESSION_STRING = get_env("TG_SESSION_STRING")
21
 
22
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
23
+ BALE_CHAT_ID = get_env("BALE_CHAT_ID") # kept for backward compatibility
24
+ bale_ids_raw = get_env("BALE_CHAT_IDS") # comma-separated for multiple chats
25
+ if bale_ids_raw:
26
+ BALE_CHAT_IDS = [x.strip() for x in bale_ids_raw.split(",") if x.strip()]
27
+ else:
28
+ BALE_CHAT_IDS = [BALE_CHAT_ID] if BALE_CHAT_ID else []
29
+
30
+ BALE_LOG_CHAT_ID = get_env("BALE_LOG_CHAT_ID") or (BALE_CHAT_IDS[0] if BALE_CHAT_IDS else None)
31
 
32
  env_channels = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
33
  TARGET_CHANNELS = list(set(env_channels + ["iu39f", "TirexNet", "xsfilterrnet"]))
 
38
  LARGE_FILE_SEMAPHORE = asyncio.Semaphore(2)
39
  BALE_API_SEMAPHORE = asyncio.Semaphore(3)
40
 
41
+ # Optional filter expression
42
+ FILTER_EXPR = get_env("FILTER_EXPR") or ""
43
+ REMOVE_WORDS = [w.strip().lower() for w in get_env("REMOVE_WORDS", "").split(",") if w.strip()]
44
+
45
+ # --- 2. FILTER EXPRESSION PARSER & EVALUATOR ---
46
+ class FilterExpr:
47
+ """Compile a filter expression string into an AST and evaluate against text."""
48
+ def __init__(self, expr_str: str):
49
+ self.ast = None
50
+ if not expr_str.strip():
51
+ return
52
+ try:
53
+ tokens = self._tokenize(expr_str)
54
+ tokens = self._insert_and_operators(tokens)
55
+ self.ast = self._parse(tokens)
56
+ except Exception as e:
57
+ print(f"⚠️ Invalid FILTER_EXPR: {e} – ignoring filter")
58
+ self.ast = None
59
+
60
+ def _tokenize(self, s):
61
+ token_re = re.compile(r'\(|\)|!|\||"[^"]*"|[^\s()!|"]+')
62
+ raw_tokens = token_re.findall(s)
63
+ typed = []
64
+ for t in raw_tokens:
65
+ if t == '(':
66
+ typed.append(('LPAREN', t))
67
+ elif t == ')':
68
+ typed.append(('RPAREN', t))
69
+ elif t == '!':
70
+ typed.append(('NOT', t))
71
+ elif t == '|':
72
+ typed.append(('OR', t))
73
+ elif t.startswith('"') and t.endswith('"'):
74
+ typed.append(('WORD', t[1:-1].lower()))
75
+ else:
76
+ typed.append(('WORD', t.lower()))
77
+ return typed
78
+
79
+ def _insert_and_operators(self, tokens):
80
+ if not tokens:
81
+ return []
82
+ terminators = {'WORD', 'RPAREN'}
83
+ starters = {'WORD', 'LPAREN', 'NOT'}
84
+ result = [tokens[0]]
85
+ for i in range(1, len(tokens)):
86
+ prev = tokens[i-1]
87
+ curr = tokens[i]
88
+ if prev[0] in terminators and curr[0] in starters:
89
+ result.append(('AND', '&'))
90
+ result.append(curr)
91
+ return result
92
+
93
+ def _parse(self, tokens):
94
+ self._pos = 0
95
+ self._tokens = tokens
96
+ ast = self._expr()
97
+ if self._pos != len(self._tokens):
98
+ raise ValueError(f"Unexpected token: {self._current()}")
99
+ return ast
100
+
101
+ def _current(self):
102
+ return self._tokens[self._pos] if self._pos < len(self._tokens) else None
103
+
104
+ def _advance(self):
105
+ self._pos += 1
106
+
107
+ def _expr(self): # OR level
108
+ left = self._term()
109
+ while self._current() and self._current()[0] == 'OR':
110
+ self._advance()
111
+ right = self._term()
112
+ left = ('OR', left, right)
113
+ return left
114
+
115
+ def _term(self): # AND level
116
+ left = self._factor()
117
+ while self._current() and self._current()[0] == 'AND':
118
+ self._advance()
119
+ right = self._factor()
120
+ left = ('AND', left, right)
121
+ return left
122
+
123
+ def _factor(self): # NOT level
124
+ if self._current() and self._current()[0] == 'NOT':
125
+ self._advance()
126
+ child = self._factor()
127
+ return ('NOT', child)
128
+ return self._atom()
129
+
130
+ def _atom(self):
131
+ tok = self._current()
132
+ if not tok:
133
+ raise ValueError("Unexpected end of expression")
134
+ if tok[0] == 'LPAREN':
135
+ self._advance()
136
+ node = self._expr()
137
+ if not self._current() or self._current()[0] != 'RPAREN':
138
+ raise ValueError("Missing )")
139
+ self._advance()
140
+ return node
141
+ elif tok[0] == 'WORD':
142
+ self._advance()
143
+ return ('WORD', tok[1])
144
+ else:
145
+ raise ValueError(f"Unexpected token: {tok}")
146
+
147
+ def evaluate(self, text: str) -> bool:
148
+ """Return True if the filter expression matches the text (message passes)."""
149
+ if self.ast is None:
150
+ return True
151
+ text_lower = text.lower()
152
+ return self._eval_node(self.ast, text_lower)
153
+
154
+ def _eval_node(self, node, text):
155
+ node_type = node[0]
156
+ if node_type == 'WORD':
157
+ return node[1] in text
158
+ elif node_type == 'AND':
159
+ return self._eval_node(node[1], text) and self._eval_node(node[2], text)
160
+ elif node_type == 'OR':
161
+ return self._eval_node(node[1], text) or self._eval_node(node[2], text)
162
+ elif node_type == 'NOT':
163
+ return not self._eval_node(node[1], text)
164
+ else:
165
+ return False
166
+
167
+
168
+ msg_filter = FilterExpr(FILTER_EXPR)
169
+ def remove_words(text: str, words: list) -> str:
170
+ """Remove all occurrences of each word (case‑insensitive) from text."""
171
+ if not words or not text:
172
+ return text
173
+ import re
174
+ for w in words:
175
+ text = re.sub(re.escape(w), '', text, flags=re.IGNORECASE)
176
+ return text
177
+
178
+ # --- 3. TELEGRAM CLIENT ---
179
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
180
 
181
+
182
+ # --- 4. BALE HELPERS (multi‑chat, with retries & splitting) ---
183
 
184
  async def send_text_to_bale(text, parse_mode=None, retries=3, log_error=True):
185
+ if not BALE_BOT_TOKEN or not BALE_CHAT_IDS:
186
  return False
187
+ overall = True
188
+ for chat_id in BALE_CHAT_IDS:
189
+ url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
190
+ payload = {"chat_id": chat_id, "text": text}
191
+ if parse_mode:
192
+ payload["parse_mode"] = parse_mode
193
 
194
+ success = False
195
+ for attempt in range(1, retries + 1):
196
+ try:
197
+ async with BALE_API_SEMAPHORE:
198
+ async with httpx.AsyncClient() as client:
199
+ resp = await client.post(url, json=payload, timeout=10)
200
+ if resp.status_code == 200:
201
+ success = True
202
+ break
203
+ else:
204
+ if attempt < retries:
205
+ await asyncio.sleep(2 ** (attempt - 1))
206
+ continue
207
+ if log_error:
208
+ await send_log_to_bale(
209
+ f"send_text_to_bale failed after {retries} attempts (chat {chat_id}): "
210
+ f"{resp.status_code} {resp.text[:200]}"
211
+ )
212
+ except Exception as e:
213
+ if attempt < retries:
214
+ await asyncio.sleep(2 ** (attempt - 1))
215
+ continue
216
+ if log_error:
217
+ await send_log_to_bale(
218
+ f"send_text_to_bale exception after {retries} attempts (chat {chat_id}): {e}"
219
+ )
220
+ if not success:
221
+ overall = False
222
+ return overall
223
 
224
 
225
  async def send_media_to_bale(file_path, caption, media_type, parse_mode=None, retries=3):
226
+ if not BALE_BOT_TOKEN or not BALE_CHAT_IDS:
227
  return False
228
 
229
  endpoint_map = {
 
236
  "video_note": "sendVideoNote",
237
  }
238
  endpoint = endpoint_map.get(media_type, "sendDocument")
 
 
 
 
 
 
 
 
239
  field_name = media_type if media_type in endpoint_map else "document"
240
 
241
+ overall = True
242
+ for chat_id in BALE_CHAT_IDS:
243
+ url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/{endpoint}"
244
+ data = {"chat_id": chat_id}
245
+ if caption:
246
+ data["caption"] = caption
247
+ if parse_mode:
248
+ data["parse_mode"] = parse_mode
249
+
250
+ success = False
251
+ for attempt in range(1, retries + 1):
252
+ try:
253
+ with open(file_path, "rb") as f:
254
+ files = {field_name: f}
255
+ async with BALE_API_SEMAPHORE:
256
+ async with httpx.AsyncClient() as client:
257
+ resp = await client.post(url, data=data, files=files, timeout=30)
258
+ if resp.status_code == 200:
259
+ success = True
260
+ break
261
+ else:
262
+ if attempt < retries:
263
+ await asyncio.sleep(2 ** (attempt - 1))
264
+ continue
265
+ await send_log_to_bale(
266
+ f"send_media_to_bale failed after {retries} attempts "
267
+ f"({media_type}) chat {chat_id}: {resp.status_code} {resp.text[:300]}\n"
268
+ f"File: {os.path.basename(file_path)}"
269
+ )
270
+ except Exception as e:
271
+ if attempt < retries:
272
+ await asyncio.sleep(2 ** (attempt - 1))
273
+ continue
274
+ await send_log_to_bale(
275
+ f"send_media_to_bale exception after {retries} attempts "
276
+ f"({media_type}) chat {chat_id}: {e}\nFile: {os.path.basename(file_path)}"
277
+ )
278
+ if not success:
279
+ overall = False
280
+ return overall
281
 
282
 
283
  async def send_log_to_bale(message):
 
302
  if len(text) <= max_len:
303
  chunks.append(text)
304
  break
 
305
  split_at = text.rfind('\n', 0, max_len)
306
  if split_at == -1:
307
  split_at = text.rfind(' ', 0, max_len)
 
317
 
318
 
319
  async def send_text_or_caption(text, parse_mode="HTML", is_caption=False, max_len=MAX_TEXT_LEN):
320
+ """Send/caption-split long text. Returns (first_part, success) for captions, success (bool) for plain text."""
 
 
 
 
321
  if not text:
322
  return ("" if is_caption else True)
323
 
 
324
  if len(text) > max_len and parse_mode:
325
+ parse_mode = None # avoid broken HTML when splitting
326
 
327
  chunks = split_long_text(text, max_len)
328
  total = len(chunks)
 
357
  return success
358
 
359
 
360
+ # --- 5. TEMP DIRECTORY HELPERS ---
361
  def create_temp_dir():
362
  return tempfile.mkdtemp(prefix="tg2bale_")
363
 
 
368
  pass
369
 
370
 
371
+ # --- 6. FILE OPERATIONS (threaded) ---
372
  async def download_media(message, temp_dir):
373
  if not message.media:
374
  return None
 
435
  return await asyncio.to_thread(split_file_sync, file_path, chunk_size)
436
 
437
 
438
+ # --- 7. MEDIA DETECTION / SIZE ---
439
  def detect_media_type(event):
440
  if event.photo:
441
  return "photo"
 
475
 
476
 
477
  def get_message_link(event, chat):
 
478
  username = getattr(chat, 'username', None)
479
  if username:
480
  return f"https://t.me/{username}/{event.message.id}"
 
481
  if getattr(chat, 'id', None):
482
  return f"https://t.me/c/{abs(chat.id)}/{event.message.id}"
483
  return ""
484
 
485
 
486
+ def build_caption(event, chat, cleaned_text=None):
487
+ msg_text = cleaned_text if cleaned_text is not None else (event.raw_text or "")
488
  msg_link = get_message_link(event, chat)
489
 
490
  preview_url = ""
 
534
  await send_media_to_bale(zip_path, first_part, "document", parse_mode="HTML")
535
 
536
 
537
+ # --- 8. TELEGRAM EVENT HANDLER (main logic) ---
538
  @tg_client.on(events.NewMessage)
539
  async def handler(event):
540
  if not event.is_channel:
 
545
  chat = await event.get_chat()
546
  username = getattr(chat, 'username', None)
547
 
 
548
  if not username or username.lower() not in TARGET_CHANNELS:
549
  return
550
 
551
+ # --- Clean up the text before forwarding ---
552
+ cleaned_text = remove_words(event.raw_text or "", REMOVE_WORDS)
553
+
554
  header = f"📢 @{username}\n\n" if username else f"📢 {chat.title}\n\n"
555
+ caption_body = build_caption(event, chat, cleaned_text=cleaned_text)
556
  final_caption = header + caption_body
557
 
558
+ # ----- Filter expression check ----- (still uses original raw_text)
559
+ if not msg_filter.evaluate(event.raw_text or ""):
560
+ return
561
+ # -----------------------------------
562
+
563
  media_type = detect_media_type(event)
564
  if not media_type:
 
565
  await send_text_or_caption(final_caption, parse_mode="HTML")
566
  return
567
 
 
568
  media_size = get_media_size(event)
569
  if media_size and media_size > CHUNK_SIZE:
570
  async with LARGE_FILE_SEMAPHORE:
 
586
  first_caption, _ = await send_text_or_caption(final_caption, parse_mode="HTML", is_caption=True)
587
  success = await send_media_to_bale(media_path, first_caption, media_type, parse_mode="HTML")
588
  if not success:
 
589
  await send_log_to_bale(f"Direct send failed for {media_type}, trying as document...")
590
  zip_path = os.path.join(temp_dir, "fallback.zip")
591
  await zip_file(media_path, zip_path)
 
600
  await send_log_to_bale(f"Handler Error (@{name}): {e}")
601
 
602
 
603
+ # --- 9. SERVER LIFESPAN ---
604
  @asynccontextmanager
605
  async def lifespan(app: FastAPI):
606
  await send_log_to_bale("Bot starting...")