File size: 47,761 Bytes
b7a406c
 
 
 
ec1bb7e
b7a406c
 
 
 
 
ec1bb7e
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
ec1bb7e
 
 
 
 
 
 
 
 
 
 
 
 
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec1bb7e
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec1bb7e
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec1bb7e
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa76d90
 
 
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa76d90
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa76d90
 
 
 
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed390e5
 
 
b7a406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec1bb7e
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
๐Ÿ“ก Telegram Auto Sender Bot - Gradio Space Edition (ZeroGPU Compatible)
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
- ุฅุฑุณุงู„ ุฑุณุงุฆู„ ุฏูˆุฑูŠุฉ ุชู„ู‚ุงุฆูŠุฉ ู„ู„ู…ุฌู…ูˆุนุงุช ุจูุงุตู„ ุฒู…ู†ูŠ ู‚ุงุจู„ ู„ู„ุชุฎุตูŠุต
- ู†ุต ุงู„ุฑุณุงู„ุฉ ู‚ุงุจู„ ู„ู„ุชุญุฑูŠุฑ ู…ู† ุฏุงุฎู„ ุงู„ุจูˆุช
- ุฒุฑ ุฅุฑุณุงู„ ููˆุฑูŠ ู„ูƒู„ ุงู„ู…ุฌู…ูˆุนุงุช
- ุฅุดุนุงุฑ ููˆุฑูŠ ุนู†ุฏ ุงู„ุฑุฏ ุนู„ู‰ ุฑุณุงุฆู„ ุงู„ุจูˆุช
- ู…ุชูˆุงูู‚ ู…ุน ZeroGPU ุนู„ู‰ Hugging Face Spaces
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
"""

import os
import logging
import asyncio
import sqlite3
import threading
import traceback
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional, List, Tuple

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ”ง ุญู„ ZeroGPU: ุฏุงู„ุฉ ูˆู‡ู…ูŠุฉ ู„ุฅุฑุถุงุก ู†ุธุงู… Hugging Face Spaces
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
try:
    import spaces

    @spaces.GPU
    def _warmup_gpu():
        """ุฏุงู„ุฉ ูˆู‡ู…ูŠุฉ ูู‚ุท ู„ุฅุฑุถุงุก ู†ุธุงู… ZeroGPU. ู„ุง ุชุณุชุฎุฏู… GPU ูุนู„ูŠุงู‹."""
        return "ok"
except ImportError:
    pass

import gradio as gr
from telegram import (
    Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
)
from telegram.ext import (
    Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters,
    CallbackContext
)
from telethon import TelegramClient, events
from telethon.sessions import StringSession
from telethon.errors import FloodWaitError

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Logging โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Environment โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
API_ID    = int(os.environ.get("TELEGRAM_API_ID", 0))
API_HASH  = os.environ.get("TELEGRAM_API_HASH", "")

DATA_DIR = Path("/data")
DB_PATH  = DATA_DIR / "users.db"
try:
    DATA_DIR.mkdir(exist_ok=True)
except Exception:
    DATA_DIR = Path("./data")
    DATA_DIR.mkdir(exist_ok=True)
    DB_PATH = DATA_DIR / "users.db"

DEFAULT_MESSAGE = (
    "๐Ÿ”” ุนุฑุถ ุฎุงุต!\n"
    "ู†ู‚ุฏู… ุฎุฏู…ุงุช ู…ู…ูŠุฒุฉ ุจุฃุณุนุงุฑ ู…ู†ุงุณุจุฉ.\n"
    "ู„ู„ุชูˆุงุตู„: @username"
)

INTERVAL_OPTIONS = [15, 30, 60, 120, 240, 480, 720, 1440]


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Database โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def init_db():
    conn = sqlite3.connect(str(DB_PATH))
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS users (
            user_id INTEGER PRIMARY KEY,
            session_string TEXT,
            phone_number TEXT,
            alert_target TEXT DEFAULT 'private',
            alert_target_id TEXT,
            scheduling_active INTEGER DEFAULT 0,
            interval_minutes INTEGER DEFAULT 60,
            message_text TEXT DEFAULT '',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    c.execute('''
        CREATE TABLE IF NOT EXISTS user_groups (
            user_id INTEGER,
            group_id INTEGER,
            group_title TEXT,
            PRIMARY KEY (user_id, group_id)
        )
    ''')
    c.execute('''
        CREATE TABLE IF NOT EXISTS sent_messages (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            chat_id INTEGER,
            message_id INTEGER,
            sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    c.execute('CREATE INDEX IF NOT EXISTS idx_sent_lookup ON sent_messages (user_id, chat_id, message_id)')
    conn.commit()
    conn.close()


def _conn():
    return sqlite3.connect(str(DB_PATH))


def db_get_user(user_id: int):
    conn = _conn()
    c = conn.cursor()
    c.execute("SELECT * FROM users WHERE user_id=?", (user_id,))
    row = c.fetchone()
    conn.close()
    return row


def db_save_session(user_id: int, session_string: str, phone: str = ""):
    conn = _conn()
    c = conn.cursor()
    c.execute('''
        INSERT INTO users (user_id, session_string, phone_number, message_text)
        VALUES (?, ?, ?, COALESCE((SELECT message_text FROM users WHERE user_id=?), ?))
        ON CONFLICT(user_id) DO UPDATE SET
            session_string=excluded.session_string,
            phone_number=excluded.phone_number
    ''', (user_id, session_string, phone, user_id, DEFAULT_MESSAGE))
    conn.commit()
    conn.close()


def db_update_alert(user_id: int, target: str, target_id: Optional[str] = None):
    conn = _conn()
    c = conn.cursor()
    if target_id is not None:
        c.execute("UPDATE users SET alert_target=?, alert_target_id=? WHERE user_id=?",
                  (target, target_id, user_id))
    else:
        c.execute("UPDATE users SET alert_target=? WHERE user_id=?", (target, user_id))
    conn.commit()
    conn.close()


def db_update_interval(user_id: int, minutes: int):
    conn = _conn()
    c = conn.cursor()
    c.execute("UPDATE users SET interval_minutes=? WHERE user_id=?", (minutes, user_id))
    conn.commit()
    conn.close()


def db_update_message(user_id: int, text: str):
    conn = _conn()
    c = conn.cursor()
    c.execute("UPDATE users SET message_text=? WHERE user_id=?", (text, user_id))
    conn.commit()
    conn.close()


def db_set_scheduling(user_id: int, active: bool):
    conn = _conn()
    c = conn.cursor()
    c.execute("UPDATE users SET scheduling_active=? WHERE user_id=?",
              (1 if active else 0, user_id))
    conn.commit()
    conn.close()


def db_get_user_groups(user_id: int) -> List[Tuple[int, str]]:
    conn = _conn()
    c = conn.cursor()
    c.execute("SELECT group_id, group_title FROM user_groups WHERE user_id=?", (user_id,))
    rows = c.fetchall()
    conn.close()
    return rows


def db_save_user_groups(user_id: int, groups: List[Tuple[int, str]]):
    conn = _conn()
    c = conn.cursor()
    c.execute("DELETE FROM user_groups WHERE user_id=?", (user_id,))
    for gid, gtitle in groups:
        c.execute("INSERT INTO user_groups (user_id, group_id, group_title) VALUES (?, ?, ?)",
                  (user_id, gid, gtitle))
    conn.commit()
    conn.close()


def db_save_sent(user_id: int, chat_id: int, message_id: int):
    conn = _conn()
    c = conn.cursor()
    c.execute("INSERT INTO sent_messages (user_id, chat_id, message_id) VALUES (?, ?, ?)",
              (user_id, chat_id, message_id))
    conn.commit()
    conn.close()


def db_is_our_message(user_id: int, chat_id: int, message_id: int) -> bool:
    conn = _conn()
    c = conn.cursor()
    c.execute("SELECT 1 FROM sent_messages WHERE user_id=? AND chat_id=? AND message_id=? LIMIT 1",
              (user_id, chat_id, message_id))
    row = c.fetchone()
    conn.close()
    return row is not None


def db_cleanup_old_sent(days: int = 14):
    conn = _conn()
    c = conn.cursor()
    c.execute(f"DELETE FROM sent_messages WHERE sent_at < datetime('now', '-{days} days')")
    conn.commit()
    conn.close()


def db_all_active_users() -> List[int]:
    conn = _conn()
    c = conn.cursor()
    c.execute("SELECT user_id FROM users WHERE scheduling_active=1 AND session_string IS NOT NULL")
    rows = [r[0] for r in c.fetchall()]
    conn.close()
    return rows


init_db()


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Session Manager โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class SessionManager:
    def __init__(self):
        self.clients: Dict[int, TelegramClient] = {}
        self.keepalive_tasks: Dict[int, asyncio.Task] = {}
        self.schedule_tasks: Dict[int, asyncio.Future] = {}
        self.loop = asyncio.new_event_loop()
        self.bot: Optional[Bot] = None
        self._lock = threading.Lock()

    def start_loop(self):
        def run():
            asyncio.set_event_loop(self.loop)
            self.loop.run_forever()
        threading.Thread(target=run, daemon=True, name="telethon-loop").start()

    def run_coro(self, coro, timeout: float = 60):
        future = asyncio.run_coroutine_threadsafe(coro, self.loop)
        return future.result(timeout=timeout)

    def set_bot(self, bot: Bot):
        self.bot = bot

    # โ”€โ”€ Session validation โ”€โ”€
    async def _validate_session(self, session_string: str):
        client = TelegramClient(StringSession(session_string), API_ID, API_HASH)
        try:
            await asyncio.wait_for(client.connect(), timeout=20)
            if await client.is_user_authorized():
                me = await client.get_me()
                phone = me.phone or ""
                await client.disconnect()
                return True, phone
            await client.disconnect()
            return False, "ุงู„ุฌู„ุณุฉ ุบูŠุฑ ู…ุตุฑุญ ุจู‡ุง"
        except asyncio.TimeoutError:
            return False, "ุงู†ุชู‡ุช ู…ู‡ู„ุฉ ุงู„ุงุชุตุงู„"
        except Exception as e:
            return False, str(e)

    def validate_session(self, session_string: str):
        return self.run_coro(self._validate_session(session_string), timeout=30)

    # โ”€โ”€ Fetch groups โ”€โ”€
    async def _fetch_groups(self, session_str: str):
        client = TelegramClient(StringSession(session_str), API_ID, API_HASH)
        try:
            await asyncio.wait_for(client.connect(), timeout=20)
            if not await client.is_user_authorized():
                raise Exception("ุงู„ุฌู„ุณุฉ ุบูŠุฑ ุตุงู„ุญุฉ")
            dialogs = await client.get_dialogs()
            groups = [(d.id, d.title) for d in dialogs if d.is_group or d.is_channel]
            await client.disconnect()
            return groups
        except asyncio.TimeoutError:
            raise Exception("ุงู†ุชู‡ุช ู…ู‡ู„ุฉ ุงู„ุงุชุตุงู„")

    def fetch_groups(self, session_str: str):
        return self.run_coro(self._fetch_groups(session_str), timeout=40)

    # โ”€โ”€ Client lifecycle โ”€โ”€
    async def _ensure_client(self, user_id: int) -> Optional[TelegramClient]:
        with self._lock:
            client = self.clients.get(user_id)
        if client and client.is_connected():
            return client

        user = db_get_user(user_id)
        if not user or not user[1]:
            return None

        client = TelegramClient(StringSession(user[1]), API_ID, API_HASH)
        try:
            await client.start()
        except Exception as e:
            logger.error(f"Start client failed for {user_id}: {e}")
            return None

        @client.on(events.NewMessage())
        async def _on_new(event):
            try:
                await self._handle_new_message(user_id, event)
            except Exception as e:
                logger.error(f"Reply handler error [{user_id}]: {e}\n{traceback.format_exc()}")

        with self._lock:
            self.clients[user_id] = client
            if user_id not in self.keepalive_tasks or self.keepalive_tasks[user_id].done():
                self.keepalive_tasks[user_id] = asyncio.create_task(self._keepalive(user_id, client))

        logger.info(f"โœ… Client started for {user_id}")
        return client

    async def _keepalive(self, user_id: int, client: TelegramClient):
        while True:
            await asyncio.sleep(60)
            try:
                user = db_get_user(user_id)
                if not user:
                    break
                if not client.is_connected():
                    logger.warning(f"Client {user_id} disconnected, reconnecting...")
                    await client.connect()
            except Exception as e:
                logger.error(f"Keepalive error [{user_id}]: {e}")
                await asyncio.sleep(15)

    # โ”€โ”€ Reply handling โ”€โ”€
    async def _handle_new_message(self, user_id: int, event):
        msg = event.message
        if not msg or not msg.reply_to_msg_id:
            return
        if not db_is_our_message(user_id, msg.chat_id, msg.reply_to_msg_id):
            return
        await self._notify_reply(user_id, event)

    async def _notify_reply(self, user_id: int, event):
        user = db_get_user(user_id)
        if not user:
            return
        alert_target = user[3]
        alert_target_id = user[4]
        target = user_id if alert_target == "private" else alert_target_id
        if not target:
            return

        msg = event.message
        try:
            sender = await event.get_sender()
        except Exception:
            sender = None

        sender_name = ""
        if sender:
            sender_name = getattr(sender, "first_name", "") or ""
            if getattr(sender, "last_name", None):
                sender_name += f" {sender.last_name}"
            if not sender_name:
                sender_name = getattr(sender, "title", "") or "ุบูŠุฑ ู…ุนุฑูˆู"
        uname = f"@{sender.username}" if sender and getattr(sender, "username", None) else "ู„ุง ูŠูˆุฌุฏ"

        try:
            chat = await event.get_chat()
            chat_title = getattr(chat, "title", "ู…ุญุงุฏุซุฉ")
        except Exception:
            chat_title = "ู…ุญุงุฏุซุฉ"

        original_text = "(ุบูŠุฑ ู…ุชูˆูุฑุฉ)"
        try:
            orig = await event.client.get_messages(msg.chat_id, ids=msg.reply_to_msg_id)
            if orig and orig.text:
                original_text = orig.text
        except Exception:
            pass

        time_str = msg.date.strftime("%Y-%m-%d %H:%M:%S") if msg.date else datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        reply_text = msg.text or "(ุฑุณุงู„ุฉ ุบูŠุฑ ู†ุตูŠุฉ)"

        text = (
            f"๐Ÿ”” <b>ุฑุฏ ุฌุฏูŠุฏ ุนู„ู‰ ุฑุณุงู„ุชูƒ</b>\n"
            f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
            f"๐Ÿ‘ค <b>ุงู„ุงุณู…:</b> {sender_name}\n"
            f"๐Ÿ“› <b>ุงู„ูŠูˆุฒุฑ:</b> {uname}\n"
            f"๐Ÿ†” <b>ุงู„ู…ุนุฑู:</b> <code>{msg.sender_id}</code>\n"
            f"๐Ÿ“ <b>ุงู„ู…ุฌู…ูˆุนุฉ:</b> {chat_title}\n"
            f"โฐ <b>ุงู„ูˆู‚ุช:</b> <code>{time_str}</code>\n"
            f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
            f"๐Ÿ’ฌ <b>ุฑุณุงู„ุชูƒ ุงู„ุฃุตู„ูŠุฉ:</b>\n<i>{original_text[:300]}</i>\n\n"
            f"โ†ฉ๏ธ <b>ู†ุต ุงู„ุฑุฏ:</b>\n<b>{reply_text[:800]}</b>"
        )

        try:
            await asyncio.to_thread(
                self.bot.send_message,
                chat_id=target,
                text=text,
                parse_mode=ParseMode.HTML,
                disable_web_page_preview=True
            )
            logger.info(f"๐Ÿ“ฉ Reply notified to {target} for user {user_id}")
        except Exception as e:
            logger.error(f"Failed to notify reply: {e}")

    # โ”€โ”€ Send to all โ”€โ”€
    async def _send_to_all_groups(self, user_id: int) -> Tuple[int, int]:
        user = db_get_user(user_id)
        if not user:
            return 0, 0
        message_text = (user[7] or "").strip()
        if not message_text:
            return 0, 0

        groups = db_get_user_groups(user_id)
        if not groups:
            return 0, 0

        client = await self._ensure_client(user_id)
        if not client:
            return 0, 0

        sent = failed = 0
        for gid, gtitle in groups:
            try:
                msg = await client.send_message(gid, message_text)
                db_save_sent(user_id, gid, msg.id)
                sent += 1
                await asyncio.sleep(2.5)
            except FloodWaitError as e:
                wait = e.seconds + 2
                logger.warning(f"FloodWait {wait}s for user {user_id}")
                await asyncio.sleep(wait)
                try:
                    msg = await client.send_message(gid, message_text)
                    db_save_sent(user_id, gid, msg.id)
                    sent += 1
                except Exception as e2:
                    logger.error(f"Retry failed [{gid}]: {e2}")
                    failed += 1
            except Exception as e:
                logger.error(f"Send failed [{user_id} -> {gid}]: {e}")
                failed += 1

        logger.info(f"โœ… User {user_id}: sent={sent}, failed={failed}")
        return sent, failed

    # โ”€โ”€ Public API โ”€โ”€
    def start_scheduling(self, user_id: int) -> Tuple[bool, str]:
        with self._lock:
            task = self.schedule_tasks.get(user_id)
            if task and not task.done():
                return False, "ุงู„ุฌุฏูˆู„ุฉ ู‚ูŠุฏ ุงู„ุชุดุบูŠู„ ุจุงู„ูุนู„"

        user = db_get_user(user_id)
        if not user or not user[1]:
            return False, "ูŠุฌุจ ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„ ุฃูˆู„ุงู‹"
        if not (user[7] or "").strip():
            return False, "ู„ู… ุชุญุฏุฏ ู†ุต ุงู„ุฑุณุงู„ุฉ ุจุนุฏ"
        if not db_get_user_groups(user_id):
            return False, "ู„ู… ุชุฎุชุฑ ุฃูŠ ู…ุฌู…ูˆุนุฉ"

        future = asyncio.run_coroutine_threadsafe(self._scheduler_loop(user_id), self.loop)
        with self._lock:
            self.schedule_tasks[user_id] = future
        db_set_scheduling(user_id, True)
        return True, "โœ… ุจุฏุฃ ุงู„ุฅุฑุณุงู„ ุงู„ุฏูˆุฑูŠ"

    def stop_scheduling(self, user_id: int) -> Tuple[bool, str]:
        db_set_scheduling(user_id, False)
        with self._lock:
            task = self.schedule_tasks.pop(user_id, None)
        if task and not task.done():
            task.cancel()
            return True, "โน๏ธ ุชู… ุฅูŠู‚ุงู ุงู„ุฅุฑุณุงู„ ุงู„ุฏูˆุฑูŠ"
        return False, "ุงู„ุฌุฏูˆู„ุฉ ุบูŠุฑ ู†ุดุทุฉ"

    def is_scheduling(self, user_id: int) -> bool:
        with self._lock:
            task = self.schedule_tasks.get(user_id)
            return task is not None and not task.done()

    async def _scheduler_loop(self, user_id: int):
        try:
            while True:
                user = db_get_user(user_id)
                if not user or user[5] == 0:
                    break

                try:
                    await self._send_to_all_groups(user_id)
                except Exception as e:
                    logger.error(f"Send cycle error [{user_id}]: {e}")

                user = db_get_user(user_id)
                if not user or user[5] == 0:
                    break
                interval = int(user[6] or 60)

                waited = 0
                while waited < interval * 60:
                    await asyncio.sleep(min(30, interval * 60 - waited))
                    waited += 30
                    u = db_get_user(user_id)
                    if not u or u[5] == 0:
                        return
                    if int(u[6] or 60) != interval:
                        break
        except asyncio.CancelledError:
            logger.info(f"Scheduler cancelled for {user_id}")
        except Exception as e:
            logger.error(f"Scheduler crashed [{user_id}]: {e}\n{traceback.format_exc()}")
            db_set_scheduling(user_id, False)
        finally:
            with self._lock:
                self.schedule_tasks.pop(user_id, None)

    def send_now(self, user_id: int) -> Tuple[bool, str]:
        user = db_get_user(user_id)
        if not user or not user[1]:
            return False, "ูŠุฌุจ ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„ ุฃูˆู„ุงู‹"
        if not (user[7] or "").strip():
            return False, "ู„ู… ุชุญุฏุฏ ู†ุต ุงู„ุฑุณุงู„ุฉ"
        if not db_get_user_groups(user_id):
            return False, "ู„ู… ุชุฎุชุฑ ุฃูŠ ู…ุฌู…ูˆุนุฉ"
        try:
            fut = asyncio.run_coroutine_threadsafe(self._send_to_all_groups(user_id), self.loop)
            sent, failed = fut.result(timeout=180)
            return True, f"โœ… ุชู… ุงู„ุฅุฑุณุงู„:\nโ€ข ู†ุฌุญ: {sent}\nโ€ข ูุดู„: {failed}"
        except Exception as e:
            return False, f"โŒ ุฎุทุฃ: {e}"

    def resume_all(self):
        for uid in db_all_active_users():
            try:
                asyncio.run_coroutine_threadsafe(self._ensure_client(uid), self.loop)
                fut = asyncio.run_coroutine_threadsafe(self._scheduler_loop(uid), self.loop)
                with self._lock:
                    self.schedule_tasks[uid] = fut
                logger.info(f"โ™ป๏ธ Resumed scheduler for {uid}")
            except Exception as e:
                logger.error(f"Resume failed [{uid}]: {e}")


session_manager = SessionManager()


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Bot helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def is_logged(user_id: int) -> bool:
    u = db_get_user(user_id)
    return bool(u and u[1])


def fmt_interval(m: int) -> str:
    if m < 60:
        return f"{m} ุฏู‚ูŠู‚ุฉ"
    if m == 60:
        return "ุณุงุนุฉ"
    if m < 1440:
        h = m / 60
        return f"{h:g} ุณุงุนุฉ"
    d = m / 1440
    return f"{d:g} ูŠูˆู…"


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Main menu โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def main_menu_kb(user_id: int) -> InlineKeyboardMarkup:
    logged = is_logged(user_id)
    rows = []
    if not logged:
        rows.append([InlineKeyboardButton("๐Ÿ” ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„", callback_data="menu_login")])
    else:
        rows.append([InlineKeyboardButton("๐Ÿ‘ฅ ุงุฎุชูŠุงุฑ ุงู„ู…ุฌู…ูˆุนุงุช", callback_data="menu_groups")])
        rows.append([InlineKeyboardButton("โš™๏ธ ุงู„ุฅุนุฏุงุฏุงุช", callback_data="menu_settings")])
        if session_manager.is_scheduling(user_id):
            rows.append([InlineKeyboardButton("โน๏ธ ุฅูŠู‚ุงู ุงู„ุฅุฑุณุงู„ ุงู„ุฏูˆุฑูŠ", callback_data="menu_stop")])
        else:
            rows.append([InlineKeyboardButton("โ–ถ๏ธ ุจุฏุก ุงู„ุฅุฑุณุงู„ ุงู„ุฏูˆุฑูŠ", callback_data="menu_start")])
        rows.append([InlineKeyboardButton("๐Ÿš€ ุฅุฑุณุงู„ ุงู„ุขู† ู„ูƒู„ ุงู„ู…ุฌู…ูˆุนุงุช", callback_data="menu_send_now")])
        rows.append([InlineKeyboardButton("๐Ÿ“Š ุงู„ุญุงู„ุฉ", callback_data="menu_status")])
        rows.append([InlineKeyboardButton("๐Ÿšช ุชุณุฌูŠู„ ุงู„ุฎุฑูˆุฌ", callback_data="menu_logout")])
    return InlineKeyboardMarkup(rows)


def show_main_menu(update: Update, context: CallbackContext, edit: bool = True):
    user = update.effective_user
    user_id = user.id
    logged = is_logged(user_id)
    if logged:
        u = db_get_user(user_id)
        interval = fmt_interval(u[6] or 60)
        status = "๐ŸŸข ูŠุนู…ู„" if session_manager.is_scheduling(user_id) else "๐Ÿ”ด ู…ุชูˆู‚ู"
        msg_preview = (u[7] or "").strip()[:60].replace("\n", " ") or "(ู„ู… ูŠุชู… ุงู„ุชุนูŠูŠู†)"
        text = (
            f"๐Ÿ‘‹ ุฃู‡ู„ุงู‹ <b>{user.first_name}</b>\n\n"
            f"โš™๏ธ <b>ุงู„ุฅุนุฏุงุฏุงุช ุงู„ุญุงู„ูŠุฉ:</b>\n"
            f"โ€ข ุงู„ูุงุตู„ ุงู„ุฒู…ู†ูŠ: <b>{interval}</b>\n"
            f"โ€ข ุญุงู„ุฉ ุงู„ุฌุฏูˆู„ุฉ: <b>{status}</b>\n"
            f"โ€ข ู†ุต ุงู„ุฑุณุงู„ุฉ: <i>{msg_preview}...</i>\n"
        )
    else:
        text = (
            f"๐Ÿ‘‹ ุฃู‡ู„ุงู‹ <b>{user.first_name}</b>\n\n"
            f"ู„ู„ุจุฏุกุŒ ุณุฌู‘ู„ ุงู„ุฏุฎูˆู„ ุจูƒูˆุฏ ุงู„ุฌู„ุณุฉ (StringSession)."
        )
    kb = main_menu_kb(user_id)
    if edit and update.callback_query:
        try:
            update.callback_query.edit_message_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)
        except Exception:
            pass
    else:
        update.message.reply_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)


def cmd_start(update: Update, context: CallbackContext):
    context.user_data.pop('state', None)
    show_main_menu(update, context, edit=False)


def cmd_help(update: Update, context: CallbackContext):
    update.message.reply_text(
        "๐Ÿ“š <b>ุงู„ุฃูˆุงู…ุฑ ุงู„ู…ุชุงุญุฉ:</b>\n"
        "/start - ุงู„ู‚ุงุฆู…ุฉ ุงู„ุฑุฆูŠุณูŠุฉ\n"
        "/login - ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„ ุจูƒูˆุฏ ุงู„ุฌู„ุณุฉ\n"
        "/status - ุญุงู„ุฉ ุงู„ุญุณุงุจ\n"
        "/ping - ูุญุต ุญุงู„ุฉ ุงู„ุจูˆุช\n"
        "/cancel - ุฅู„ุบุงุก ุงู„ุนู…ู„ูŠุฉ ุงู„ุญุงู„ูŠุฉ",
        parse_mode=ParseMode.HTML
    )


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Menu callbacks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def menu_callback(update: Update, context: CallbackContext):
    q = update.callback_query
    q.answer()
    data = q.data
    user_id = update.effective_user.id

    if data == "menu_login":
        context.user_data['state'] = 'session'
        q.edit_message_text(
            "๐Ÿ” <b>ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„ ุจูƒูˆุฏ ุงู„ุฌู„ุณุฉ</b>\n\n"
            "ุฃุฑุณู„ ูƒูˆุฏ ุงู„ุฌู„ุณุฉ (StringSession) ุงู„ุฎุงุต ุจุญุณุงุจูƒ.\n"
            "ู„ู„ุฅู„ุบุงุก ุฃุฑุณู„ /cancel",
            parse_mode=ParseMode.HTML
        )
        return

    if not is_logged(user_id):
        q.answer("ูŠุฌุจ ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„ ุฃูˆู„ุงู‹", show_alert=True)
        return

    if data == "menu_groups":
        show_groups(update, context)
    elif data == "menu_settings":
        show_settings(update, context)
    elif data == "menu_start":
        ok, msg = session_manager.start_scheduling(user_id)
        q.answer(msg, show_alert=True)
        show_main_menu(update, context)
    elif data == "menu_stop":
        ok, msg = session_manager.stop_scheduling(user_id)
        q.answer(msg, show_alert=True)
        show_main_menu(update, context)
    elif data == "menu_send_now":
        q.edit_message_text("โณ ุฌุงุฑู ุฅุฑุณุงู„ ุงู„ุฑุณุงู„ุฉ ู„ูƒู„ ุงู„ู…ุฌู…ูˆุนุงุช...")
        ok, msg = session_manager.send_now(user_id)
        q.edit_message_text(
            msg,
            parse_mode=ParseMode.HTML,
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("๐Ÿ”™ ุฑุฌูˆุน", callback_data="menu_back")]])
        )
    elif data == "menu_status":
        show_status(update, context)
    elif data == "menu_logout":
        session_manager.stop_scheduling(user_id)
        conn = _conn()
        c = conn.cursor()
        c.execute("UPDATE users SET session_string=NULL, scheduling_active=0 WHERE user_id=?", (user_id,))
        conn.commit()
        conn.close()
        q.answer("ุชู… ุชุณุฌูŠู„ ุงู„ุฎุฑูˆุฌ", show_alert=True)
        show_main_menu(update, context)
    elif data == "menu_back":
        show_main_menu(update, context)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Login โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def handle_session_input(update: Update, context: CallbackContext):
    user_id = update.effective_user.id
    session_string = update.message.text.strip()
    msg = update.message.reply_text("โณ ุฌุงุฑู ุงู„ุชุญู‚ู‚ ู…ู† ุงู„ุฌู„ุณุฉ...")
    try:
        ok, result = session_manager.validate_session(session_string)
    except Exception as e:
        ok, result = False, str(e)
    try:
        msg.delete()
    except Exception:
        pass

    if ok:
        db_save_session(user_id, session_string, result if isinstance(result, str) else "")
        try:
            asyncio.run_coroutine_threadsafe(session_manager._ensure_client(user_id), session_manager.loop)
        except Exception as e:
            logger.error(f"Failed to start client background: {e}")
        update.message.reply_text("โœ… <b>ุชู… ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„ ุจู†ุฌุงุญ!</b>", parse_mode=ParseMode.HTML)
    else:
        update.message.reply_text(f"โŒ ูุดู„: {result}\n\nุญุงูˆู„ ู…ุฑุฉ ุฃุฎุฑู‰ ุฃูˆ ุฃุฑุณู„ /cancel.")

    context.user_data.pop('state', None)
    show_main_menu(update, context, edit=False)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Groups โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def show_groups(update: Update, context: CallbackContext, page: int = 0, refresh: bool = False):
    q = update.callback_query
    user_id = update.effective_user.id
    user = db_get_user(user_id)
    if not user or not user[1]:
        q.edit_message_text("โŒ ุงู„ุฌู„ุณุฉ ุบูŠุฑ ุตุงู„ุญุฉ. ุงู„ุฑุฌุงุก ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„.")
        return

    if refresh or 'groups_list' not in context.user_data:
        q.edit_message_text("โณ ุฌุงุฑู ุฌู„ุจ ุงู„ู…ุฌู…ูˆุนุงุช ู…ู† ุชูŠู„ูŠุฌุฑุงู…...")
        try:
            groups = session_manager.fetch_groups(user[1])
        except Exception as e:
            q.edit_message_text(
                f"โŒ ูุดู„ ุงู„ุฌู„ุจ:\n{e}",
                reply_markup=InlineKeyboardMarkup([
                    [InlineKeyboardButton("๐Ÿ”„ ุฅุนุงุฏุฉ ุงู„ู…ุญุงูˆู„ุฉ", callback_data="grp_refresh")],
                    [InlineKeyboardButton("๐Ÿ”™ ุฑุฌูˆุน", callback_data="menu_back")],
                ])
            )
            return
        groups.sort(key=lambda x: x[1].lower())
        context.user_data['groups_list'] = groups
        context.user_data['temp_selected'] = {g[0] for g in db_get_user_groups(user_id)}

    groups_list: List[Tuple[int, str]] = context.user_data['groups_list']
    selected: set = context.user_data['temp_selected']

    if not groups_list:
        q.edit_message_text("โŒ ู„ุง ุชูˆุฌุฏ ู…ุฌู…ูˆุนุงุช.")
        return

    per_page = 8
    total_pages = max(1, (len(groups_list) + per_page - 1) // per_page)
    page = max(0, min(page, total_pages - 1))
    start = page * per_page
    end = start + per_page

    rows = []
    for gid, gtitle in groups_list[start:end]:
        prefix = "โœ…" if gid in selected else "โฌœ๏ธ"
        rows.append([InlineKeyboardButton(f"{prefix} {gtitle[:40]}", callback_data=f"tog_{gid}")])

    nav = []
    if page > 0:
        nav.append(InlineKeyboardButton("โ—€๏ธ", callback_data=f"grp_page_{page-1}"))
    nav.append(InlineKeyboardButton(f"{page+1}/{total_pages}", callback_data="noop"))
    if page < total_pages - 1:
        nav.append(InlineKeyboardButton("โ–ถ๏ธ", callback_data=f"grp_page_{page+1}"))
    if nav:
        rows.append(nav)

    rows.append([InlineKeyboardButton(f"๐Ÿ’พ ุญูุธ ({len(selected)} ู…ุฎุชุงุฑุฉ)", callback_data="grp_save")])
    rows.append([InlineKeyboardButton("๐Ÿ”„ ุชุญุฏูŠุซ", callback_data="grp_refresh")])
    rows.append([InlineKeyboardButton("๐Ÿ”™ ุฑุฌูˆุน", callback_data="menu_back")])

    # โœจ ุญูุธ ุงู„ุตูุญุฉ ุงู„ุญุงู„ูŠุฉ ู„ู…ู†ุน ุงู„ุฑุฌูˆุน ู„ู„ุตูุญุฉ ุงู„ุฃูˆู„ู‰
    context.user_data['groups_page'] = page

    q.edit_message_text(
        f"๐Ÿ“Œ <b>ุงุฎุชุฑ ุงู„ู…ุฌู…ูˆุนุงุช ู„ู„ุฅุฑุณุงู„</b>\n"
        f"ุฅุฌู…ุงู„ูŠ: {len(groups_list)} | ู…ุฎุชุงุฑ: {len(selected)}",
        parse_mode=ParseMode.HTML,
        reply_markup=InlineKeyboardMarkup(rows)
    )


def groups_callback(update: Update, context: CallbackContext):
    q = update.callback_query
    data = q.data
    user_id = update.effective_user.id

    if data == "noop":
        q.answer()
        return

    if data == "grp_refresh":
        q.answer("ุฌุงุฑูŠ ุงู„ุชุญุฏูŠุซ...")
        show_groups(update, context, page=0, refresh=True)
        return

    if data == "grp_save":
        groups_list = context.user_data.get('groups_list', [])
        selected = context.user_data.get('temp_selected', set())
        to_save = [(gid, t) for gid, t in groups_list if gid in selected]
        db_save_user_groups(user_id, to_save)
        context.user_data.pop('groups_list', None)
        context.user_data.pop('temp_selected', None)
        context.user_data.pop('groups_page', None)
        q.answer(f"ุชู… ุญูุธ {len(to_save)} ู…ุฌู…ูˆุนุฉ โœ…", show_alert=True)
        show_main_menu(update, context)
        return

    if data.startswith("grp_page_"):
        page = int(data.split("_")[2])
        q.answer()
        show_groups(update, context, page=page)
        return

    if data.startswith("tog_"):
        try:
            gid = int(data.split("_", 1)[1])
        except ValueError:
            q.answer()
            return
        selected: set = context.user_data.get('temp_selected', set())
        if gid in selected:
            selected.discard(gid)
        else:
            selected.add(gid)
        context.user_data['temp_selected'] = selected

        # โœจ ุงู„ุญู„: ุงู‚ุฑุฃ ุงู„ุตูุญุฉ ุงู„ุญุงู„ูŠุฉ ู…ู† context ุจุฏู„ุงู‹ ู…ู† regex
        page = context.user_data.get('groups_page', 0)

        q.answer()
        show_groups(update, context, page=page)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Settings โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def show_settings(update: Update, context: CallbackContext):
    q = update.callback_query
    user_id = update.effective_user.id
    u = db_get_user(user_id)
    interval = fmt_interval(u[6] or 60)
    msg_text = (u[7] or "").strip()
    preview = msg_text[:80].replace("\n", " ") + ("..." if len(msg_text) > 80 else "")
    if not preview:
        preview = "(ู„ู… ูŠุชู… ุงู„ุชุนูŠูŠู†)"
    target = "๐Ÿ“ฑ ุญุณุงุจูƒ ุงู„ุฎุงุต" if u[3] == "private" else f"๐Ÿ“ข {u[4] or 'ุบูŠุฑ ู…ุญุฏุฏ'}"

    text = (
        f"โš™๏ธ <b>ุงู„ุฅุนุฏุงุฏุงุช</b>\n"
        f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
        f"โฑ๏ธ ุงู„ูุงุตู„ ุงู„ุฒู…ู†ูŠ: <b>{interval}</b>\n"
        f"๐Ÿ“ข ูˆุฌู‡ุฉ ุงู„ุชู†ุจูŠู‡ุงุช: <b>{target}</b>\n"
        f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
        f"๐Ÿ“ <b>ู†ุต ุงู„ุฑุณุงู„ุฉ:</b>\n<i>{preview}</i>"
    )
    kb = InlineKeyboardMarkup([
        [InlineKeyboardButton("โฑ๏ธ ุชุบูŠูŠุฑ ุงู„ูุงุตู„ ุงู„ุฒู…ู†ูŠ", callback_data="set_interval_menu")],
        [InlineKeyboardButton("๐Ÿ“ ุชุนุฏูŠู„ ู†ุต ุงู„ุฑุณุงู„ุฉ", callback_data="set_message")],
        [InlineKeyboardButton("๐Ÿ“ข ูˆุฌู‡ุฉ ุงู„ุชู†ุจูŠู‡ุงุช", callback_data="set_alert_menu")],
        [InlineKeyboardButton("๐Ÿ”™ ุฑุฌูˆุน", callback_data="menu_back")],
    ])
    q.edit_message_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)


def settings_callback(update: Update, context: CallbackContext):
    q = update.callback_query
    user_id = update.effective_user.id
    data = q.data

    if data == "set_interval_menu":
        rows = []
        row = []
        for i, m in enumerate(INTERVAL_OPTIONS):
            row.append(InlineKeyboardButton(fmt_interval(m), callback_data=f"set_int_{m}"))
            if len(row) == 3:
                rows.append(row)
                row = []
        if row:
            rows.append(row)
        rows.append([InlineKeyboardButton("โœ๏ธ ู…ุฎุตุต (ุจุงู„ุฏู‚ุงุฆู‚)", callback_data="set_int_custom")])
        rows.append([InlineKeyboardButton("๐Ÿ”™ ุฑุฌูˆุน", callback_data="menu_settings")])
        q.edit_message_text(
            "โฑ๏ธ ุงุฎุชุฑ ุงู„ูุงุตู„ ุงู„ุฒู…ู†ูŠ ุจูŠู† ูƒู„ ุฅุฑุณุงู„ ูˆุขุฎุฑ:",
            reply_markup=InlineKeyboardMarkup(rows)
        )
    elif data.startswith("set_int_"):
        val = data.split("_")[2]
        if val == "custom":
            context.user_data['state'] = 'custom_interval'
            q.edit_message_text("โœ๏ธ ุฃุฑุณู„ ุงู„ูุงุตู„ ุงู„ุฒู…ู†ูŠ ุจุงู„ุฏู‚ุงุฆู‚ (ุฑู‚ู… ุจูŠู† 1 ูˆ 10080):")
        else:
            m = int(val)
            db_update_interval(user_id, m)
            q.answer(f"โœ… ุชู… ุงู„ุชุนูŠูŠู†: {fmt_interval(m)}", show_alert=True)
            show_settings(update, context)
    elif data == "set_message":
        context.user_data['state'] = 'message'
        u = db_get_user(user_id)
        current = (u[7] or "").strip() or "(ูุงุฑุบุฉ)"
        q.edit_message_text(
            f"๐Ÿ“ <b>ุชุนุฏูŠู„ ู†ุต ุงู„ุฑุณุงู„ุฉ</b>\n\n"
            f"<b>ุงู„ู†ุต ุงู„ุญุงู„ูŠ:</b>\n<i>{current[:500]}</i>\n\n"
            f"ุฃุฑุณู„ ุงู„ู†ุต ุงู„ุฌุฏูŠุฏ ุงู„ุขู† (ูŠุฏุนู… ุฃุณุทุฑ ู…ุชุนุฏุฏุฉ).",
            parse_mode=ParseMode.HTML
        )
    elif data == "set_alert_menu":
        kb = InlineKeyboardMarkup([
            [InlineKeyboardButton("๐Ÿ“ฑ ุญุณุงุจูŠ ุงู„ุฎุงุต", callback_data="set_alert_private")],
            [InlineKeyboardButton("๐Ÿ“ข ู‚ู†ุงุฉ/ู…ุฌู…ูˆุนุฉ (ID ุฃูˆ @username)", callback_data="set_alert_channel")],
            [InlineKeyboardButton("๐Ÿ”™ ุฑุฌูˆุน", callback_data="menu_settings")],
        ])
        q.edit_message_text("๐Ÿ“ข ุงุฎุชุฑ ูˆุฌู‡ุฉ ุฅุดุนุงุฑุงุช ุงู„ุฑุฏูˆุฏ:", reply_markup=kb)
    elif data == "set_alert_private":
        db_update_alert(user_id, "private", "")
        q.answer("โœ… ุชู… ุงู„ุชุนูŠูŠู† ุฅู„ู‰ ุญุณุงุจูƒ ุงู„ุฎุงุต", show_alert=True)
        show_settings(update, context)
    elif data == "set_alert_channel":
        context.user_data['state'] = 'channel'
        q.edit_message_text(
            "๐Ÿ“ข ุฃุฑุณู„ ู…ุนุฑู ุงู„ู‚ู†ุงุฉ/ุงู„ู…ุฌู…ูˆุนุฉ:\n"
            "โ€ข ูŠู…ูƒู†ูƒ ุฅุฑุณุงู„ <code>@username</code>\n"
            "โ€ข ุฃูˆ ุงู„ู…ุนุฑู ุงู„ุฑู‚ู…ูŠ ู…ุซู„ <code>-1001234567890</code>\n\n"
            "โš ๏ธ ุชุฃูƒุฏ ู…ู† ุฃู† ุงู„ุจูˆุช ู…ุดุฑู ููŠ ุงู„ู‚ู†ุงุฉ.",
            parse_mode=ParseMode.HTML
        )


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Status โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def show_status(update: Update, context: CallbackContext):
    q = update.callback_query
    user_id = update.effective_user.id
    u = db_get_user(user_id)
    if not u:
        q.edit_message_text("ู„ุง ุชูˆุฌุฏ ุจูŠุงู†ุงุช.")
        return
    groups = db_get_user_groups(user_id)
    interval = fmt_interval(u[6] or 60)
    sched = "๐ŸŸข ูŠุนู…ู„" if session_manager.is_scheduling(user_id) else "๐Ÿ”ด ู…ุชูˆู‚ู"
    client_ok = session_manager.clients.get(user_id)
    client_status = "๐ŸŸข ู…ุชุตู„" if (client_ok and client_ok.is_connected()) else "๐Ÿ”ด ุบูŠุฑ ู…ุชุตู„"
    target = "๐Ÿ“ฑ ุญุณุงุจูƒ" if u[3] == "private" else f"๐Ÿ“ข {u[4] or 'โ€”'}"

    msg_text = (u[7] or "").strip()
    preview = msg_text[:120].replace("\n", " ") + ("..." if len(msg_text) > 120 else "")
    if not preview:
        preview = "(ู„ู… ูŠุชู… ุงู„ุชุนูŠูŠู†)"

    text = (
        f"๐Ÿ“Š <b>ุญุงู„ุฉ ุงู„ุญุณุงุจ</b>\n"
        f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
        f"๐Ÿ‘ค ุงู„ู…ุณุชุฎุฏู…: <code>{user_id}</code>\n"
        f"๐Ÿ“ž ุงู„ู‡ุงุชู: <code>{u[2] or 'โ€”'}</code>\n"
        f"๐Ÿ”Œ ุงู„ุงุชุตุงู„: {client_status}\n"
        f"โ–ถ๏ธ ุงู„ุฌุฏูˆู„ุฉ: {sched}\n"
        f"โฑ๏ธ ุงู„ูุงุตู„: <b>{interval}</b>\n"
        f"๐Ÿ‘ฅ ุงู„ู…ุฌู…ูˆุนุงุช: <b>{len(groups)}</b>\n"
        f"๐Ÿ“ข ูˆุฌู‡ุฉ ุงู„ุชู†ุจูŠู‡ุงุช: {target}\n"
        f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
        f"๐Ÿ“ <b>ู†ุต ุงู„ุฑุณุงู„ุฉ:</b>\n<i>{preview}</i>"
    )
    q.edit_message_text(
        text,
        parse_mode=ParseMode.HTML,
        reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("๐Ÿ”™ ุฑุฌูˆุน", callback_data="menu_back")]])
    )


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Text router โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def text_router(update: Update, context: CallbackContext):
    state = context.user_data.get('state')
    if not state:
        return
    user_id = update.effective_user.id
    text = update.message.text

    if state == 'session':
        handle_session_input(update, context)

    elif state == 'message':
        if len(text) > 4000:
            update.message.reply_text("โŒ ุงู„ู†ุต ุทูˆูŠู„ ุฌุฏุงู‹ (ุงู„ุญุฏ 4000 ุญุฑู).")
            return
        db_update_message(user_id, text)
        context.user_data.pop('state', None)
        update.message.reply_text(f"โœ… ุชู… ุญูุธ ู†ุต ุงู„ุฑุณุงู„ุฉ ({len(text)} ุญุฑู).")
        show_main_menu(update, context, edit=False)

    elif state == 'custom_interval':
        try:
            n = int(text.strip())
            if n < 1 or n > 10080:
                raise ValueError
        except ValueError:
            update.message.reply_text("โŒ ุฃุฏุฎู„ ุฑู‚ู…ุงู‹ ุตุญูŠุญุงู‹ ุจูŠู† 1 ูˆ 10080.")
            return
        db_update_interval(user_id, n)
        context.user_data.pop('state', None)
        update.message.reply_text(f"โœ… ุชู… ุชุนูŠูŠู† ุงู„ูุงุตู„: {fmt_interval(n)}")

    elif state == 'channel':
        target = text.strip()
        if not target:
            update.message.reply_text("โŒ ุฃุฏุฎู„ ู…ุนุฑูุงู‹ ุตุงู„ุญุงู‹.")
            return
        db_update_alert(user_id, "channel", target)
        context.user_data.pop('state', None)
        update.message.reply_text(f"โœ… ุชู… ุญูุธ ูˆุฌู‡ุฉ ุงู„ุชู†ุจูŠู‡ุงุช: <code>{target}</code>", parse_mode=ParseMode.HTML)


def cmd_cancel(update: Update, context: CallbackContext):
    context.user_data.pop('state', None)
    update.message.reply_text("โŒ ุชู… ุงู„ุฅู„ุบุงุก.")
    show_main_menu(update, context, edit=False)


def cmd_ping(update: Update, context: CallbackContext):
    update.message.reply_text("๐ŸŸข ุงู„ุจูˆุช ูŠุนู…ู„.")


def cmd_status(update: Update, context: CallbackContext):
    user_id = update.effective_user.id
    u = db_get_user(user_id)
    if not u:
        update.message.reply_text("โŒ ู„ู… ุชุณุฌู„ ุงู„ุฏุฎูˆู„.")
        return
    groups = db_get_user_groups(user_id)
    sched = "๐ŸŸข ูŠุนู…ู„" if session_manager.is_scheduling(user_id) else "๐Ÿ”ด ู…ุชูˆู‚ู"
    update.message.reply_text(
        f"๐Ÿ“Š <b>ุงู„ุญุงู„ุฉ</b>\n"
        f"โ–ถ๏ธ ุงู„ุฌุฏูˆู„ุฉ: {sched}\n"
        f"โฑ๏ธ ุงู„ูุงุตู„: {fmt_interval(u[6] or 60)}\n"
        f"๐Ÿ‘ฅ ุงู„ู…ุฌู…ูˆุนุงุช: {len(groups)}",
        parse_mode=ParseMode.HTML
    )


def cmd_login(update: Update, context: CallbackContext):
    context.user_data['state'] = 'session'
    update.message.reply_text(
        "๐Ÿ” <b>ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„</b>\n\nุฃุฑุณู„ ูƒูˆุฏ ุงู„ุฌู„ุณุฉ (StringSession):",
        parse_mode=ParseMode.HTML
    )


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Cleanup loop โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def start_cleanup_loop():
    async def _loop():
        while True:
            try:
                db_cleanup_old_sent(14)
            except Exception as e:
                logger.error(f"Cleanup error: {e}")
            await asyncio.sleep(6 * 3600)
    asyncio.run_coroutine_threadsafe(_loop(), session_manager.loop)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Run bot in background โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def run_bot_in_background():
    """ุชุดุบูŠู„ ุจูˆุช ุชูŠู„ูŠุฌุฑุงู… ููŠ ุฎูŠุท ู…ู†ูุตู„."""
    if not BOT_TOKEN or not API_ID or not API_HASH:
        logger.error("โŒ Missing env vars: TELEGRAM_BOT_TOKEN / TELEGRAM_API_ID / TELEGRAM_API_HASH")
        return

    session_manager.start_loop()

    updater = Updater(BOT_TOKEN, use_context=True)
    dp = updater.dispatcher
    session_manager.set_bot(updater.bot)

    # Handlers
    dp.add_handler(CommandHandler("start", cmd_start))
    dp.add_handler(CommandHandler("help", cmd_help))
    dp.add_handler(CommandHandler("cancel", cmd_cancel))
    dp.add_handler(CommandHandler("ping", cmd_ping))
    dp.add_handler(CommandHandler("status", cmd_status))
    dp.add_handler(CommandHandler("login", cmd_login))

    dp.add_handler(CallbackQueryHandler(menu_callback, pattern=r'^menu_'))
    dp.add_handler(CallbackQueryHandler(groups_callback, pattern=r'^(tog_|grp_|noop)'))
    dp.add_handler(CallbackQueryHandler(settings_callback, pattern=r'^set_'))

    dp.add_handler(MessageHandler(Filters.text & ~Filters.command, text_router))

    session_manager.resume_all()
    start_cleanup_loop()

    logger.info("๐Ÿค– Bot starting in background thread...")
    updater.start_polling()
    logger.info("โœ… Bot polling started.")

    while True:
        threading.Event().wait(3600)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Gradio UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def gradio_status():
    """ุนุฑุถ ุญุงู„ุฉ ุงู„ุจูˆุช ุนู„ู‰ ุตูุญุฉ Gradio."""
    try:
        active_users = len(db_all_active_users())
        clients = len(session_manager.clients)
        schedules = len(session_manager.schedule_tasks)
        return (
            f"๐Ÿค– ุงู„ุจูˆุช ูŠุนู…ู„ ุจู†ุฌุงุญ!\n"
            f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
            f"๐Ÿ‘ฅ ุงู„ู…ุณุชุฎุฏู…ูˆู† ุงู„ู†ุดุทูˆู†: {active_users}\n"
            f"๐Ÿ”Œ ุนู…ู„ุงุก Telethon ุงู„ู…ุชุตู„ูˆู†: {clients}\n"
            f"โฑ๏ธ ุงู„ุฌุฏุงูˆู„ ุงู„ู†ุดุทุฉ: {schedules}\n"
            f"โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"
            f"ุงูุชุญ ุงู„ุจูˆุช ุนู„ู‰ ุชูŠู„ูŠุฌุฑุงู… ูˆุฃุฑุณู„ /start ู„ู„ุจุฏุก."
        )
    except Exception as e:
        return f"โš ๏ธ ุญุงู„ุฉ ุบูŠุฑ ู…ุนุฑูˆูุฉ: {e}"


def build_gradio_ui():
    with gr.Blocks(title="Telegram Auto Sender Bot", theme=gr.themes.Soft()) as demo:
        gr.Markdown(
            """
            # ๐Ÿค– Telegram Auto Sender Bot
            ### ุงู„ุจูˆุช ูŠุนู…ู„ ููŠ ุงู„ุฎู„ููŠุฉ ุนู„ู‰ ู‡ุฐุง ุงู„ู€ Space
            ู‡ุฐู‡ ุงู„ุตูุญุฉ ูู‚ุท ู„ู„ุชุฃูƒุฏ ู…ู† ุฃู† ุงู„ู€ Space ู†ุดุท. **ู„ุง ุชุบู„ู‚** ู‡ุฐู‡ ุงู„ุตูุญุฉ.
            ุงูุชุญ ุงู„ุจูˆุช ุนู„ู‰ ุชูŠู„ูŠุฌุฑุงู… ูˆุฃุฑุณู„ `/start` ู„ู„ุจุฏุก.
            """
        )
        with gr.Row():
            status_btn = gr.Button("๐Ÿ”„ ุชุญุฏูŠุซ ุงู„ุญุงู„ุฉ", variant="primary")
        status_out = gr.Textbox(label="ุญุงู„ุฉ ุงู„ุจูˆุช", lines=8, interactive=False)
        status_btn.click(fn=gradio_status, inputs=[], outputs=status_out)
        demo.load(fn=gradio_status, inputs=[], outputs=status_out)
        gr.Markdown(
            """
            ---
            ### ๐Ÿ“‹ ุฎุทูˆุงุช ุงู„ุงุณุชุฎุฏุงู…
            1. ุงูุชุญ ุงู„ุจูˆุช ุนู„ู‰ ุชูŠู„ูŠุฌุฑุงู… ูˆุฃุฑุณู„ `/start`
            2. ุงุถุบุท **๐Ÿ” ุชุณุฌูŠู„ ุงู„ุฏุฎูˆู„** ูˆุฃุฑุณู„ ูƒูˆุฏ ุงู„ุฌู„ุณุฉ (StringSession)
            3. ุงุฎุชุฑ ุงู„ู…ุฌู…ูˆุนุงุช ู…ู† **๐Ÿ‘ฅ ุงุฎุชูŠุงุฑ ุงู„ู…ุฌู…ูˆุนุงุช**
            4. ุนุฏู‘ู„ ุงู„ุฑุณุงู„ุฉ ูˆุงู„ูุงุตู„ ู…ู† **โš™๏ธ ุงู„ุฅุนุฏุงุฏุงุช**
            5. ุงุจุฏุฃ ุงู„ุฅุฑุณุงู„ ุงู„ุฏูˆุฑูŠ ุจู€ **โ–ถ๏ธ ุจุฏุก ุงู„ุฅุฑุณุงู„ ุงู„ุฏูˆุฑูŠ**
            6. ู„ู„ุฅุฑุณุงู„ ุงู„ููˆุฑูŠ ุงุถุบุท **๐Ÿš€ ุฅุฑุณุงู„ ุงู„ุขู†**
            """
        )
    return demo


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Main โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
if __name__ == "__main__":
    bot_thread = threading.Thread(target=run_bot_in_background, daemon=True, name="bot-thread")
    bot_thread.start()

    logger.info("๐ŸŒ Starting Gradio interface on 0.0.0.0:7860")
    demo = build_gradio_ui()
    demo.queue().launch(
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True,
        quiet=False
    )