File size: 36,670 Bytes
21bc372
 
43eea36
21bc372
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
a36887a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbbca4c
a36887a
 
 
 
 
 
bbbca4c
a36887a
 
 
 
 
bbbca4c
a36887a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28eac2f
a36887a
 
 
afee755
 
a36887a
5abbacd
 
 
a36887a
 
 
 
 
 
43eea36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d021610
 
43eea36
 
 
8a3fa89
 
43eea36
 
d021610
43eea36
 
 
 
 
 
 
 
 
 
 
 
a36887a
 
 
 
 
43eea36
 
 
 
a36887a
 
 
 
 
 
 
 
 
 
43eea36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbbca4c
 
9fee460
bbbca4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5abbacd
 
9fee460
 
 
 
 
 
bbbca4c
 
5abbacd
 
 
 
 
 
 
 
 
3181c05
5abbacd
 
 
 
 
 
 
 
 
 
bbbca4c
 
 
 
 
 
 
 
5abbacd
bbbca4c
 
 
 
 
 
 
 
 
5abbacd
bbbca4c
 
 
 
 
 
 
 
 
 
 
 
 
 
5abbacd
 
 
bbbca4c
 
 
 
 
 
43eea36
bbbca4c
 
5abbacd
21bc372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
d437744
21bc372
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
465767b
21bc372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
465767b
 
21bc372
 
 
 
465767b
 
 
21bc372
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
465767b
21bc372
465767b
 
 
 
 
21bc372
465767b
 
 
21bc372
 
 
 
 
465767b
21bc372
 
 
465767b
21bc372
465767b
21bc372
 
9b0297e
465767b
 
 
9b0297e
465767b
 
 
 
 
 
 
 
 
21bc372
 
 
 
465767b
21bc372
465767b
 
21bc372
 
 
 
465767b
ef21dc3
 
21bc372
ef21dc3
21bc372
 
465767b
ef21dc3
 
 
 
21bc372
0a2bc0c
21bc372
 
 
 
 
465767b
 
21bc372
 
465767b
21bc372
465767b
21bc372
 
465767b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21bc372
 
465767b
21bc372
 
 
 
465767b
 
 
21bc372
 
 
 
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
 
465767b
 
21bc372
 
 
 
 
 
 
 
 
465767b
21bc372
465767b
21bc372
 
 
465767b
21bc372
 
 
 
465767b
 
 
 
21bc372
 
 
 
 
 
 
 
 
 
465767b
21bc372
 
 
 
 
 
 
 
 
 
465767b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef21dc3
 
465767b
 
 
 
 
 
 
 
 
 
 
 
21bc372
465767b
21bc372
 
bbbca4c
 
 
 
 
 
 
 
 
 
 
 
ef21dc3
465767b
 
 
 
 
 
ef21dc3
 
 
465767b
 
 
 
21bc372
465767b
21bc372
465767b
21bc372
 
a36887a
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
# -*- coding: utf-8 -*-
import time
import os
import uuid
import asyncio
import pyromod
from pyromod.helpers import ikb
from datetime import datetime as dt
from pyrogram import *
from pyrogram import Client as ren, filters
from pyrogram.types import *

from akn.utils.database import db as db_client
from akn.manage.settings_control import verify_bot_ownershipdl
from akn.utils.logger import LOGS
from config import PRIVATE_LOGS

@Client.on_callback_query(filters.regex("^my_userbotub$"))
async def userbotdashboardub(client: Client, callback: CallbackQuery):
    user_id = callback.from_user.id
    
    user_data = await db_client.session.find_one({"user_id": user_id})
    if not user_data or "user_client" not in user_data:
        return await callback.answer("❌ No userbot found!", show_alert=True)

    bot_data = user_data["user_client"][0]
    status = bot_data.get("status", "pending")

    status_icons = {
        "approved": "βœ…",
        "rejected": "❌", 
        "pending": "⏳",
        "stopped": "πŸ›‘",
        "error": "⚠️"
    }
    start = time.time()
    await client.get_me()
    end = time.time()
    latency = (end - start) * 1000

    text = f"""
πŸ”§ **Your Userbot Dashboard**

πŸ†” **User ID:** `{user_id}`
πŸ“› **Status:** {status_icons.get(status, "οΏ½")} {status.capitalize()}
⏰ **Last Active:** {bot_data.get("timestamp", "Never")}
βœ” **Pong:** `{latency:.2f} ms`
πŸ”— **Session:** {'Set' if bot_data.get("session_string") else 'Not Set'}
"""

    buttons = []
    if not bot_data.get("session_string"):
        buttons.append(
            [InlineKeyboardButton("βž• Set Session String", callback_data="set_sessionub")]
        )
    else:
        buttons.append(
            [InlineKeyboardButton("πŸ”„ Update Session", callback_data="update_sessionub")]
        )

    if status == "approved":
        buttons.extend([
            [InlineKeyboardButton("❔ Check Status", callback_data=f"statusub_{user_id}")]
        ])
    
    buttons.append(
        [InlineKeyboardButton("πŸ”„ Refresh", callback_data="my_userbotub"),
         InlineKeyboardButton("βš™οΈ Settings", callback_data="ubsetting")]
    )
    buttons.append(
        [InlineKeyboardButton("πŸ”™ Back", callback_data="confirm_userbot")]
    )
    await callback.message.edit_text(
        text,
        reply_markup=InlineKeyboardMarkup(buttons)
    )
    await callback.answer()

