File size: 25,613 Bytes
78d4936
0189974
1b5719b
8ee0322
eef97a7
78d4936
 
1b5719b
7956eb0
1b5719b
 
 
 
3c05ff4
 
98ab4e9
1b5719b
c1dc926
 
553ca09
78d4936
7956eb0
3c05ff4
 
1b5719b
7956eb0
78d4936
7956eb0
 
78d4936
3c05ff4
4056428
3c05ff4
 
 
 
 
 
4056428
3c05ff4
4056428
3c05ff4
 
 
 
78d4936
3c05ff4
3c9449b
3c05ff4
 
 
 
 
 
 
 
 
 
 
4056428
3c05ff4
 
 
 
 
 
 
 
 
4056428
 
3c05ff4
 
 
4056428
 
3c05ff4
4056428
3580517
c1dc926
3580517
c1dc926
3580517
c1dc926
3c05ff4
3c9449b
 
3c05ff4
 
 
 
 
 
4056428
 
3c05ff4
 
 
4056428
 
3c05ff4
4056428
3c05ff4
 
 
3c9449b
3c05ff4
 
78d4936
4056428
3c05ff4
 
78d4936
3c05ff4
78d4936
3c05ff4
 
4056428
 
3c05ff4
4056428
3c05ff4
78d4936
3c05ff4
 
 
 
 
 
 
4056428
 
3c05ff4
 
 
4056428
 
3c05ff4
4056428
3c05ff4
3c9449b
 
3c05ff4
 
 
 
 
 
4056428
 
3c05ff4
 
 
4056428
 
3c05ff4
4056428
3c05ff4
 
 
3c9449b
3c05ff4
4056428
3c05ff4
 
 
 
 
 
 
 
3c9449b
3c05ff4
 
 
 
 
 
 
36b5e1c
3c05ff4
36b5e1c
4056428
36b5e1c
 
 
1497e15
 
 
 
4056428
1497e15
0dd38bc
c1dc926
 
 
3c05ff4
 
1497e15
c437284
3c05ff4
4056428
7956eb0
 
 
89c3556
7956eb0
 
 
 
4056428
8ee0322
 
 
 
 
 
4056428
8ee0322
 
 
 
 
4056428
8ee0322
 
 
 
 
 
 
4056428
8ee0322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7956eb0
 
 
 
 
 
 
 
 
 
31445af
7956eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c9449b
 
7956eb0
 
 
 
 
 
 
 
 
 
4056428
78d4936
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ccbff
 
 
4056428
78d4936
 
7956eb0
e1fa587
7956eb0
e64dc9b
 
 
7956eb0
89c3556
7956eb0
 
 
78d4936
 
 
 
 
 
4056428
78d4936
4056428
 
 
3c9449b
 
 
 
7956eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d4936
 
 
4056428
 
78d4936
 
 
 
 
 
3580517
 
 
 
d5ccbff
3c9449b
 
 
 
 
 
 
 
 
 
 
d5ccbff
 
 
3c9449b
 
3580517
 
 
7956eb0
 
3580517
7956eb0
 
0dd38bc
7956eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
98ab4e9
7956eb0
 
 
 
e103abc
e64dc9b
 
 
7956eb0
89c3556
7956eb0
fa6fea6
7956eb0
2b3bf8e
3c9449b
7956eb0
 
 
 
 
 
3c9449b
 
22db4d0
99c10c6
fa6fea6
4056428
 
 
99c10c6
22db4d0
3c9449b
 
 
 
 
 
d5ccbff
3c9449b
 
 
 
 
 
7956eb0
 
 
 
22db4d0
7956eb0
 
 
689299e
7956eb0
 
 
 
 
 
 
 
 
 
 
4056428
 
78d4936
 
4056428
78d4936
4056428
 
 
 
 
 
78d4936
 
 
4056428
 
 
 
78d4936
 
4056428
78d4936
 
 
4056428
78d4936
 
4056428
b978403
4056428
78d4936
 
4056428
 
78d4936
 
 
 
 
 
 
 
 
4056428
78d4936
 
 
 
 
 
 
 
7956eb0
4056428
7956eb0
 
