-
Notifications
You must be signed in to change notification settings - Fork 1
/
calc.py
54 lines (48 loc) · 1.46 KB
/
calc.py
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
import io
import sys
import traceback
from . import *
@bot.on(d3vil_cmd(pattern="calc (.*)"))
@bot.on(sudo_cmd(pattern="calc (.*)", allow_sudo=True))
async def _(car):
if car.fwd_from:
return
cmd = car.text.split(" ", maxsplit=1)[1]
event = await edit_or_reply(car, "Calculating ...")
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
redirected_error = sys.stderr = io.StringIO()
stdout, stderr, exc = None, None, None
san = f"print({cmd})"
try:
await aexec(san, event)
except Exception:
exc = traceback.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 = "Sorry I can't find result for the given equation"
final_output = "**EQUATION**: `{}` \n\n **SOLUTION**: \n`{}` \n".format(
cmd, evaluation
)
await event.edit(final_output)
async def aexec(code, event):
exec(f"async def __aexec(event): " + "".join(f"\n {l}" for l in code.split("\n")))
return await locals()["__aexec"](event)
CmdHelp("calc").add_command(
"calc", "Your expression", "Sopves the given maths equation by BODMAS rule"
).add_info(
"Calculator"
).add_warning(
"✅ Harmless Module."
).add()