userbot.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. """
  2. CREDITS:
  3. EVAL AND SH FUNCTION IN THIS MODULE IS WRITTEN BY @Pokurt.
  4. SOURCE:
  5. https://github.com/pokurt/Nana-Remix/blob/master/nana/plugins/devs.py
  6. """
  7. import os
  8. import re
  9. import subprocess
  10. import sys
  11. import traceback
  12. from html import escape
  13. from inspect import getfullargspec
  14. from io import StringIO
  15. from time import time
  16. import aiofiles
  17. from pyrogram import filters
  18. from pyrogram.types import Message
  19. from wbb import SUDOERS, USERBOT_PREFIX, app, app2, arq
  20. __MODULE__ = "Userbot"
  21. __HELP__ = """
  22. .alive - Send Alive Message.
  23. .l - Execute Python Code.
  24. .sh - Execute Shell Code.
  25. .approve | .disapprove - Approve Or Disapprove A User To PM You.
  26. .block | .unblock - Block Or Unblock A User.
  27. """
  28. arq = arq
  29. # Eval and Sh module from nana-remix
  30. async def aexec(code, client, message):
  31. exec(
  32. "async def __aexec(client, message): "
  33. + "".join(f"\n {a}" for a in code.split("\n"))
  34. )
  35. return await locals()["__aexec"](client, message)
  36. async def edit_or_reply(msg: Message, **kwargs):
  37. func = msg.edit_text if msg.from_user.is_self else msg.reply
  38. spec = getfullargspec(func.__wrapped__).args
  39. await func(**{k: v for k, v in kwargs.items() if k in spec})
  40. @app2.on_message(
  41. filters.user(SUDOERS)
  42. & ~filters.forwarded
  43. & ~filters.via_bot
  44. & filters.command("l", prefixes=USERBOT_PREFIX)
  45. )
  46. async def executor(client, message: Message):
  47. try:
  48. cmd = message.text.split(" ", maxsplit=1)[1]
  49. except IndexError:
  50. return await message.delete()
  51. old_stderr = sys.stderr
  52. old_stdout = sys.stdout
  53. redirected_output = sys.stdout = StringIO()
  54. redirected_error = sys.stderr = StringIO()
  55. stdout, stderr, exc = None, None, None
  56. try:
  57. await aexec(cmd, client, message)
  58. except Exception:
  59. exc = traceback.format_exc()
  60. stdout = redirected_output.getvalue()
  61. stderr = redirected_error.getvalue()
  62. sys.stdout = old_stdout
  63. sys.stderr = old_stderr
  64. evaluation = ""
  65. if exc:
  66. evaluation = exc
  67. elif stderr:
  68. evaluation = stderr
  69. elif stdout:
  70. evaluation = stdout
  71. else:
  72. evaluation = "Success"
  73. final_output = f"**INPUT:**\n```{escape(cmd)}```\n\n**OUTPUT**:\n```{escape(evaluation.strip())}```"
  74. if len(final_output) > 4096:
  75. filename = "output.txt"
  76. with open(filename, "w+", encoding="utf8") as out_file:
  77. out_file.write(str(evaluation.strip()))
  78. await message.reply_document(
  79. document=filename,
  80. caption=f"**INPUT:**\n`{escape(cmd[0:980])}`\n\n**OUTPUT:**\n`Attached Document`",
  81. quote=False,
  82. )
  83. await message.delete()
  84. os.remove(filename)
  85. else:
  86. await edit_or_reply(message, text=final_output)
  87. @app2.on_message(
  88. filters.user(SUDOERS)
  89. & ~filters.forwarded
  90. & ~filters.via_bot
  91. & filters.command("sh", prefixes=USERBOT_PREFIX),
  92. )
  93. async def shellrunner(client, message: Message):
  94. if len(message.command) < 2:
  95. return await edit_or_reply(message, text="**Usage:**\n/sh git pull")
  96. text = message.text.split(None, 1)[1]
  97. if "\n" in text:
  98. code = text.split("\n")
  99. output = ""
  100. for x in code:
  101. shell = re.split(""" (?=(?:[^'"]|'[^']*'|"[^"]*")*$)""", x)
  102. try:
  103. process = subprocess.Popen(
  104. shell,
  105. stdout=subprocess.PIPE,
  106. stderr=subprocess.PIPE,
  107. )
  108. except Exception as err:
  109. print(err)
  110. await edit_or_reply(
  111. message,
  112. text=f"**INPUT:**\n```{escape(text)}```\n\n**ERROR:**\n```{escape(err)}```",
  113. )
  114. output += f"**{code}**\n"
  115. output += process.stdout.read()[:-1].decode("utf-8")
  116. output += "\n"
  117. else:
  118. shell = re.split(""" (?=(?:[^'"]|'[^']*'|"[^"]*")*$)""", text)
  119. for a in range(len(shell)):
  120. shell[a] = shell[a].replace('"', "")
  121. try:
  122. process = subprocess.Popen(
  123. shell,
  124. stdout=subprocess.PIPE,
  125. stderr=subprocess.PIPE,
  126. )
  127. except Exception as err:
  128. print(err)
  129. exc_type, exc_obj, exc_tb = sys.exc_info()
  130. errors = traceback.format_exception(
  131. etype=exc_type,
  132. value=exc_obj,
  133. tb=exc_tb,
  134. )
  135. return await edit_or_reply(
  136. message,
  137. text=f"**INPUT:**\n```{escape(text)}```\n\n**ERROR:**\n```{''.join(errors)}```",
  138. )
  139. output = process.stdout.read()[:-1].decode("utf-8")
  140. if str(output) == "\n":
  141. output = None
  142. if output:
  143. if len(output) > 4096:
  144. with open("output.txt", "w+") as file:
  145. file.write(output)
  146. await app.send_document(
  147. message.chat.id,
  148. "output.txt",
  149. reply_to_message_id=message.message_id,
  150. caption="`Output`",
  151. )
  152. return os.remove("output.txt")
  153. await edit_or_reply(
  154. message,
  155. text=f"**INPUT:**\n```{escape(text)}```\n\n**OUTPUT:**\n```{escape(output)}```",
  156. )
  157. else:
  158. await edit_or_reply(
  159. message,
  160. text=f"**INPUT:**\n```{escape(text)}```\n\n**OUTPUT: **\n`No output`",
  161. )
  162. """ C and CPP Eval """
  163. async def sendFile(message: Message, text: str):
  164. file = "output.txt"
  165. async with aiofiles.open(file, mode="w+") as f:
  166. await f.write(text)
  167. await message.reply_document(file)
  168. os.remove(file)
  169. @app2.on_message(
  170. filters.command(["c", "cpp"], prefixes=USERBOT_PREFIX) & filters.user(SUDOERS)
  171. )
  172. async def c_cpp_eval(_, message: Message):
  173. code = message.text.strip()[3:]
  174. file = "exec.c"
  175. compiler = "g++"
  176. out = "exec"
  177. cmdCompile = [compiler, "-g", file, "-o", out]
  178. cmdRun = [f"./{out}"]
  179. async with aiofiles.open(file, mode="w+") as f:
  180. await f.write(code)
  181. t1 = time()
  182. pCompile = subprocess.run(cmdCompile, capture_output=True)
  183. os.remove(file)
  184. err = pCompile.stderr.decode()
  185. if err:
  186. text = f"""
  187. **INPUT:**
  188. ```{escape(code)}```
  189. **COMPILE-TIME ERROR:**
  190. ```{escape(err)}```
  191. """
  192. if len(text) > 4090:
  193. return await sendFile(message, text)
  194. return await edit_or_reply(message, text=text)
  195. pRun = subprocess.run(cmdRun, capture_output=True)
  196. t2 = time()
  197. os.remove(out)
  198. err = pRun.stderr.decode()
  199. out = pRun.stdout.decode()
  200. err = f"**RUNTIME ERROR:**\n```{escape(err)}```" if err else None
  201. out = f"**OUTPUT:**\n```{escape(out)}```" if out else None
  202. text = f"""
  203. **INPUT:**
  204. ```{escape(code)}```
  205. {err if err else out}
  206. `Compiled and executed in {round(t2-t1, 5)} seconds`
  207. """
  208. if len(text) > 4090:
  209. return await sendFile(message, text)
  210. await edit_or_reply(message, text=text)