89c3556
7956eb0
 
 
 
 
89c3556
 
 
7956eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89c3556
7956eb0
 
 
 
 
 
 
 
89c3556
7956eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4056428
 
3c05ff4
 
 
 
 
 
3c9449b
3c05ff4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c9449b
3c05ff4
 
 
 
 
 
 
 
 
 
4056428
3c05ff4
 
 
 
 
 
 
 
 
 
78d4936
 
809532c
 
 
78d4936
 
 
 
809532c
3c05ff4
809532c
 
 
 
a9917a5
809532c
 
 
 
3c05ff4
 
 
 
 
809532c
 
 
d7e1221
809532c
 
 
 
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
import subprocess as subp
import sys
from asyncio import create_subprocess_shell, sleep, subprocess
from importlib.metadata import PackageNotFoundError, metadata
from io import BytesIO, StringIO
from os import execvp
from sys import executable
from time import gmtime, strftime, time
from traceback import format_exc

from pyrogram.errors import (ChannelInvalid, ChannelPrivate, ChatAdminRequired,
                             EntityBoundsInvalid, FloodWait, MessageTooLong,
                             PeerIdInvalid, RPCError)
from pyrogram.types import InlineKeyboardButton as IKB
from pyrogram.types import InlineKeyboardMarkup as IKM
from pyrogram.types import Message

from Powers import (BOT_TOKEN, LOG_DATETIME, LOGFILE, LOGGER, MESSAGE_DUMP,
                    OWNER_ID, SUPPORT_USERS, UPTIME)
from Powers.bot_class import Gojo
from Powers.database import MongoDB
from Powers.database.chats_db import Chats
from Powers.database.support_db import SUPPORTS
from Powers.database.users_db import Users
from Powers.utils.clean_file import remove_markdown_and_html
from Powers.utils.custom_filters import command
from Powers.utils.extract_user import extract_user
from Powers.utils.parser import mention_markdown


def can_change_type(curr, to_user):
    if curr == "dev" and to_user in ["whitelist", "sudo"]:
        return True
    elif curr == "sudo" and to_user == "whitelist":
        return True
    else:
        return False


@Gojo.on_message(command(["addsupport"]))
async def add_support(c: Gojo, m: Message):
    support = SUPPORTS()
    curr_user = support.get_support_type(m.from_user.id)
    if not curr_user:
        await m.reply_text("Stay in you limit")
        return
    split = m.command
    if reply_to := m.reply_to_message:
        try:
            userr = reply_to.from_user.id
        except Exception:
            await m.reply_text("Reply to an user")
            return
        curr = support.get_support_type(userr)
        try:
            to = split[1].lower()
        except IndexError:
            await m.reply_text("**USAGE**\n/addsupport [reply to message | user id] [dev | sudo | whitelist]")
            return
        if to not in ["dev", "sudo", "whitelist"]:
            await m.reply_text("**USAGE**\n/addsupport [reply to message | user id] [dev | sudo | whitelist]")
            return
        if m.from_user.id == int(OWNER_ID):
            if to == curr:
                await m.reply_text(f"This user is already in {to} users")
            elif curr:
                kb = IKM(
                    [
                        [
                            IKB("Yes", f"change_support_type:{to}"),
                            IKB("No", "change_support_type:no")
                        ]
                    ]
                )
                await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
                                   reply_markup=kb)
            else:
                support.insert_support_user(userr, to)
                if to == "dev":
                    SUPPORT_USERS["Dev"].add(userr)
                elif to == "sudo":
                    SUPPORT_USERS["Sudo"].add(userr)
                else:
                    SUPPORT_USERS["White"].add(userr)
                await m.reply_text(f"This user is now a {to} user")
            return
        if can_do := can_change_type(curr_user, to):
            if to == curr:
                await m.reply_text(f"This user is already in {to} users")
            elif curr:
                kb = IKM(
                    [
                        [
                            IKB("Yes", f"change_support_type:{to}"),
                            IKB("No", "change_support_type:no")
                        ]
                    ]
                )
                await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
                                   reply_markup=kb)
            else:
                support.insert_support_user(userr, to)
                await m.reply_text(f"This user is now a {to} user")
        else:
            await m.reply_text("Sorry you can't do it")
        return
    elif len(split) >= 3:
        user = split[1]
        try:
            userr, _, _ = extract_user(user)
        except Exception:
            await m.reply_text("Tell the user to start me first")
            return
        curr = support.get_support_type(userr)
        try:
            to = m.command[2].lower()
        except IndexError:
            await m.reply_text(
                "**USAGE**\n/addsupport [reply to message | user id | username] [dev | sudo | whitelist]")
            return
        if to not in ["dev", "sudo", "whitelist"]:
            await m.reply_text("**USAGE**\n/addsupport [reply to message | user id] [dev | sudo | whitelist]")
            return
        if m.from_user.id == int(OWNER_ID):
            if to == curr:
                await m.reply_text(f"This user is already in {to} users")
            elif curr:
                kb = IKM(
                    [
                        [
                            IKB("Yes", f"change_support_type:{to}"),
                            IKB("No", "change_support_type:no")
                        ]
                    ]
                )
                await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
                                   reply_markup=kb)
            else:
                support.insert_support_user(userr, to)
                await m.reply_text(f"This user is now a {to} user")
            return
        if can_do := can_change_type(curr_user, to):
            if to == curr:
                await m.reply_text(f"This user is already in {to} users")
            elif curr:
                kb = IKM(
                    [
                        [
                            IKB("Yes", f"change_support_type:{to}"),
                            IKB("No", "change_support_type:no")
                        ]
                    ]
                )
                await m.reply_text(f"This is user is already in {curr} users\nDo you want to make him {to} user?",
                                   reply_markup=kb)
            else:
                support.insert_support_user(userr, to)
                await m.reply_text(f"This user is now a {to} user")
        else:
            await m.reply_text("Sorry you can't do it")
        return


