Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
anasty17
GitHub Repository: anasty17/mirror-leech-telegram-bot
Path: blob/master/bot/modules/exec.py
1619 views
1
from aiofiles import open as aiopen
2
from contextlib import redirect_stdout
3
from io import StringIO, BytesIO
4
from os import path as ospath, getcwd, chdir
5
from textwrap import indent
6
from traceback import format_exc
7
8
from .. import LOGGER
9
from ..core.telegram_manager import TgClient
10
from ..helper.ext_utils.bot_utils import sync_to_async, new_task
11
from ..helper.telegram_helper.message_utils import send_file, send_message
12
13
namespaces = {}
14
15
16
def namespace_of(message):
17
if message.chat.id not in namespaces:
18
namespaces[message.chat.id] = {
19
"__builtins__": globals()["__builtins__"],
20
"bot": TgClient.bot,
21
"message": message,
22
"user": message.from_user or message.sender_chat,
23
"chat": message.chat,
24
}
25
26
return namespaces[message.chat.id]
27
28
29
def log_input(message):
30
LOGGER.info(
31
f"IN: {message.text} (user={message.from_user.id if message.from_user else message.sender_chat.id}, chat={message.chat.id})"
32
)
33
34
35
async def send(msg, message):
36
if len(str(msg)) > 2000:
37
with BytesIO(str.encode(msg)) as out_file:
38
out_file.name = "output.txt"
39
await send_file(message, out_file)
40
else:
41
LOGGER.info(f"OUT: '{msg}'")
42
await send_message(message, f"<code>{msg}</code>")
43
44
45
@new_task
46
async def aioexecute(_, message):
47
await send(await do("aexec", message), message)
48
49
50
@new_task
51
async def execute(_, message):
52
await send(await do("exec", message), message)
53
54
55
def cleanup_code(code):
56
if code.startswith("```") and code.endswith("```"):
57
return "\n".join(code.split("\n")[1:-1])
58
return code.strip("` \n")
59
60
61
async def do(func, message):
62
log_input(message)
63
content = message.text.split(maxsplit=1)[-1]
64
body = cleanup_code(content)
65
env = namespace_of(message)
66
67
chdir(getcwd())
68
async with aiopen(ospath.join(getcwd(), "bot/modules/temp.txt"), "w") as temp:
69
await temp.write(body)
70
71
stdout = StringIO()
72
73
try:
74
if func == "exec":
75
exec(f"def func():\n{indent(body, ' ')}", env)
76
else:
77
exec(f"async def func():\n{indent(body, ' ')}", env)
78
except Exception as e:
79
return f"{e.__class__.__name__}: {e}"
80
81
rfunc = env["func"]
82
83
try:
84
with redirect_stdout(stdout):
85
func_return = (
86
await sync_to_async(rfunc) if func == "exec" else await rfunc()
87
)
88
except:
89
value = stdout.getvalue()
90
return f"{value}{format_exc()}"
91
else:
92
value = stdout.getvalue()
93
result = None
94
if func_return is None:
95
if value:
96
result = f"{value}"
97
else:
98
try:
99
result = f"{repr(await sync_to_async(eval, body, env))}"
100
except:
101
pass
102
else:
103
result = f"{value}{func_return}"
104
if result:
105
return result
106
107
108
@new_task
109
async def clear(_, message):
110
log_input(message)
111
global namespaces
112
if message.chat.id in namespaces:
113
del namespaces[message.chat.id]
114
await send("Locals Cleared.", message)
115
116