File size: 36,614 Bytes
aacab9c
 
5eb10de
6a81089
ea7745f
36975ba
00a0c99
 
 
 
 
 
 
aacab9c
8cdf978
00a0c99
 
9443cfb
e8cb213
00a0c99
 
 
 
aacab9c
e8f1697
9443cfb
e8f1697
00a0c99
 
 
9443cfb
e8f1697
8cdf978
9443cfb
00a0c99
 
 
 
 
 
9443cfb
00a0c99
 
6a81089
00a0c99
 
 
 
 
 
 
 
 
e8f1697
00a0c99
36975ba
00a0c99
 
9443cfb
00a0c99
 
36975ba
00a0c99
 
 
 
36975ba
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9443cfb
00a0c99
 
 
9443cfb
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0933bec
5eb10de
00a0c99
5eb10de
00a0c99
 
 
 
 
 
1f84851
0f42019
00a0c99
 
 
0f42019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36975ba
 
 
 
 
 
 
 
 
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
add1ba6
36975ba
5eb10de
 
9443cfb
5eb10de
 
 
 
 
 
00a0c99
 
 
5eb10de
00a0c99
 
5eb10de
 
 
 
 
 
 
 
 
36975ba
 
 
9443cfb
00a0c99
5eb10de
 
00a0c99
 
 
 
 
 
 
add1ba6
6a81089
00a0c99
 
 
 
 
 
 
 
 
 
 
 
85e5c42
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
add1ba6
00a0c99
 
 
 
 
 
 
 
 
 
 
6a81089
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85e5c42
00a0c99
 
 
 
 
 
85e5c42
00a0c99
 
85e5c42
 
 
add1ba6
00a0c99
 
 
 
 
 
 
 
 
 
 
 
add1ba6
00a0c99
 
 
 
 
 
 
 
 
 
 
 
add1ba6
00a0c99
0933bec
add1ba6
0933bec
 
00a0c99
0933bec
 
 
 
 
 
 
add1ba6
 
0933bec
 
00a0c99
85e5c42
00a0c99
85e5c42
36975ba
 
85e5c42
 
00a0c99
85e5c42
00a0c99
85e5c42
00a0c99
85e5c42
 
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
85e5c42
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f42019
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85e5c42
00a0c99
 
 
 
85e5c42
 
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85e5c42
add1ba6
00a0c99
 
 
 
 
e8f1697
00a0c99
5eb10de
 
add1ba6
 
9443cfb
e8f1697
00a0c99
9443cfb
00a0c99
 
 
 
e7aeb33
add1ba6
00a0c99
 
 
 
 
 
e8f1697
00a0c99
 
 
 
 
 
6a81089
00a0c99
 
36975ba
5eb10de
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5af969c
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
add1ba6
5af969c
00a0c99
 
 
5eb10de
 
00a0c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9443cfb
e8f1697
00a0c99
e8f1697
00a0c99
 
e1936eb
5eb10de
8cdf978
00a0c99
e8cb213
00a0c99
 
 
 
 
 
 
 
aacab9c
e8cb213
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
import os
import asyncio
import tempfile
import zipfile
import httpx
import shutil
import re
import secrets
import html
from datetime import datetime
from collections import deque
from contextlib import asynccontextmanager

from telethon import TelegramClient, events
from telethon.sessions import StringSession
from telethon.errors import AuthKeyDuplicatedError

from fastapi import FastAPI
import uvicorn
import gradio as gr

# Disable Gradio SSR proxying
os.environ["GRADIO_SSR_MODE"] = "false"

def get_env(name):
    return os.getenv(name)

# ==========================================
# 1. COMMON TELEGRAM CONFIGURATION
# ==========================================
TG_API_ID = int(get_env("TG_API_ID") or 0)
TG_API_HASH = get_env("TG_API_HASH")
TG_SESSION_STRING = get_env("TG_SESSION_STRING")

# ==========================================
# 2. BOT 1 CONFIGURATION (Standard Relay)
# ==========================================
BALE_BOT_TOKEN_1 = get_env("BALE_BOT_TOKEN")
BALE_CHAT_ID_1 = get_env("BALE_CHAT_ID")
BALE_LOG_CHAT_ID_1 = get_env("BALE_LOG_CHAT_ID") or BALE_CHAT_ID_1

env_channels_1 = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",") if c.strip()]
TARGET_CHANNELS_1 = list(set(env_channels_1))

# ==========================================
# 3. BOT 2 CONFIGURATION (Filtered/Obfuscated)
# ==========================================
BALE_BOT_TOKEN_2 = get_env("BALE_BOT_TOKEN_2")
bale_ids_raw_2 = get_env("BALE_CHAT_IDS") or get_env("BALE_CHAT_ID_2")
if bale_ids_raw_2:
    BALE_CHAT_IDS_2 = [x.strip() for x in bale_ids_raw_2.split(",") if x.strip()]