@Gojo.on_message(command("rmsupport"))
async def rm_support(c: Gojo, m: Message):
    support = SUPPORTS()
    curr_user = support.get_support_type(m.from_user.id)
    if not curr_user:
        await m.reply_text("Stay in you limit")
        return
    split = m.command
    if reply_to := m.reply_to_message:
        try:
            curr = reply_to.from_user.id
        except Exception:
            await m.reply_text("Reply to an user")
            return
    elif len(split) >= 2:
        try:
            curr = int(split[1])
        except Exception:
            try:
                curr, _, _ = extract_user(m)
            except Exception:
                await m.reply_text("Dunno who u r talking abt")
                return
    else:
        await m.reply_text("**USAGE**\n/rmsupport [reply to user | user id | username]")
        return
    to_user = support.get_support_type(curr)
    can_user = can_change_type(curr_user, to_user)
    if m.from_user.id == int(OWNER_ID) or can_user:
        support.delete_support_user(curr)
        SUPPORT_USERS["Dev"].discard(curr)
        SUPPORT_USERS["Sudo"].discard(curr)
        SUPPORT_USERS["White"].discard(curr)
        await m.reply_text("Done! User now no longer belongs to the support staff")
    else:
        await m.reply_text("Sorry you can't do that...")
    return


@Gojo.on_message(command("ping", sudo_cmd=True))
async def ping(_, m: Message):
    start = time()
    replymsg = await m.reply_text(text="Pinging...", quote=True)
    delta_ping = time() - start
    await replymsg.edit_text(f"<b>Pong!</b>\n{delta_ping * 1000:.3f} ms")
    return


"""

['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'License', 'Download-URL', 'Project-URL', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Description-Content-Type', 'License-File', 'License-File', 'License-File', 'Requires-Dist', 'Requires-Dist', 'Description']

"""


@Gojo.on_message(command(["minfo", "moduleinfo"], dev_cmd=True))
async def check_module_info(_, m: Message):
    if len(m.command) != 2:
        await m.reply_text("**USAGE**\n/minfo [module name]")
        return

    module = m.command[-1]

    try:
        minfo = metadata(module)
    except PackageNotFoundError:
        await m.reply_text(f"No module found with name {module}")
        return

    name = minfo["Name"]
    version = minfo["Version"]
    summary = minfo["Summary"]
    home_page = minfo["Home-Page"]
    author = minfo["Author"]
    license = minfo["License"]
    download = minfo["Download-URL"]

    txt = f"""
Here are the info about the module **{name}**
• Version: {version}

• Summary: {summary}

• Home page: {home_page}

• Author: {author}

• License: {license}

• Download: {download}
"""
    await m.reply_text(txt, disable_web_page_preview=True)
    return