@Client.on_callback_query(filters.regex("^session_exportuball$"))
async def export_all_sessionsub(client, callback):
    user_data = await db_client.session.find_one({"user_id": callback.from_user.id})
    if not user_data or not user_data.get("user_client"):
        return await callback.answer("⚠️ No sessions to export!", show_alert=True)

    sessions = user_data["user_client"]
    export_text = ""
    for index, session in enumerate(sessions, 1):
        status = session.get("status", "unknown")
        is_active = session.get("is_active", False)
        session_str = session.get("session_string", "None")
        export_text += (
            f"Userbot #{index}\n"
            f"Status: {status}\n"
            f"Active: {is_active}\n"
            f"Session: {session_str}\n\n"
        )
    filename = f"sessions_{callback.from_user.id}.txt"
    with open(filename, "w") as f:
        f.write(export_text)

    try:
        await callback.message.edit_text("Downloading export all session.....", reply_markup=None)
        await asyncio.sleep(2)
        await callback.message.edit_text("Uploading.....", reply_markup=None)
        await callback.message.edit_media(
            media=InputMediaDocument(
                media=filename,
                caption="πŸ“ Your session details.\n\n"
                        "<b>Never share your session string with anyone</b>"
            ),
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("❌ Close", callback_data="close")]
            ])
        )
        os.remove(filename) 
        await callback.answer()
    except Exception as e:
        LOGS.error(f"Error in export_all_sessionsub handler: {str(e)}")
        await callback.answer(f"❌ Error: Please try again later.", True)
        try:
            os.remove(filename)
        except:
            pass

@Client.on_callback_query(filters.regex("^ubsetting$"))
async def userbotsettingsub(client: Client, callback: CallbackQuery):
    user_id = callback.from_user.id
    
    buttons = [
        [InlineKeyboardButton("πŸ“ Session Info", callback_data="session_infoub"),
         InlineKeyboardButton("πŸ—‘ Delete Userbot", callback_data="delete_userbotub")
        ],
        [InlineKeyboardButton("πŸ“₯ Export All Sessions", callback_data="session_exportuball")],
        [InlineKeyboardButton("πŸ”™ Back", callback_data="my_userbotub")]
    ]

    await callback.message.edit_text(
        "βš™οΈ **Userbot Settings**\n\n"
        "Manage your userbot configuration:",
        reply_markup=InlineKeyboardMarkup(buttons)
    )
    await callback.answer()

@Client.on_callback_query(filters.regex("^delete_userbotub$"))
async def sessionconfirmdeleteub(client, callback):
    await callback.message.edit_text(
        "⚠️ This will permanently delete your userbot!",
        reply_markup=InlineKeyboardMarkup([
            [InlineKeyboardButton("βœ… Confirm", "confirm_rmdeleteub")],
            [InlineKeyboardButton("❌ Cancel", "my_userbotub")]
        ])
    )

