summaryrefslogtreecommitdiff
path: root/calc.py
diff options
context:
space:
mode:
authorPanFritz <redstonenoobpan@gmail.com>2015-01-13 12:51:25 +0100
committerPanFritz <redstonenoobpan@gmail.com>2015-01-13 12:51:25 +0100
commitf85a8e1bab9ae7b1a2ae349a710d21f2a185dcd5 (patch)
tree4944961925565e3f68b4837d40ab8e2c4d91514c /calc.py
parentdaf325a6e4a4a42d2a3bd8cd039b70daa783a232 (diff)
removed should_calc condition from line 23, replaced break
Diffstat (limited to 'calc.py')
-rw-r--r--calc.py62
1 files changed, 62 insertions, 0 deletions
diff --git a/calc.py b/calc.py
index e69de29..ef2d1a7 100644
--- a/calc.py
+++ b/calc.py
@@ -0,0 +1,62 @@
+from helpers import *
+
+calc_users = open_json_file("calc", [])
+math_operators = ["+", "-", "*", "/", "&", "|", ">", "<", "~", "%"]
+ignore_operators = ["**", "&&", "||"] # ** may be too intensive, the others cause syntax errors
+calc_perm = "utils.calc"
+
+
+def calc(text):
+ """
+ extracts a mathematical expression from `text`
+ returns (expression, result) or None
+ """
+ expression = ""
+ should_calc = False
+ for char in text:
+ if char.isdigit() or (should_calc and char in [".", " "]):
+ expression += char
+ elif char in math_operators:
+ # calculation must include at least 1 operator
+ should_calc = True
+ expression += char
+ elif char.isalpha():
+ # don't include any more text in the calculation
+ expression = ""
+ if should_calc and not any(op in expression for op in ignore_operators):
+ try:
+ result = str(eval(expression)) # pylint: disable = W0123
+ except: # pylint: disable = W0702
+ # we can run into all kinds of errors here
+ # most probably SyntaxError
+ return None
+ return (expression, result)
+ return None
+
+
+@hook.event("player.AsyncPlayerChatEvent", "monitor")
+def on_calc_chat(event):
+ sender = event.getPlayer()
+ message = event.getMessage()
+ if not event.isCancelled() and uid(sender) in calc_users and sender.hasPermission(calc_perm):
+ output = calc(message)
+ if type(output)in [int, float, long, complex]:
+ msg(sender, "&2=== Calc: &e" + output[0] + " &2= &c" + str(output[1]).replace("420", "blazeit"))
+
+
+@hook.command("calc", description="Toggles chat calculations")
+def on_calc_command(sender, args):
+ plugin_header(sender, "Chat Calculator")
+ if not sender.hasPermission(calc_perm):
+ noperm(sender)
+ return True
+ if not checkargs(sender, args, 0, 1):
+ return True
+ if not is_player(sender):
+ msg(sender, "&cYou are not a player!" % sender)
+ return True
+
+ toggle(sender, calc_users, name = "Calc")
+ save_json_file("calc", calc_users)
+
+ return True