@Gojo.on_message(command("logs", dev_cmd=True))
async def send_log(c: Gojo, m: Message):
    replymsg = await m.reply_text("Sending logs...!")
    await c.send_message(
        MESSAGE_DUMP,
        f"#LOGS\n\n**User:** {(await mention_markdown(m.from_user.first_name, m.from_user.id))}",
    )
    # Send logs
    with open(LOGFILE) as f:
        raw = ((f.read()))[1]
    await m.reply_document(
        document=LOGFILE,
        quote=True,
    )
    await replymsg.delete()
    return


@Gojo.on_message(command("neofetch", dev_cmd=True))
async def neofetch_stats(_, m: Message):
    cmd = "neofetch --stdout"

    process = await create_subprocess_shell(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, stderr = await process.communicate()
    e = stderr.decode() or "No Error"
    OUTPUT = stdout.decode() or "No Output"

    try:
        await m.reply_text(OUTPUT, quote=True)
    except MessageTooLong:
        with BytesIO(str.encode(await remove_markdown_and_html(OUTPUT))) as f:
            f.name = "neofetch.txt"
            await m.reply_document(document=f, caption="neofetch result")
        await m.delete()
    return


HARMFUL = [
    "base64",
    "bash",
    "get_me()",
    "phone",
    "os.system",
    "sys.stdout",
    "sys.stderr",
    "subprocess",
    "DB_URI",
    "DB_URI",
    "BOT_TOKEN",
    "API_HASH",
    "APP_ID",
    "SSH_CLIENT",
    "SSH_CONNECTION"
    "SSH"

]


@Gojo.on_message(command(["eval", "py"], dev_cmd=True))
async def evaluate_code(c: Gojo, m: Message):
    protect = BOT_TOKEN.split(":")
    initial = protect[0]
    end = protect[1][-5:]
    if len(m.text.split()) == 1:
        await m.reply_text(text="Please execute the code correctly!")
        return
    sm = await m.reply_text("`Processing...`")
    cmd = m.text.split(None, maxsplit=1)[1]
    if "while True:" in cmd:
        await sm.delete()
        await m.reply_text("BSDK SPAM NI")
        await c.send_message(
            MESSAGE_DUMP,
            f"@{m.from_user.username} TREID TO USE `while True` \n userid = {m.from_user.id}"
        )
        return
    if m.reply_to_message and m.reply_to_message.document and (m.reply_to_message.document.mime_type.split("/")[
                                                                   1] == "x-python" or m.reply_to_message.document.file_name.endswith(
            "py")):
        await sm.delete()
        await m.reply_text("Loading external plugin is prohibited")
        return
    reply_to_id = m.reply_to_message.id if m.reply_to_message else m.id
    old_stderr = sys.stderr
    old_stdout = sys.stdout
    redirected_output = sys.stdout = StringIO()
    redirected_error = sys.stderr = StringIO()
    stdout, stderr, exc = None, None, None

    try:
        await aexec(cmd, c, m)
    except Exception as ef:
        LOGGER.error(ef)
        exc = format_exc()

    stdout = redirected_output.getvalue()
    stderr = redirected_error.getvalue()
    sys.stdout = old_stdout
    sys.stderr = old_stderr

    evaluation = ""
    if exc:
        evaluation = exc
    elif stderr:
        evaluation = stderr
    elif stdout:
        evaluation = stdout
    else:
        evaluation = "Success"
    for i in evaluation.split(None):
        ev = i.strip()
        if (
                (ev.startswith(initial) or ev.endswith(end))
                or (BOT_TOKEN in ev)
        ) and m.from_user.id != OWNER_ID:
            evaluation = "Bhaag ja bsdk"
            await c.send_message(
                MESSAGE_DUMP,
                f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}",
            )
            final_output = f"**EVAL**: ```python\n{cmd}```\n\n<b>OUTPUT</b>:\n```powershell\n{evaluation}```</code> \n"
            await sm.edit(final_output)
            return

    for j in HARMFUL:
        if (j in evaluation.split() or j in cmd) and m.from_user.id != OWNER_ID:
            evaluation = "Bhaag ja bsdk"
            await c.send_message(
                MESSAGE_DUMP,
                f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}")
            final_output = f"**EVAL**: ```python\n{cmd}```\n\n<b>OUTPUT</b>:\n```powershell\n{evaluation}```</code> \n"
            await sm.edit(final_output)
            return
    for i in evaluation.split():
        for j in i.split("="):
            if j and j[0] in HARMFUL and m.from_user.id != OWNER_ID:
                evaluation = "Bhaag ja bsdk"
                await c.send_message(
                    MESSAGE_DUMP,
                    f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}"
                )
                final_output = f"**EVAL**: ```python\n{cmd}```\n\n<b>OUTPUT</b>:\n```powershell\n{evaluation}```</code> \n"
                await sm.edit(final_output)
                return

    try:
        final_output = f"**EVAL**: ```python\n{cmd}```\n\n<b>OUTPUT</b>:\n```powershell\n{evaluation}```</code> \n"
        await sm.edit(final_output)
    except MessageTooLong:
        final_output = f"<b>EVAL</b>: <code>{cmd}</code>\n\n<b>OUTPUT</b>:\n<code>{evaluation}</code> \n"
        with BytesIO(str.encode(await remove_markdown_and_html(final_output))) as f:
            f.name = "py.txt"
            await m.reply_document(
                document=f,
                caption=cmd,
                disable_notification=True,
                reply_to_message_id=reply_to_id,
            )
        await sm.delete()

    return