@Client.on_callback_query(filters.regex("^confirm_rmdeleteub$"))
async def sessionrmdeleteubnow(client, callback):
    user_mention = callback.from_user.mention
    user_data = await db_client.session.find_one({"user_id": callback.from_user.id})
    if not user_data or not user_data.get("user_client"):
        return await callback.answer(
            "❌ You don't have any Userbot deployed yet!",
            show_alert=True
        )
    try:
        result = await db_client.session.update_one(
            {
                "_id": user_data["_id"],
                "user_id": callback.from_user.id,
                "user_client.user_id": callback.from_user.id
            },
            {"$pull": {"user_client": {"user_id": callback.from_user.id}}}
        )
        if result.modified_count == 1:
            await callback.message.edit_text(
                f"βœ… User `{callback.from_user.id}` has been permanently removed",
                reply_markup=InlineKeyboardMarkup([
                    [InlineKeyboardButton("⭐ My Userbot", callback_data="my_userbotub")]
                ])
            )
            await notify_admins_user(
                client=client,
                message=f"πŸ›‘ <b>Deleted Userbot</b>\n\n"
                        f"πŸ‘€ User: {user_mention} ({callback.from_user.id})\n",
                user_id=callback.from_user.id,
                is_button=False
            )
        else:
            raise Exception("Database update failed")
    except Exception as e:
        LOGS.error(f"Error in sessionrmdeleteubnow handler: {str(e)}")
        await callback.answer(f"❌ Error: Please try again later.", True)
        await notify_admins_user(
            client=client,
            message=f"🚨 <b>Error in sessionrmdeleteubnow handler</b>\n\n"
                    f"πŸ‘€ User: {user_mention} ({callback.from_user.id})\n"
                    f"🧠 Error: <code>{str(e)}</code>",
            user_id=callback.from_user.id,
            is_button=False
        )

@Client.on_callback_query(filters.regex("^session_infoub$"))
async def infosessionstringub(client: Client, callback: CallbackQuery):
    user_data = await db_client.session.find_one({"user_id": callback.from_user.id})
    if not user_data or not user_data.get("user_client"):
        return await callback.answer(
            "❌ You don't have any Userbot deployed yet!",
            show_alert=True
        )
    user = user_data["user_client"][0]
    await callback.message.edit_text(
        "πŸ”’ <b>Session String Secure</b>\n\n"
        f"Copy: `{user.get('session_string', 'Nothing')}`\n\n"
        "Important: <b>Never share your session string with anyone</b>",
        reply_markup=ikb([
            [("Β« Back", "ubsetting")]
        ])
    )
    await callback.answer()

@Client.on_callback_query(filters.regex("^(set_sessionub|update_sessionub)$"))
async def asksessionstringub(client: Client, callback: CallbackQuery):
    user_data = await db_client.session.find_one({"user_id": callback.from_user.id})
    if not user_data or not user_data.get("user_client"):
        return await callback.answer(
            "❌ You don't have any Userbot deployed yet!",
            show_alert=True
        )
    _user_string = user_data.get("user_client")[0]
    user_mention = callback.from_user.mention
    await callback.message.edit_text(
        "πŸ”‘ **Session String Setup: @sessiondevbot**\n\n"
        "Please send your session string in this format:\n\n"
        "`ABCDEF1234ghIklzyx57W2v1u123ew11*********`\n\n"
        "⚠️ This will replace your current session!\n\n"
        "Cancelled use /cancel",
        reply_markup=None
    )
    try:
        string_msg = await client.listen(callback.message.chat.id, timeout=60)
        if string_msg.text.lower() == "/cancel":
            await string_msg.reply(
                "❌ Cancelled.",
                reply_markup=ikb([
                    [("Β« Back", "my_userbotub")]
                ])
            )
            return

        string_update = string_msg.text.strip()
        if string_update == _user_string.get("session_string"):
            return await string_msg.reply(
                "❌ Error Session string same use different!",
                reply_markup=ikb([
                    [("Β« Back", "my_userbotub")]

                ])
            )
        await db_client.session.update_one(
            {
                "user_id": callback.from_user.id,
                "user_client.user_id": callback.from_user.id
            },
            {
                "$set": {
                    "user_client.$.session_string": string_update
                }
            }
        )
        await string_msg.reply(
            "βœ… Session string updated successfully!",
            reply_markup=ikb([
                [("Β« Back", "my_userbotub")]
            ])
        )
        await notify_admins_user(
            client=client,
            message=f"πŸ’¬ <b>Update Session</b>\n\n"
                    f"πŸ‘€ User: {user_mention} ({callback.from_user.id})",
            user_id=user_id,
            is_button=True
        )
        return
    except TimeoutError:
        await callback.message.reply_text("βŒ› Session setup timed out")
    except Exception as e:
        await callback.message.reply_text(f"❌ Error: Please try again later.")
        await notify_admins_user(
            client=client,
            message=f"🚨 <b>Error in asksessionstringub handler</b>\n\n"
                    f"πŸ‘€ User: {user_mention} ({callback.from_user.id})\n"
                    f"🧠 Error: <code>{str(e)}</code>",
            user_id=callback.from_user.id,
            is_button=False
        )