else:
    BALE_CHAT_IDS_2 = []

BALE_LOG_CHAT_ID_2 = get_env("BALE_LOG_CHAT_ID_2") or (BALE_CHAT_IDS_2[0] if BALE_CHAT_IDS_2 else None)

env_channels_2 = [c.strip().lower() for c in (get_env("TARGET_CHANNELS_2") or "").split(",") if c.strip()]
TARGET_CHANNELS_2 = list(set(env_channels_2 + ["iu39f", "tirexnet", "xsfilterrnet"]))

FILTER_EXPR = get_env("FILTER_EXPR") or ""
REMOVE_WORDS = [w.strip().lower() for w in (get_env("REMOVE_WORDS") or "").split(",") if w.strip()]

# Constants
CHUNK_SIZE = 19 * 1024 * 1024  # 19 MB
MAX_TEXT_LEN = 4000
DUMMY_BYTE_COUNT = 64

LARGE_FILE_SEMAPHORE = asyncio.Semaphore(2)
BALE_API_SEMAPHORE = asyncio.Semaphore(4)

LOG_BUFFER = deque(maxlen=250)
TELEGRAM_STATUS = "Stopped"
TELEGRAM_ERROR = None

def add_log(msg: str):
    timestamp = datetime.now().strftime("%H:%M:%S")
    entry = f"[{timestamp}] {msg}"
    LOG_BUFFER.append(entry)
    print(entry)


# ==========================================
# 4. FILTER EXPRESSION PARSER (For Bot 2)
# ==========================================
class FilterExpr:
    def __init__(self, expr_str: str):
        self.ast = None
        if not expr_str.strip():
            return
        try:
            tokens = self._tokenize(expr_str)
            tokens = self._insert_and_operators(tokens)
            self.ast = self._parse(tokens)
        except Exception as e:
            add_log(f"Invalid FILTER_EXPR: {e}")
            self.ast = None

    def _tokenize(self, s):
        token_re = re.compile(r'\(|\)|!|\||"[^"]*"|[^\s()!|"]+')
        raw_tokens = token_re.findall(s)
        typed = []
        for t in raw_tokens:
            if t == '(':
                typed.append(('LPAREN', t))
            elif t == ')':
                typed.append(('RPAREN', t))
            elif t == '!':
                typed.append(('NOT', t))
            elif t == '|':
                typed.append(('OR', t))
            elif t.startswith('"') and t.endswith('"'):
                typed.append(('WORD', t[1:-1].lower()))
            else:
                typed.append(('WORD', t.lower()))
        return typed

    def _insert_and_operators(self, tokens):
        if not tokens:
            return []
        terminators = {'WORD', 'RPAREN'}
        starters = {'WORD', 'LPAREN', 'NOT'}
        result = [tokens[0]]
        for i in range(1, len(tokens)):
            prev = tokens[i-1]
            curr = tokens[i]
            if prev[0] in terminators and curr[0] in starters:
                result.append(('AND', '&'))
            result.append(curr)
        return result

    def _parse(self, tokens):
        self._pos = 0
        self._tokens = tokens
        ast = self._expr()
        if self._pos != len(self._tokens):
            raise ValueError(f"Unexpected token: {self._current()}")
        return ast

    def _current(self):
        return self._tokens[self._pos] if self._pos < len(self._tokens) else None

    def _advance(self):
        self._pos += 1

    def _expr(self):
        left = self._term()
        while self._current() and self._current()[0] == 'OR':
            self._advance()
            right = self._term()
            left = ('OR', left, right)
        return left

    def _term(self):
        left = self._factor()
        while self._current() and self._current()[0] == 'AND':
            self._advance()
            right = self._factor()
            left = ('AND', left, right)
        return left

    def _factor(self):
        if self._current() and self._current()[0] == 'NOT':
            self._advance()
            child = self._factor()
            return ('NOT', child)
        return self._atom()

    def _atom(self):
        tok = self._current()
        if not tok:
            raise ValueError("Unexpected end of expression")
        if tok[0] == 'LPAREN':
            self._advance()
            node = self._expr()
            if not self._current() or self._current()[0] != 'RPAREN':
                raise ValueError("Missing )")
            self._advance()
            return node
        elif tok[0] == 'WORD':
            self._advance()
            return ('WORD', tok[1])
        else:
            raise ValueError(f"Unexpected token: {tok}")

    def evaluate(self, text: str) -> bool:
        if self.ast is None:
            return True
        return self._eval_node(self.ast, text.lower())

    def _eval_node(self, node, text):
        node_type = node[0]
        if node_type == 'WORD':
            return node[1] in text
        elif node_type == 'AND':
            return self._eval_node(node[1], text) and self._eval_node(node[2], text)
        elif node_type == 'OR':
            return self._eval_node(node[1], text) or self._eval_node(node[2], text)
        elif node_type == 'NOT':
            return not self._eval_node(node[1], text)
        return False