async def aexec(code, c, m):
    exec("async def __aexec(c, m): " + "".join(f"\n {l}" for l in code.split("\n")))
    return await locals()["__aexec"](c, m)


@Gojo.on_message(command(["exec", "sh"], dev_cmd=True))
async def execution(c: Gojo, m: Message):
    protect = BOT_TOKEN.split(":")
    initial = protect[0]
    end = protect[1][-5:]
    if len(m.text.split()) == 1:
        await m.reply_text(text="Please execute the code correctly!")
        return
    sm = await m.reply_text("`Processing...`\n")
    cmd = m.text.split(maxsplit=1)[1]

    reply_to_id = m.reply_to_message.id if m.reply_to_message else m.id
    process = await create_subprocess_shell(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    stdout, stderr = await process.communicate()
    e = stderr.decode().strip() or "No Error"
    o = stdout.decode().strip() or "No Output"
    out = o
    xxx = o.split()
    for OwO in xxx:
        if OwO.startswith(initial) or OwO.endswith(end):
            out = "You can't access them"
            break
    for x in xxx:
        xx = x.split("=")
        if xx and xx[0] in HARMFUL and m.from_user.id != OWNER_ID:
            out = "You can't access them"
            await c.send_message(
                MESSAGE_DUMP,
                f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}",
            )
    for x in HARMFUL:
        if x in out and m.from_user.id != OWNER_ID:
            out = "You can't access them"
            await c.send_message(
                MESSAGE_DUMP,
                f"@{m.from_user.username} TREID TO FETCH ENV OF BOT \n userid = {m.from_user.id}",
            )
    OUTPUT = ""
    OUTPUT += f"<b>QUERY:</b>\n<u>Command:</u>\n<code>{cmd}</code> \n"
    OUTPUT += f"<u>PID</u>: <code>{process.pid}</code>\n\n"
    OUTPUT += f"<b>stderr</b>: \n<code>{e}</code>\n\n"
    OUTPUT += f"<b>stdout</b>: \n<code>{out}</code>"

    try:
        await sm.edit_text(OUTPUT)
    except (MessageTooLong, EntityBoundsInvalid):
        with BytesIO(str.encode(await remove_markdown_and_html(OUTPUT))) as f:
            f.name = "sh.txt"
            await m.reply_document(
                document=f,
                caption=cmd,
                disable_notification=True,
                reply_to_message_id=reply_to_id,
            )
        await sm.delete()
    return