@ren.on_callback_query(filters.regex("^my_bots$"))
async def show_user_bots(client: Client, callback: CallbackQuery):
    user_id = callback.from_user.id
    user_mention = callback.from_user.mention

    try:
        user_data = await db_client.alldl_bot.find_one({"user_id": user_id})
        if not user_data or not user_data.get("bots"):
            return await callback.answer(
                "❌ You don't have any bots deployed yet!",
                show_alert=True
            )

        bots_by_status = {
            "approved": [],
            "pending": [],
            "rejected": [],
            "error": []
        }
        for bot in user_data["bots"]:
            status = bot.get("status", "pending")
            bots_by_status.setdefault(status, []).append(bot)

        start = time.time()
        await client.get_me()
        end = time.time()
        latency = (end - start) * 1000
        message_text = f"πŸ€– <b>Your Bot Dashboard</b> πŸ‘‹ {user_mention}\n\n"
        message_text += f"🏷 <b>Tier:</b> {'πŸ’Ž Premium' if user_data.get('is_premium') else 'πŸ†“ Free'}\n"
        message_text += f"πŸš€ <b>Active Bots:</b> {sum(1 for b in bots_by_status['approved'] if b.get('is_active'))}\n"
        message_text += f"⏳ <b>Pending:</b> {len(bots_by_status['pending'])}\n"
        message_text += f"❌ <b>Rejected:</b> {len(bots_by_status['rejected'])}\n"
        message_text += f"βœ” <b>Pong:</b> `{latency:.2f} ms`\n\n"

        buttons = []

        if bots_by_status["approved"]:
            message_text += "βœ… <b>Approved Bots:</b>\n"
            for bot in bots_by_status["approved"]:
                bot_name = bot.get("bot_username", "Unknown")
                status = "🟒 Online" if bot.get("is_active") else "πŸ”΄ Offline"
                message_text += f"┣ {bot_name} - {status} - `{latency:.2f}`\n"

                buttons.append([
                    InlineKeyboardButton(
                        f"βš™οΈ Manage {bot_name}",
                        callback_data=f"botmgmt_{bot.get('uuid', 'unknown')}"
                    )
                ])

        if bots_by_status["pending"]:
            message_text += "\nπŸ•’ <b>Pending Approval:</b>\n"
            for bot in bots_by_status["pending"]:
                token_preview = bot.get("bot_token", "")[:10] + "..."
                submitted_time = bot.get("timestamp", "Unknown")
                message_text += f"┣ {token_preview} - {submitted_time}\n"

                buttons.append([
                    InlineKeyboardButton(
                        f"❌ Cancel {token_preview}",
                        callback_data=f"cancelbotdl_{bot.get('uuid', 'unknown')}"
                    )
                ])

        if bots_by_status["rejected"]:
            message_text += "\n❌ <b>Rejected Bots:</b>\n"
            for bot in bots_by_status["rejected"]:
                token_preview = bot.get("bot_token", "")[:10] + "..."
                reason = bot.get("admin_action", {}).get("reason", "No reason given")
                message_text += f"┣ {token_preview} - {reason}\n"

                buttons.append([
                    InlineKeyboardButton(
                        f"πŸ” Resubmit {token_preview}",
                        callback_data=f"resubmitdl_{bot.get('uuid', 'unknown')}"
                    )
                ])

        buttons.append([
            InlineKeyboardButton("πŸ†• Deploy New Bot", callback_data="tutorial_alldlbot"),
            InlineKeyboardButton("πŸ’Ž Upgrade Plan", callback_data="premium_upgrades")
        ])
        buttons.append([
            InlineKeyboardButton("πŸ”„ Refresh", callback_data="my_bots"),
            InlineKeyboardButton("❌ Close", callback_data="close")
        ])
        buttons.append([
            InlineKeyboardButton("Β« Back", callback_data="customzie_bot"),
        ])

        try:
            await callback.message.edit_text(
                message_text,
                reply_markup=InlineKeyboardMarkup(buttons)
            )
        except Exception as e:
            LOGS.error(f"Edit message failed: {e}")
            await callback.answer("⚠️ Failed to update message, try again.", show_alert=True)

        await callback.answer()

    except Exception as e:
        LOGS.error(f"Error in my_bots handler: {str(e)}")
        await callback.answer("⚠️ Error fetching your bots!", show_alert=True)
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in my_bots handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex(r"^botmgmt_(\w+)$"))
async def manage_single_bot(client: Client, callback: CallbackQuery):
    bot_uuid = callback.matches[0].group(1)
    user_id = callback.from_user.id
    user_mention = callback.from_user.mention

    try:
        user_data = await db_client.alldl_bot.find_one(
            {
                "user_id": user_id,
                "bots.uuid": bot_uuid
            },
            {"bots.$": 1}
        )

        if not user_data or not user_data.get("bots"):
            return await callback.answer("❌ Bot not found!", show_alert=True)

        bot = user_data["bots"][0]
        bot_username = bot.get("bot_username", "Unknown")
        bot_uuid = bot.get("uuid", "???")

        status = "🟒 Online" if bot.get("is_active") else "πŸ”΄ Offline"
        last_active = bot.get("last_active", "Never")

        buttons = [
            [
                InlineKeyboardButton("πŸ”„ Restart Bot", callback_data=f"restartdl_{bot_uuid}"),
                InlineKeyboardButton("πŸ›‘ Stop Bot", callback_data=f"stopbotdl_{bot_uuid}")
            ],
            [
                InlineKeyboardButton("πŸ“Š Stats", callback_data=f"botstatsdl_{bot_uuid}"),
                InlineKeyboardButton("βš™οΈ Settings", callback_data=f"botsettingsdl_{bot_uuid}")
            ],
            [InlineKeyboardButton("Β« Back", callback_data="my_bots")]
        ]

        await callback.message.edit_text(
            f"βš™οΈ <b>Managing {bot_username}</b>\n\n"
            f"Status: {status}\n"
            f"Last Active: {last_active}\n"
            f"UUID: <code>{bot_uuid}</code>\n\n"
            "Choose an action below:",
            reply_markup=InlineKeyboardMarkup(buttons)
        )
        await callback.answer()

    except Exception as e:
        LOGS.error(f"Bot management error: {str(e)}")
        await callback.answer("❌ Error managing bot!", show_alert=True)
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in single manage handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex(r"^botsettingsdl_(\w+)$"))
async def handle_bot_settingsdl(client: Client, callback: CallbackQuery):
    try:
        bots_uuid = callback.matches[0].group(1)
        user_id = callback.from_user.id
        user_mention = callback.from_user.mention

        if not await verify_bot_ownershipdl(user_id, bots_uuid):
            await callback.answer("❌ Unauthorized access!", show_alert=True)
            return

        bot_data = await db_client.alldl_bot.find_one(
            {"user_id": user_id, "bots.uuid": bots_uuid},
            {"bots.$": 1}
        )

        if not bot_data:
            return await callback.answer("❌ Bot not found!", show_alert=True)

        buttons = InlineKeyboardMarkup([
            [InlineKeyboardButton("πŸ” Reset Token", callback_data=f"start_reset_tokendl")],
            [InlineKeyboardButton("πŸ—‘ Delete Bot", callback_data=f"deletebotdl_{bots_uuid}")],
            [InlineKeyboardButton("Β« Back to bot", callback_data="my_bots")]
        ])

        await callback.message.edit_text(
            f"βš™οΈ Bot Settings\n\n"
            f"πŸ†” UUID: `{bots_uuid}`\n"
            f"πŸ”— Username: {bot_data['bots'][0].get('bot_username', 'N/A')}\n"
            f"πŸ“… Created: {bot_data['bots'][0].get('created_at', 'Unknown')}",
            reply_markup=buttons
        )
        await callback.answer()

    except Exception as e:
        LOGS.error(f"Settings error: {str(e)}")
        await callback.answer("⚠️ Error loading settings!", show_alert=True)
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in settingdl handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex("start_reset_tokendl"))
async def reset_tokendl_callbackx(client, callback_query):
    user_id = callback_query.from_user.id
    bot_data = await db_client.alldl_bot.find_one({"user_id": user_id})
    if not bot_data:
        await callback_query.answer("❌ Bot not found!", show_alert=True)
        return
    old_uuid = bot_data["bots"][0].get("uuid")
    await callback_query.message.edit_text(
        "✏️ Please send the UUID of the bot you want to reset.\n\nYou can cancel by typing `/cancel`\n\nYou can't this button is disabled.",
        reply_markup=ikb([
            [("πŸ”’ Locked Cancel", "noop")]
        ])
    )
    try:
        uuid_msg = await client.listen(callback_query.message.chat.id, timeout=60)
        if uuid_msg.text.lower() == "/cancel":
            await uuid_msg.reply(
                "❌ Cancelled.",
                reply_markup=ikb([
                    [("Β« Back", "customzie_bot")]
                ])
            )
            return

        bots_uuid = uuid_msg.text.strip()
        if bots_uuid != old_uuid:
            await uuid_msg.reply(
                "❌ Token reset cancelled.",
                reply_markup=ikb([
                    [("Β« Back", "customzie_bot")]
                ])
            )
            return
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("βœ… Yes", callback_data=f"resettokendl_{bots_uuid}"),
                InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_resetdl_{bots_uuid}")
            ]
        ])
        await uuid_msg.reply(
            f"Are you sure you want to reset the token for:\n`{bots_uuid}`",
            reply_markup=keyboard
        )
    except asyncio.TimeoutError:
        await callback_query.message.reply("⏰ Timeout. Please try again.")