msg_filter = FilterExpr(FILTER_EXPR)

def remove_words(text: str, words: list) -> str:
    if not words or not text:
        return text
    for w in words:
        text = re.sub(re.escape(w), '', text, flags=re.IGNORECASE)
    return text


# ==========================================
# 5. GENERAL FILE & TEXT HELPERS
# ==========================================
def split_long_text(text, max_len=MAX_TEXT_LEN):
    if len(text) <= max_len:
        return [text]
    chunks = []
    while text:
        if len(text) <= max_len:
            chunks.append(text)
            break
        split_at = text.rfind('\n', 0, max_len)
        if split_at == -1:
            split_at = text.rfind(' ', 0, max_len)
        if split_at == -1:
            split_at = max_len
        chunk = text[:split_at].rstrip()
        text = text[split_at:].lstrip()
        if not chunk:
            chunk = text[:max_len]
            text = text[max_len:]
        chunks.append(chunk)
    return chunks

def create_temp_dir():
    return tempfile.mkdtemp(prefix="tg2bale_")

def cleanup_temp_dir(temp_dir):
    try:
        shutil.rmtree(temp_dir, ignore_errors=True)
    except Exception:
        pass

def zip_file_sync(file_path, zip_path):
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        zf.write(file_path, arcname=os.path.basename(file_path))
    return zip_path

async def zip_file(file_path, zip_path):
    return await asyncio.to_thread(zip_file_sync, file_path, zip_path)

def split_file_sync(file_path, chunk_size=CHUNK_SIZE, suffix=".dat"):
    chunk_paths = []
    base = file_path + ".part"
    with open(file_path, "rb") as f:
        i = 0
        while True:
            chunk_data = f.read(chunk_size)
            if not chunk_data:
                break
            chunk_path = f"{base}{i:03d}{suffix}"
            with open(chunk_path, "wb") as chunk_file:
                chunk_file.write(chunk_data)
            chunk_paths.append(chunk_path)
            i += 1
    return chunk_paths

async def split_file(file_path, chunk_size=CHUNK_SIZE, suffix=".dat"):
    return await asyncio.to_thread(split_file_sync, file_path, chunk_size, suffix)

async def download_media(message, temp_dir):
    if not message.media:
        return None
    try:
        suffix = ""
        if message.photo:
            suffix = ".jpg"
        elif message.video:
            suffix = ".mp4"
        elif getattr(message, 'document', None):
            for attr in message.document.attributes:
                if hasattr(attr, 'file_name') and '.' in attr.file_name:
                    suffix = f".{attr.file_name.split('.')[-1]}"
                    break
            if not suffix and message.document.mime_type and '/' in message.document.mime_type:
                suffix = f".{message.document.mime_type.split('/')[-1]}"
        elif message.audio:
            suffix = ".mp3"
        elif message.voice:
            suffix = ".ogg"
        elif message.sticker:
            suffix = ".webp"
        elif message.video_note:
            suffix = ".mp4"

        file_path = os.path.join(temp_dir, f"media{suffix}")
        await message.download_media(file=file_path)
        return file_path
    except Exception as e:
        add_log(f"Media download error: {e}")
        return None

def get_message_link(event, chat):
    username = getattr(chat, 'username', None)
    if username:
        return f"https://t.me/{username}/{event.message.id}"
    if getattr(chat, 'id', None):
        return f"https://t.me/c/{abs(chat.id)}/{event.message.id}"
    return ""


# ==========================================
# 6. UNIVERSAL BALE SENDER FUNCTIONS
# ==========================================
async def send_text_to_bale_targets(bot_token, chat_ids, text, parse_mode=None, retries=3):
    if not bot_token or not chat_ids:
        return False
    overall = True
    for chat_id in chat_ids:
        url = f"https://tapi.bale.ai/bot{bot_token}/sendMessage"
        payload = {"chat_id": chat_id, "text": text}
        if parse_mode:
            payload["parse_mode"] = parse_mode

        sent = False
        for attempt in range(1, retries + 1):
            try:
                async with BALE_API_SEMAPHORE:
                    async with httpx.AsyncClient() as client:
                        resp = await client.post(url, json=payload, timeout=10)
                        if resp.status_code == 200:
                            sent = True
                            break
                        if attempt < retries:
                            await asyncio.sleep(2 ** (attempt - 1))
            except Exception:
                if attempt < retries:
                    await asyncio.sleep(2 ** (attempt - 1))
        if not sent:
            overall = False
    return overall