async def stop_and_send_logger(c: Gojo, is_update=False):
    runtime = strftime("%Hh %Mm %Ss", gmtime(time() - UPTIME))
    LOGGER.info("Uploading logs before stopping...!\n")
    # Send Logs to MESSAGE_DUMP and LOG_CHANNEL
    await c.send_document(
        MESSAGE_DUMP,
        document=LOGFILE,
        caption=(
            f"{'Updating and Restarting' if is_update else 'Restarting'} The Bot !\n\n" f"Uptime: {runtime}\n" f"<code>{LOG_DATETIME}</code>"
        ),
    )
    if MESSAGE_DUMP:
        # LOG_CHANNEL is not necessary
        await c.send_document(
            MESSAGE_DUMP,
            document=LOGFILE,
            caption=f"Uptime: {runtime}",
        )
    MongoDB.close()
    LOGGER.info(
        f"""Bot Stopped.
            Logs have been uploaded to the MESSAGE_DUMP Group!
            Runtime: {runtime}s\n
        """,
    )
    return


@Gojo.on_message(command(["restart", "update"], owner_cmd=True))
async def restart_the_bot(c: Gojo, m: Message):
    try:
        cmds = m.command
        await m.reply_text(
            f"Restarting{' and updating ' if cmds[0] == 'update' else ' '}the bot...\nType `/ping` after few minutes")
        if cmds[0] == "update":
            try:
                out = subp.check_output(["git", "pull"]).decode("UTF-8")
                if "Already up to date." in str(out):
                    return await m.reply_text("Its already up-to date!")
                await m.reply_text(f"```{out}```")
            except Exception as e:
                return await m.reply_text(str(e))
            m = await m.reply_text("**Updated with main branch, restarting now.**")
            await stop_and_send_logger(c, True)
        if cmds[0] == "restart":
            await stop_and_send_logger(c)
        execvp(executable, [executable, "-m", "Powers"])
    except Exception as e:
        await m.reply_text(f"Failed to restart the bot due to\n{e}")
        LOGGER.error(e)
        LOGGER.error(format_exc())
        return


@Gojo.on_message(command("chatlist", dev_cmd=True))
async def chats(c: Gojo, m: Message):
    exmsg = await m.reply_text(text="Exporting Charlist...")
    await c.send_message(
        MESSAGE_DUMP,
        f"#CHATLIST\n\n**User:** {(await mention_markdown(m.from_user.first_name, m.from_user.id))}",
    )
    all_chats = (Chats.list_chats_full()) or {}
    chatfile = """List of chats in my database.

        <b>Chat name | Chat ID | Members count</b>"""
    P = 1
    for chat in all_chats:
        try:
            chat_info = await c.get_chat(chat["_id"])
            chat_members = chat_info.members_count
            try:
                invitelink = chat_info.invite_link
            except KeyError:
                invitelink = "No Link!"
            chatfile += f"{P}. {chat['chat_name']} | {chat['_id']} | {chat_members} | {invitelink}\n"
            P += 1
        except ChatAdminRequired:
            pass
        except (ChannelPrivate, ChannelInvalid):
            Chats.remove_chat(chat["_id"])
        except PeerIdInvalid:
            LOGGER.warning(f"Peer not found {chat['_id']}")
        except FloodWait as ef:
            LOGGER.error("FloodWait required, Sleeping for 60s")
            LOGGER.error(ef)
            sleep(60)
        except RPCError as ef:
            LOGGER.error(ef)
            await m.reply_text(f"**Error:**\n{ef}")

    with BytesIO(str.encode(await remove_markdown_and_html(chatfile))) as f:
        f.name = "chatlist.txt"
        await m.reply_document(
            document=f,
            caption="Here is the list of chats in my Database.",
        )
    await exmsg.delete()
    return


@Gojo.on_message(command("uptime", dev_cmd=True))
async def uptime(_, m: Message):
    up = strftime("%Hh %Mm %Ss", gmtime(time() - UPTIME))
    await m.reply_text(text=f"<b>Uptime:</b> <code>{up}</code>", quote=True)
    return