@ren.on_callback_query(filters.regex(r"^(resettokendl|cancel_resetdl)_(\w+)$"))
async def tokenx_reset_flowdl(client: Client, callback: CallbackQuery):
    action, bot_uuid = callback.matches[0].groups()
    user_id = callback.from_user.id
    user_mention = callback.from_user.mention

    bot_data = await db_client.alldl_bot.find_one(
        {
            "user_id": user_id,
            "bots.uuid": bot_uuid
        },
        {"bots.$": 1}
    )

    if not bot_data:
        await callback.answer("❌ Bot not found!", show_alert=True)
        return

    if action == "cancel_resetdl":
        await callback.answer("Token reset cancelled ❌", show_alert=False)
        await callback.message.edit_text(
            "❌ Token reset cancelled.",
            reply_markup=ikb([
                [("Β« Back", "customzie_bot")]
            ])
        )
        return

    try:
        current_token = bot_data["bots"][0]["uuid"]
        new_token = str(uuid.uuid4())[:8]
        await db_client.alldl_bot.update_one(
            {
                "user_id": user_id,
                "bots.uuid": bot_uuid
            },
            {
                "$set": {
                    "bots.$.uuid": new_token,
                    "bots.$.updated_at": dt.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
                "$push": {
                    "bots.$.old_tokens": {
                        "token": current_token,
                        "reset_at": dt.now().strftime("%Y-%m-%d %H:%M:%S")
                    }
                }
            }
        )
        await callback.message.edit_text(
            f"βœ… Token has been reset successfully!\n\n`{new_token}`",
            reply_markup=None
        )
        await callback.answer("New token generated βœ…", show_alert=False)

    except Exception as e:
        LOGS.error(f"Token reset error: {str(e)}")
        await callback.answer("❌ Failed to reset token. Please try again later.", True)
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in tokenx reset handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex("^noop$"))
async def noopx_callback(client, callback_query):
    await callback_query.answer("πŸ”’ This button is disabled.", show_alert=False)