async def send_media_to_bale_targets(bot_token, chat_ids, file_path, caption, media_type, parse_mode=None, upload_filename=None, retries=3):
    if not bot_token or not chat_ids:
        return False

    endpoint_map = {
        "photo": "sendPhoto",
        "video": "sendVideo",
        "document": "sendDocument",
        "audio": "sendAudio",
        "voice": "sendVoice",
        "sticker": "sendSticker",
        "video_note": "sendVideoNote",
    }
    endpoint = endpoint_map.get(media_type, "sendDocument")
    field_name = media_type if media_type in endpoint_map else "document"

    overall = True
    for chat_id in chat_ids:
        url = f"https://tapi.bale.ai/bot{bot_token}/{endpoint}"
        data = {"chat_id": chat_id}
        if caption:
            data["caption"] = caption
            if parse_mode:
                data["parse_mode"] = parse_mode

        sent = False
        for attempt in range(1, retries + 1):
            try:
                cur_filename = upload_filename
                if cur_filename and attempt > 1 and '/' in cur_filename:
                    cur_filename = cur_filename.replace('/', '-')

                with open(file_path, "rb") as f:
                    files = {field_name: (cur_filename, f)} if cur_filename else {field_name: f}
                    async with BALE_API_SEMAPHORE:
                        async with httpx.AsyncClient() as client:
                            resp = await client.post(url, data=data, files=files, timeout=30)
                            if resp.status_code == 200:
                                sent = True
                                break
                            if attempt < retries:
                                await asyncio.sleep(2 ** (attempt - 1))
            except Exception:
                if attempt < retries:
                    await asyncio.sleep(2 ** (attempt - 1))
        if not sent:
            overall = False
    return overall

async def send_text_or_caption_bale(bot_token, chat_ids, text, parse_mode="HTML", is_caption=False, max_len=MAX_TEXT_LEN):
    if not text:
        return ("" if is_caption else True)

    if len(text) > max_len and parse_mode:
        parse_mode = None

    chunks = split_long_text(text, max_len)
    total = len(chunks)

    if is_caption:
        first_chunk = chunks[0]
        if total == 1:
            return first_chunk, True

        first_chunk = first_chunk + f"\n… (1/{total})"
        success = True
        for i in range(1, total):
            chunk_text = f"{chunks[i]}\n… ({i+1}/{total})"
            ok = await send_text_to_bale_targets(bot_token, chat_ids, chunk_text, parse_mode=None)
            if not ok:
                success = False
            await asyncio.sleep(0.5)
        return first_chunk, success

    success = True
    for i, chunk in enumerate(chunks, 1):
        if total > 1:
            chunk = f"{chunk}\n… ({i}/{total})"
        ok = await send_text_to_bale_targets(bot_token, chat_ids, chunk, parse_mode=parse_mode)
        if not ok:
            success = False
        if i < total:
            await asyncio.sleep(0.5)
    return success

async def log_to_bale(bot_token, log_chat_id, message, bot_tag="Bot"):
    add_log(f"[{bot_tag}] {message}")
    if not bot_token or not log_chat_id:
        return
    url = f"https://tapi.bale.ai/bot{bot_token}/sendMessage"
    payload = {"chat_id": log_chat_id, "text": f"πŸ”§ [{bot_tag} Log]:\n{message}"}
    try:
        async with httpx.AsyncClient() as client:
            await client.post(url, json=payload, timeout=5)
    except Exception:
        pass


# ==========================================
# 7. BOT 1 HANDLERS (Standard)
# ==========================================
def detect_media_type_bot1(event):
    if event.photo: return "photo"
    if event.video: return "video"
    if event.audio: return "audio"
    if event.voice: return "voice"
    if event.sticker: return "sticker"
    if event.video_note: return "video_note"
    if event.document: return "document"
    return None

def get_media_size_bot1(event):
    try:
        if event.photo: return event.photo.sizes[-1].size
        if event.video: return event.video.size
        if event.audio: return event.audio.size
        if event.voice: return event.voice.size
        if event.video_note: return event.video_note.size
        if event.sticker: return getattr(event.sticker, 'size', None)
        if event.document: return event.document.size
    except Exception:
        pass
    return None

def build_caption_bot1(event, chat):
    msg_text = event.raw_text or ""
    msg_link = get_message_link(event, chat)

    preview_url = ""
    if event.message and event.message.web_preview and event.message.web_preview.url:
        preview_url = event.message.web_preview.url

    parts = []
    if msg_text:
        parts.append(msg_text)
    if preview_url:
        parts.append(f'<a href="{preview_url}">{preview_url}</a>')
    if msg_link:
        parts.append(f'<a href="{msg_link}">πŸ“Ž Open in Telegram</a>')
    return "\n\n".join(parts)

