Path: blob/master/bot/modules/exec.py
1619 views
from aiofiles import open as aiopen1from contextlib import redirect_stdout2from io import StringIO, BytesIO3from os import path as ospath, getcwd, chdir4from textwrap import indent5from traceback import format_exc67from .. import LOGGER8from ..core.telegram_manager import TgClient9from ..helper.ext_utils.bot_utils import sync_to_async, new_task10from ..helper.telegram_helper.message_utils import send_file, send_message1112namespaces = {}131415def namespace_of(message):16if message.chat.id not in namespaces:17namespaces[message.chat.id] = {18"__builtins__": globals()["__builtins__"],19"bot": TgClient.bot,20"message": message,21"user": message.from_user or message.sender_chat,22"chat": message.chat,23}2425return namespaces[message.chat.id]262728def log_input(message):29LOGGER.info(30f"IN: {message.text} (user={message.from_user.id if message.from_user else message.sender_chat.id}, chat={message.chat.id})"31)323334async def send(msg, message):35if len(str(msg)) > 2000:36with BytesIO(str.encode(msg)) as out_file:37out_file.name = "output.txt"38await send_file(message, out_file)39else:40LOGGER.info(f"OUT: '{msg}'")41await send_message(message, f"<code>{msg}</code>")424344@new_task45async def aioexecute(_, message):46await send(await do("aexec", message), message)474849@new_task50async def execute(_, message):51await send(await do("exec", message), message)525354def cleanup_code(code):55if code.startswith("```") and code.endswith("```"):56return "\n".join(code.split("\n")[1:-1])57return code.strip("` \n")585960async def do(func, message):61log_input(message)62content = message.text.split(maxsplit=1)[-1]63body = cleanup_code(content)64env = namespace_of(message)6566chdir(getcwd())67async with aiopen(ospath.join(getcwd(), "bot/modules/temp.txt"), "w") as temp:68await temp.write(body)6970stdout = StringIO()7172try:73if func == "exec":74exec(f"def func():\n{indent(body, ' ')}", env)75else:76exec(f"async def func():\n{indent(body, ' ')}", env)77except Exception as e:78return f"{e.__class__.__name__}: {e}"7980rfunc = env["func"]8182try:83with redirect_stdout(stdout):84func_return = (85await sync_to_async(rfunc) if func == "exec" else await rfunc()86)87except:88value = stdout.getvalue()89return f"{value}{format_exc()}"90else:91value = stdout.getvalue()92result = None93if func_return is None:94if value:95result = f"{value}"96else:97try:98result = f"{repr(await sync_to_async(eval, body, env))}"99except:100pass101else:102result = f"{value}{func_return}"103if result:104return result105106107@new_task108async def clear(_, message):109log_input(message)110global namespaces111if message.chat.id in namespaces:112del namespaces[message.chat.id]113await send("Locals Cleared.", message)114115116