@ren.on_callback_query(filters.regex(r"^deletebotdl_(\w+)$"))
async def handle_delete_botdl(client: Client, callback: CallbackQuery):
    try:
        bots_uuid = callback.matches[0].group(1)
        user_id = callback.from_user.id
        user_mention = callback.from_user.mention
        if not await verify_bot_ownershipdl(user_id, bots_uuid):
            await callback.answer("❌ Unauthorized access!", show_alert=True)
            return

        bot_data = await db_client.alldl_bot.find_one(
            {
                "user_id": user_id,
                "bots.uuid": bots_uuid,
            },
            {"bots.$": 1}
        )

        if not bot_data:
            await callback.answer("❌ Bot not found!", show_alert=True)
            return

        await callback.message.edit_text(
            f"⚠️ **Permanent Deletion**\n\n"
            f"πŸ†” UUID: `{bots_uuid}`\n"
            f"πŸ”— Username: {bot_data['bots'][0].get('bot_username', 'N/A')}\n\n"
            "This will immediately:\n"
            "1. Stop the bot instance\n"
            "2. Remove all download history\n"
            "3. Delete configuration data",
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("☠️ Confirm Delete", callback_data=f"confirmdeletedl_{bots_uuid}")],
                [InlineKeyboardButton("πŸ”’ Cancel", callback_data=f"nodeletedl_{bots_uuid}")],
                [InlineKeyboardButton("Β« Back", callback_data="my_bots")]
            ])
        )
        await callback.answer()

    except Exception as e:
        LOGS.error(f"Delete init error: {str(e)}")
        await callback.answer("⚠️ Error processing request", show_alert=True)
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in delete_botdl handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex(r"^(confirmdeletedl|nodeletedl)_(\w+)$"))
async def delete_confirmationdl(client: Client, callback: CallbackQuery):
    action, bots_uuid = callback.matches[0].groups()
    
    if action == "nodeletedl":
        await callback.message.edit_text(
            "βœ… Deletion cancelled",
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("Β« Back", callback_data="my_bots")]
            ])
        )
        await callback.answer()
        return

    try:
        user_id = callback.from_user.id
        user_mention = callback.from_user.mention


        result = await db_client.alldl_bot.update_one(
            {"user_id": user_id},
            {"$pull": {"bots": {"uuid": bots_uuid}}}
        )

        if result.modified_count == 1:
            await callback.message.edit_text(
                "πŸ—‘οΈ **Bot Deleted**\n\n"
                f"All data for `{bots_uuid}` has been removed\n"
                f"Average review time: 24-48 hours",
                reply_markup=InlineKeyboardMarkup([
                    [InlineKeyboardButton("Β« Back", callback_data="customzie_bot")],
                ])
            )
            await notify_admins(
                client=client,
                message=f"πŸ—‘οΈ <b>Bot Deleted</b>\n\n"
                        f"User: {user_mention}\n"
                        f"UUID: {bots_uuid}\n",
                user_id=user_id,
                bots_uuid=bots_uuid
            )
        else:
            raise Exception("Database update failed")

    except Exception as e:
        LOGS.error(f"Deletion error: {str(e)}")
        await callback.message.edit_text("❌ Deletion failed. Please contact support.")
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error indelete_confirmationdl handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex(r"^resubmitdl_(\w+)$"))
async def xresubmission(client: Client, callback: CallbackQuery):
    try:
        bots_uuid = callback.matches[0].group(1)
        user_id = callback.from_user.id
        user_mention = callback.from_user.mention
        if not await verify_bot_ownershipdl(user_id, bots_uuid):
            await callback.answer("❌ Unauthorized access!", show_alert=True)
            return

        bot_data = await db_client.alldl_bot.find_one(
            {
                "user_id": user_id,
                "bots.uuid": bots_uuid,
                "bots.status": "rejected"
            },
            {"bots.$": 1}
        )

        if not bot_data:
            await callback.answer("❌ Bot not found or not eligible for resubmission", show_alert=True)
            return

        bot = bot_data["bots"][0]
        rejection_reason = bot.get("admin_action", {}).get("reason", "No reason provided")


        await callback.message.edit_text(
            f"πŸ”„ **Resubmit Bot Request**\n\n"
            f"πŸ†” UUID: `{bots_uuid}`\n"
            f"❌ Previous Rejection Reason: {rejection_reason}\n\n"
            "Please confirm you want to resubmit this bot for approval:",
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("βœ… Confirm Resubmit", callback_data=f"confirm_resubmitdl_{bots_uuid}")],
                [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_resubmitdl_")],
                [InlineKeyboardButton("Β« Back", callback_data="my_bots")]
            ])
        )
        await callback.answer()

    except Exception as e:
        LOGS.error(f"Resubmission init error: {str(e)}")
        await callback.answer("⚠️ Error processing request", show_alert=True)
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in xresubmission handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex(r"^cancelbotdl_(\w+)$"))
async def handle_cancel_bot(client: Client, callback: CallbackQuery):
    try:
        bots_uuid = callback.matches[0].group(1)
        user_id = callback.from_user.id
        user_mention = callback.from_user.mention
        if not await verify_bot_ownershipdl(user_id, bots_uuid):
            await callback.answer("❌ Unauthorized access!", show_alert=True)
            return

        bot_data = await db_client.alldl_bot.find_one(
            {
                "user_id": user_id,
                "bots.uuid": bots_uuid,
                "bots.status": "pending"
            },
            {"bots.$": 1}
        )

        if not bot_data:
            await callback.answer("❌ No pending bot found with this ID", show_alert=True)
            return
    
        await callback.message.edit_text(
            f"⚠️ **Confirm Cancellation**\n\n"
            f"UUID: `{bots_uuid}`\n"
            f"Submitted: {bot_data['bots'][0].get('timestamp', 'Unknown')}\n\n"
            "This will permanently remove the bot request:",
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("πŸ—‘ Confirm Delete", callback_data=f"confirmcanceldl_{bots_uuid}")],
                [InlineKeyboardButton("πŸ”™ Keep Request", callback_data=f"keepbotdl_{user_id}")],
                [InlineKeyboardButton("Β« Back", callback_data="my_bots")]
            ])
        )
        await callback.answer()

    except Exception as e:
        LOGS.error(f"Cancel init error: {str(e)}")
        await callback.answer("⚠️ Error processing request", show_alert=True)
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in cancel_bot handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex(r"^confirmcanceldl_(\w+)$"))
async def confirm_cancel_bot(client: Client, callback: CallbackQuery):
    try:
        bots_uuid = callback.matches[0].group(1)
        user_id = callback.from_user.id
        user_mention = callback.from_user.mention
        if not await verify_bot_ownershipdl(user_id, bots_uuid):
            await callback.answer("❌ Unauthorized access!", show_alert=True)
            return

        result = await db_client.alldl_bot.update_one(
            {"user_id": user_id},
            {"$pull": {"bots": {"uuid": bots_uuid}}}
        )

        if result.modified_count == 1:
            await callback.message.edit_text(
                "βœ… **Request Cancelled**\n\n"
                f"Bot `{bots_uuid}` has been permanently removed",
                reply_markup=InlineKeyboardMarkup([
                    [InlineKeyboardButton("πŸ“‹ My Bots", callback_data="my_bots")]
                ])
            )
        else:
            raise Exception("Database update failed")

    except Exception as e:
        LOGS.error(f"Cancel error: {str(e)}")
        await callback.message.edit_text("❌ Failed to cancel request. Please contact support.")
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in confirm cancel handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