async def handle_large_document_bot1(event, media_path, final_caption, temp_dir):
    file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
    await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"Large file: {os.path.basename(media_path)}, size={file_size/(1024*1024):.1f} MB", "Bot-1")

    zip_path = os.path.join(temp_dir, "media.zip")
    await zip_file(media_path, zip_path)
    zip_size = os.path.getsize(zip_path)

    chat_ids = [BALE_CHAT_ID_1]
    if zip_size > CHUNK_SIZE:
        chunks = await split_file(zip_path, CHUNK_SIZE, suffix=".zip")
        total = len(chunks)
        await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"ZIP split into {total} chunks", "Bot-1")
        for idx, chunk_path in enumerate(chunks, start=1):
            part_caption = f"{final_caption}\nπŸ“¦ Part {idx}/{total}"
            first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, part_caption, parse_mode="HTML", is_caption=True)
            success = await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, chunk_path, first_part, "document", parse_mode="HTML")
            if not success:
                await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, chunk_path, first_part, "document", parse_mode=None)
            await asyncio.sleep(1.5)
    else:
        first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML", is_caption=True)
        await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, zip_path, first_part, "document", parse_mode="HTML")

async def process_bot1(event, chat, username):
    header = f"πŸ“’ @{username}\n\n" if username else f"πŸ“’ {chat.title}\n\n"
    caption_body = build_caption_bot1(event, chat)
    final_caption = header + caption_body

    media_type = detect_media_type_bot1(event)
    chat_ids = [BALE_CHAT_ID_1]

    if not media_type:
        await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML")
        return

    media_size = get_media_size_bot1(event)
    if media_size and media_size > CHUNK_SIZE:
        async with LARGE_FILE_SEMAPHORE:
            temp_dir = create_temp_dir()
            try:
                await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"Large {media_type} from {username or chat.title}: {media_size/(1024*1024):.1f} MB", "Bot-1")
                media_path = await download_media(event, temp_dir)
                if media_path:
                    await handle_large_document_bot1(event, media_path, final_caption, temp_dir)
            finally:
                cleanup_temp_dir(temp_dir)
        return

    temp_dir = create_temp_dir()
    try:
        media_path = await download_media(event, temp_dir)
        if media_path:
            first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_1, chat_ids, final_caption, parse_mode="HTML", is_caption=True)
            success = await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, media_path, first_caption, media_type, parse_mode="HTML")
            if not success:
                zip_path = os.path.join(temp_dir, "fallback.zip")
                await zip_file(media_path, zip_path)
                await send_media_to_bale_targets(BALE_BOT_TOKEN_1, chat_ids, zip_path, first_caption, "document", parse_mode=None)
    finally:
        cleanup_temp_dir(temp_dir)