@Gojo.on_message(command("leavechat", dev_cmd=True))
async def leave_chat(c: Gojo, m: Message):
    if len(m.text.split()) != 2:
        await m.reply_text("Supply a chat id which I should leave!", quoet=True)
        return

    chat_id = m.text.split(None, 1)[1]

    replymsg = await m.reply_text(f"Trying to leave chat {chat_id}...", quote=True)
    try:
        await c.leave_chat(chat_id)
        await replymsg.edit_text(f"Left <code>{chat_id}</code>.")
    except PeerIdInvalid:
        await replymsg.edit_text("Haven't seen this group in this session!")
    except RPCError as ef:
        LOGGER.error(ef)
        await replymsg.edit_text(f"Failed to leave chat!\nError: <code>{ef}</code>.")
    return


@Gojo.on_message(command("chatbroadcast", dev_cmd=True))
async def chat_broadcast(c: Gojo, m: Message):
    if m.reply_to_message:
        msg = m.reply_to_message.text.markdown
    else:
        await m.reply_text("Reply to a message to broadcast it")
        return

    exmsg = await m.reply_text("Started broadcasting!")
    all_chats = (Chats.list_chats_by_id()) or {}
    err_str, done_broadcast = "", 0

    for chat in all_chats:
        try:
            await c.send_message(chat, msg, disable_web_page_preview=True)
            done_broadcast += 1
            await sleep(0.1)
        except RPCError as ef:
            LOGGER.error(ef)
            err_str += str(ef)
            continue

    await exmsg.edit_text(
        f"Done broadcasting ✅\nSent message to {done_broadcast} chats",
    )

    if err_str:
        with BytesIO(str.encode(await remove_markdown_and_html(err_str))) as f:
            f.name = "error_broadcast.txt"
            await m.reply_document(
                document=f,
                caption="Broadcast Error",
            )

    return


@Gojo.on_message(command(["forward", "fwd"], dev_cmd=True))
async def forward_type_broadcast(c: Gojo, m: Message):
    repl = m.reply_to_message
    if not repl:
        await m.reply_text("Please reply to message to broadcast it")
        return
    split = m.command

    chat = Chats.list_chats_by_id()
    user = [i["_id"] for i in Users.list_users()]
    alll = chat + user
    if len(split) != 2:
        tag = "all"
    else:
        try:
            if split[0].lower() == "-u":
                tag = "user"
            elif split[0].lower() == "-c":
                tag = "chat"
            else:
                tag = "all"
        except IndexError:
            pass
    if tag == "chat":
        peers = chat
    elif tag == "user":
        peers = user
    else:
        peers = alll

    xx = await m.reply_text("Broadcasting...")

    failed = 0
    total = len(peers)
    for peer in peers:
        try:
            await repl.forward(int(peer))
            await sleep(0.1)
        except Exception:
            failed += 1
    txt = f"Broadcasted message to {total - failed} peers out of {total}\nFailed to broadcast message to {failed} peers"
    if not failed:
        txt = f"Broadcasted message to {total} peers"
    await m.reply_text(txt)
    try:
        await xx.delete()
    except Exception:
        pass
    return


__PLUGIN__ = "devs"

__HELP__ = """
**DEV and SUDOERS commands**

**Owner's commands:**
• /restart : Restart the bot
• /update : To update the bot with the main stream repo

**Dev's commands:**
• /addsupport [dev | sudo | whitelist] : Reply to message or give me user id or username
• /logs : Return the logs of bot.
• /neofetch : Fetch neo.
• /eval : Evaluate the given python code.
• /exec : Execute the given code.
• /minfo [module name]: Give info about module
• /chatlist : Return the list of chats present in database
• /uptime : Return the uptime of the bot.
• /leavechat : Bot will leave the provided chat.
• /chatbroadcast : Broadcast the messge to chats.
• /forward (/fwd) [tag] : Forward message to peers according to tag. Default to all
    Available tags:
     `-u` : For users
     `-c` : For chats
     `-all` : For all

**Sudoer's command:**
• /ping : return the ping of the bot.
• /cleandb : Delete useless junks from database (Automatically start cleaning it at 3:00:00 AM)

**Example:**
/ping
"""