@ren.on_callback_query(filters.regex(r"^confirm_resubmitdl_(\w+)$"))
async def confirm_resubmission(client: Client, callback: CallbackQuery):
    try:
        bots_uuid = callback.matches[0].group(1)
        user_id = callback.from_user.id
        user_mention = callback.from_user.mention
        if not await verify_bot_ownershipdl(user_id, bots_uuid):
            await callback.answer("❌ Unauthorized access!", show_alert=True)
            return

        result = await db_client.alldl_bot.update_one(
            {
                "user_id": user_id,
                "bots.uuid": bots_uuid
            },
            {
                "$set": {
                    "bots.$.status": "pending",
                    "bots.$.resubmitted_at": dt.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "bots.$.admin_action.reviewed": False
                }
            }
        )

        if result.modified_count == 1:
            await callback.message.edit_text(
                f"βœ… **Resubmission Successful**\n\n"
                f"Bot `{bots_uuid}` has been queued for admin review.\n"
                f"Average review time: 24-48 hours",
                reply_markup=InlineKeyboardMarkup([
                    [InlineKeyboardButton("πŸ“Š View Status", callback_data=f"statusdl_{user_id}")]
                ])
            )
            await notify_admins(
                client=client,
                message=f"Bot resubmitted: {bots_uuid} by {callback.from_user.mention}",
                user_id=user_id,
                bots_uuid=bots_uuid
            )
        else:
            raise Exception("Database update failed")

    except Exception as e:
        LOGS.error(f"Resubmission error: {str(e)}")
        await callback.message.edit_text("❌ Failed to resubmit. Please try again later.")
        await client.send_message(
            PRIVATE_LOGS,
            f"🚨 <b>Error in confirm_resubmission handler</b>\n\n"
            f"πŸ‘€ User: {user_mention} ({user_id})\n"
            f"🧠 Error: <code>{str(e)}</code>"
        )