# ==========================================
# 8. BOT 2 HANDLERS (Filtering & Obfuscation)
# ==========================================
def is_audio_or_video_bot2(event) -> bool:
    if event.video or event.audio or event.voice or event.video_note:
        return True
    if event.document:
        mime = getattr(event.document, 'mime_type', '') or ''
        if mime.startswith('video/') or mime.startswith('audio/'):
            return True
        for attr in getattr(event.document, 'attributes', []):
            fname = getattr(attr, 'file_name', '')
            if fname:
                ext = fname.lower().split('.')[-1]
                if ext in {'mp4', 'mkv', 'avi', 'mov', 'flv', 'wmv', 'webm', '3gp',
                           'mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'opus'}:
                    return True
    return False

def is_image_bot2(event) -> bool:
    if event.photo or event.sticker:
        return True
    if event.document:
        mime = getattr(event.document, 'mime_type', '') or ''
        if mime.startswith('image/'):
            return True
        for attr in getattr(event.document, 'attributes', []):
            fname = getattr(attr, 'file_name', '')
            if fname:
                ext = fname.lower().split('.')[-1]
                if ext in {'jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'svg', 'ico'}:
                    return True
    return False

def obfuscate_suffix(suffix: str) -> str:
    clean = suffix.lstrip('.').strip().lower()
    if not clean:
        clean = "bin"
    if len(clean) == 1:
        return f"*{clean}/"
    elif len(clean) == 2:
        return f"{clean[0]}*/{clean[1]}"
    else:
        res = []
        for i, c in enumerate(clean):
            res.append(c)
            if i < len(clean) - 1:
                res.append('*' if i % 2 == 0 else '/')
        s = "".join(res)
        if '/' not in s: s += "/"
        if '*' not in s: s = "*" + s
        return s

def inject_dummy_bytes(src_path: str, dst_path: str, count: int = DUMMY_BYTE_COUNT):
    dummy = os.urandom(count)
    with open(src_path, "rb") as f_in, open(dst_path, "wb") as f_out:
        f_out.write(dummy)
        shutil.copyfileobj(f_in, f_out)

def get_original_file_info(event):
    orig_name = None
    orig_ext = ""
    if getattr(event, 'document', None):
        for attr in event.document.attributes:
            if hasattr(attr, 'file_name') and attr.file_name:
                orig_name = attr.file_name
                break
        if orig_name and '.' in orig_name:
            orig_ext = orig_name.rsplit('.', 1)[-1]
        elif event.document.mime_type and '/' in event.document.mime_type:
            orig_ext = event.document.mime_type.split('/')[-1]

    if not orig_ext:
        orig_ext = "bin"
    return orig_name, orig_ext.lower()

def extract_hyperlinks(event, text: str = "") -> list:
    urls = []
    seen = set()

    def add_url(u):
        u = u.strip()
        if u and u not in seen:
            seen.add(u)
            urls.append(u)

    if event.message and event.message.entities:
        for ent in event.message.entities:
            if hasattr(ent, 'url') and ent.url:
                add_url(ent.url)
            elif ent.__class__.__name__ == 'MessageEntityUrl':
                raw = event.raw_text or ""
                u = raw[ent.offset: ent.offset + ent.length]
                add_url(u)

    if event.message and event.message.web_preview and event.message.web_preview.url:
        add_url(event.message.web_preview.url)

    if text:
        for u in re.findall(r'(https?://[^\s<>"\']+)', text):
            add_url(u)

    return urls

def build_full_caption_bot2(event, chat, cleaned_text: str = None, deobf_info: str = None) -> str:
    parts = []
    username = getattr(chat, 'username', None)
    title = getattr(chat, 'title', None)
    if username:
        parts.append(f"πŸ“’ <b>Channel:</b> @{username}\nπŸ”— https://t.me/{username}")
    elif title:
        parts.append(f"πŸ“’ <b>Channel:</b> {html.escape(title)}")

    body = cleaned_text if cleaned_text is not None else (event.raw_text or "")
    if body.strip():
        parts.append(html.escape(body.strip()))

    urls = extract_hyperlinks(event, body)
    post_link = get_message_link(event, chat)
    link_lines = []
    if post_link and post_link not in urls:
        link_lines.append(f'β€’ <a href="{post_link}">πŸ“Ž Open in Telegram</a>')
    for u in urls:
        escaped_u = html.escape(u)
        link_lines.append(f'β€’ <a href="{escaped_u}">{escaped_u}</a>')
    if link_lines:
        parts.append("πŸ”— <b>Links:</b>\n" + "\n".join(link_lines))

    if deobf_info:
        parts.append(deobf_info)

    return "\n\n".join(parts)

def build_deobfuscation_instructions(original_ext: str, obfuscated_suffix: str) -> str:
    return (
        f"πŸ›  <b>Deobfuscation Instructions:</b>\n"
        f"β€’ <b>Original Extension:</b> <code>.{original_ext}</code> (Obfuscated: <code>{obfuscated_suffix}</code>)\n"
        f"β€’ <b>Restore Steps:</b>\n"
        f"  1. Remove first {DUMMY_BYTE_COUNT} dummy bytes.\n"
        f"  2. Rename suffix <code>{obfuscated_suffix}</code> back to <code>.{original_ext}</code>\n"
        f"β€’ <i>One-line command (Linux/Mac/Python):</i>\n"
        f"<code>python -c \"open('restored.{original_ext}','wb').write(open('INPUT_FILE','rb').read()[{DUMMY_BYTE_COUNT}:])\"</code>"
    )

async def handle_large_document_bot2(event, media_path, final_caption, temp_dir, upload_filename=None):
    file_size = os.path.getsize(media_path) if os.path.exists(media_path) else 0
    display_name = upload_filename or os.path.basename(media_path)
    await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Large file: {display_name}, size={file_size/(1024*1024):.1f} MB", "Bot-2")

    target_path = media_path
    target_size = os.path.getsize(target_path)

    if target_size > CHUNK_SIZE:
        chunks = await split_file(target_path, CHUNK_SIZE, suffix=".dat")
        total = len(chunks)
        await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Split into {total} parts", "Bot-2")
        for idx, chunk_path in enumerate(chunks, start=1):
            chunk_display_name = f"{display_name}.part{idx:03d}"
            part_caption = f"{final_caption}\n\nπŸ“¦ <b>Part {idx}/{total}</b>"

            first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, part_caption, parse_mode="HTML", is_caption=True)
            success = await send_media_to_bale_targets(
                BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, chunk_path, first_part, "document",
                parse_mode="HTML", upload_filename=chunk_display_name
            )
            if not success:
                await send_media_to_bale_targets(
                    BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, chunk_path, first_part, "document",
                    parse_mode=None, upload_filename=chunk_display_name.replace('/', '-')
                )
            await asyncio.sleep(1.5)
    else:
        first_part, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, final_caption, parse_mode="HTML", is_caption=True)
        await send_media_to_bale_targets(
            BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, target_path, first_part, "document",
            parse_mode="HTML", upload_filename=display_name
        )

async def process_bot2(event, chat, username):
    if not msg_filter.evaluate(event.raw_text or ""):
        return

    # 1. Block audio/video
    if is_audio_or_video_bot2(event):
        await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Blocked audio/video from @{username or 'channel'}", "Bot-2")
        return

    cleaned_text = remove_words(event.raw_text or "", REMOVE_WORDS)

    # 2. Text only
    if not event.media:
        caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text)
        await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML")
        return

    # 3. Images (intact)
    if is_image_bot2(event):
        temp_dir = create_temp_dir()
        try:
            media_path = await download_media(event, temp_dir)
            if media_path:
                caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text)
                media_size = os.path.getsize(media_path)
                if media_size > CHUNK_SIZE:
                    await handle_large_document_bot2(event, media_path, caption, temp_dir)
                else:
                    first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML", is_caption=True)
                    m_type = "photo" if event.photo else "document"
                    success = await send_media_to_bale_targets(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, media_path, first_caption, m_type, parse_mode="HTML")
                    if not success:
                        await send_media_to_bale_targets(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, media_path, first_caption, "document", parse_mode=None)
        finally:
            cleanup_temp_dir(temp_dir)
        return

    # 4. Other files (Dummy bytes + obfuscation)
    orig_name, orig_ext = get_original_file_info(event)
    rand_name = f"file_{secrets.token_hex(4)}"
    obf_suffix = obfuscate_suffix(orig_ext)
    upload_filename = f"{rand_name}.{obf_suffix}"

    deobf_info = build_deobfuscation_instructions(orig_ext, obf_suffix)
    caption = build_full_caption_bot2(event, chat, cleaned_text=cleaned_text, deobf_info=deobf_info)

    temp_dir = create_temp_dir()
    try:
        raw_media_path = await download_media(event, temp_dir)
        if not raw_media_path:
            return

        obf_media_path = os.path.join(temp_dir, f"{rand_name}.dat")
        inject_dummy_bytes(raw_media_path, obf_media_path, DUMMY_BYTE_COUNT)

        file_size = os.path.getsize(obf_media_path)
        if file_size > CHUNK_SIZE:
            async with LARGE_FILE_SEMAPHORE:
                await handle_large_document_bot2(event, obf_media_path, caption, temp_dir, upload_filename=upload_filename)
        else:
            first_caption, _ = await send_text_or_caption_bale(BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, caption, parse_mode="HTML", is_caption=True)
            success = await send_media_to_bale_targets(
                BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, obf_media_path, first_caption, "document",
                parse_mode="HTML", upload_filename=upload_filename
            )
            if not success:
                await send_media_to_bale_targets(
                    BALE_BOT_TOKEN_2, BALE_CHAT_IDS_2, obf_media_path, first_caption, "document",
                    parse_mode=None, upload_filename=upload_filename.replace('/', '-')
                )
    finally:
        cleanup_temp_dir(temp_dir)


# ==========================================
# 9. CENTRAL TELEGRAM EVENT DISPATCHER
# ==========================================
tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)

@tg_client.on(events.NewMessage)
async def unified_handler(event):
    if not event.is_channel:
        return
    chat = None
    username = None
    try:
        chat = await event.get_chat()
        username = (getattr(chat, 'username', '') or '').lower()

        is_bot1 = username in TARGET_CHANNELS_1 if username else False
        is_bot2 = username in TARGET_CHANNELS_2 if username else False

        if not is_bot1 and not is_bot2:
            return

        # Route to Bot 1 if matched
        if is_bot1 and BALE_BOT_TOKEN_1:
            try:
                await process_bot1(event, chat, username)
            except Exception as e:
                await log_to_bale(BALE_BOT_TOKEN_1, BALE_LOG_CHAT_ID_1, f"Bot 1 Handler error (@{username}): {e}", "Bot-1")

        # Route to Bot 2 if matched
        if is_bot2 and BALE_BOT_TOKEN_2:
            try:
                await process_bot2(event, chat, username)
            except Exception as e:
                await log_to_bale(BALE_BOT_TOKEN_2, BALE_LOG_CHAT_ID_2, f"Bot 2 Handler error (@{username}): {e}", "Bot-2")

    except Exception as e:
        add_log(f"Global Router Exception: {e}")