async def notify_admins_user(client, message, user_id, is_button=False):
     admin_buttons = InlineKeyboardMarkup([
        [InlineKeyboardButton("βœ… Approve", callback_data=f"approved_ub_{user_id}"),
         InlineKeyboardButton("❌ Reject",  callback_data=f"rejected_ub_{user_id}")],
        [InlineKeyboardButton("πŸ‘€ View User", url=f"tg://user?id={user_id}")]
    ])
     return await client.send_message(
         PRIVATE_LOGS,
         text=message,
         reply_markup=admin_buttons if is_button else None
    )

async def notify_admins(client, message, user_id, bots_uuid):
     admin_buttons = InlineKeyboardMarkup([
        [InlineKeyboardButton("βœ… Approve", callback_data=f"approved_alldl_{user_id}_{bots_uuid}"),
         InlineKeyboardButton("❌ Reject",  callback_data=f"rejected_alldl_{user_id}_{bots_uuid}")],
        [InlineKeyboardButton("πŸ‘€ View User", url=f"tg://user?id={user_id}")]
    ])
     return await client.send_message(
         PRIVATE_LOGS,
         text=message,
         reply_markup=admin_buttons
    )

@ren.on_callback_query(filters.regex(r"^cancel_resubmitdl_"))
async def cancel_resubmit(client: Client, callback: CallbackQuery):
    await callback.message.edit_text(
        "🚫 Resubmission cancelled",
        reply_markup=InlineKeyboardMarkup([
            [InlineKeyboardButton("Β« Back", callback_data="my_bots")]
        ])
    )
    await callback.answer()