# ==========================================
# 10. GRADIO DASHBOARD & FILE DEOBFUSCATOR
# ==========================================
def get_status_info():
    status_icon = "🟒" if TELEGRAM_STATUS == "Connected" else ("🟑" if "Connecting" in TELEGRAM_STATUS else "πŸ”΄")
    status_text = f"{status_icon} **Telegram Status:** {TELEGRAM_STATUS}"
    if TELEGRAM_ERROR:
        status_text += f"\n*Details:* {TELEGRAM_ERROR}"

    channels_text = "**Bot 1 Channels:**\n" + ("\n".join([f"β€’ `@{c}`" for c in TARGET_CHANNELS_1]) if TARGET_CHANNELS_1 else "None")
    channels_text += "\n\n**Bot 2 Channels:**\n" + ("\n".join([f"β€’ `@{c}`" for c in TARGET_CHANNELS_2]) if TARGET_CHANNELS_2 else "None")
    return status_text, channels_text

def get_logs():
    return "\n".join(LOG_BUFFER) if LOG_BUFFER else "No logs recorded yet."

def deobfuscate_uploaded_file(file_obj, desired_ext):
    if file_obj is None:
        return None, "Please upload a file first."
    try:
        clean_ext = desired_ext.lstrip('.').strip() if desired_ext else "bin"
        out_path = os.path.join(tempfile.gettempdir(), f"restored_{secrets.token_hex(3)}.{clean_ext}")

        with open(file_obj.name, "rb") as f_in, open(out_path, "wb") as f_out:
            f_in.seek(DUMMY_BYTE_COUNT)
            shutil.copyfileobj(f_in, f_out)

        return out_path, f"Done! Stripped first {DUMMY_BYTE_COUNT} bytes. Saved as .{clean_ext}"
    except Exception as e:
        return None, f"Error: {e}"

with gr.Blocks(title="Telegram Relay & Deobfuscator") as demo:
    gr.Markdown("# Unified Telegram to Bale Relay Dashboard")

    with gr.Tabs():
        with gr.TabItem("Status & Live Logs"):
            with gr.Row():
                status_box = gr.Markdown()
                channels_box = gr.Markdown()

            with gr.Row():
                refresh_btn = gr.Button("Refresh Status & Logs", variant="primary")

            log_output = gr.Code(label="Live Bot Logs (Auto-refreshes every 3s)", language="shell")

            timer = gr.Timer(value=3)
            timer.tick(fn=get_status_info, outputs=[status_box, channels_box])
            timer.tick(fn=get_logs, outputs=[log_output])
            refresh_btn.click(fn=get_status_info, outputs=[status_box, channels_box])
            refresh_btn.click(fn=get_logs, outputs=[log_output])

        with gr.TabItem("File Deobfuscator Tool"):
            gr.Markdown(
                "### Restore files obfuscated by Bot 2\n"
                f"Upload any file received from Bale to trim the first {DUMMY_BYTE_COUNT} dummy bytes."
            )
            with gr.Row():
                file_input = gr.File(label="Upload Obfuscated File")
                target_ext = gr.Textbox(label="Original Extension", placeholder="e.g. zip, apk, conf, json", value="zip")

            restore_btn = gr.Button("Deobfuscate & Restore", variant="primary")
            result_status = gr.Markdown()
            file_output = gr.File(label="Download Clean Restored File")

            restore_btn.click(
                fn=deobfuscate_uploaded_file,
                inputs=[file_input, target_ext],
                outputs=[file_output, result_status]
            )


# ==========================================
# 11. FASTAPI LIFECYCLE & SERVER
# ==========================================
@asynccontextmanager
async def lifespan(app: FastAPI):
    global TELEGRAM_STATUS, TELEGRAM_ERROR
    TELEGRAM_STATUS = "Connecting..."
    add_log("Telegram connecting...")
    try:
        await tg_client.connect()
        if not await tg_client.is_user_authorized():
            TELEGRAM_STATUS = "Unauthorized"
            TELEGRAM_ERROR = "Session string unauthorized."
            add_log("❌ TELEGRAM NOT AUTHORIZED!")
        else:
            TELEGRAM_STATUS = "Connected"
            add_log("βœ… Telegram Connected successfully!")
            asyncio.create_task(tg_client.run_until_disconnected())
    except AuthKeyDuplicatedError:
        TELEGRAM_STATUS = "Session Revoked"
        TELEGRAM_ERROR = "Session duplicated/revoked."
        add_log("❌ Telegram Session Revoked.")
    except Exception as e:
        TELEGRAM_STATUS = "Error"
        TELEGRAM_ERROR = str(e)
        add_log(f"Connection error: {e}")

    yield

    await tg_client.disconnect()
    TELEGRAM_STATUS = "Stopped"
    add_log("Telegram disconnected")

app = FastAPI(lifespan=lifespan)

@app.get("/health")
async def health():
    return {
        "status": TELEGRAM_STATUS,
        "bot1_channels": TARGET_CHANNELS_1,
        "bot2_channels": TARGET_CHANNELS_2
    }

# Mount Gradio onto the root of FastAPI
app = gr.mount_gradio_app(app, demo, path="/")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)