Changed calc to run on a separate thread
This commit is contained in:
43
calc.py
43
calc.py
@@ -1,48 +1,27 @@
|
|||||||
from helpers import *
|
from helpers import *
|
||||||
|
import threading
|
||||||
|
|
||||||
calc_users = open_json_file("calc", [])
|
calc_users = open_json_file("calc", [])
|
||||||
math_operators = ["+", "-", "*", "/", "&", "|"]
|
|
||||||
ignore_operators = ["**", "&&", "||"] # ** may be too intensive, the others cause syntax errors
|
|
||||||
calc_perm = "utils.calc"
|
calc_perm = "utils.calc"
|
||||||
|
|
||||||
|
def calculate(text):
|
||||||
|
pass
|
||||||
|
|
||||||
def calc(text):
|
def calc(text, sender):
|
||||||
"""
|
|
||||||
extracts a mathematical expression from `text`
|
|
||||||
returns (expression, result) or None
|
|
||||||
"""
|
|
||||||
expression = ""
|
|
||||||
should_calc = False
|
|
||||||
for char in text:
|
|
||||||
if char.isdigit() or (expression and char == ".") or (should_calc and char == " "):
|
|
||||||
expression += char
|
|
||||||
elif char in math_operators:
|
|
||||||
# calculation must include at least 1 operator
|
|
||||||
should_calc = True
|
|
||||||
expression += char
|
|
||||||
elif should_calc and char.isalpha():
|
|
||||||
# don't include any more text in the calculation
|
|
||||||
break
|
|
||||||
if should_calc and not any(op in expression for op in ignore_operators):
|
|
||||||
try:
|
try:
|
||||||
result = str(eval(expression)) # pylint: disable = W0123
|
result = calculate(text)
|
||||||
except: # pylint: disable = W0702
|
msg(sender, "&2=== Calc:&6 %s" % result)
|
||||||
# we can run into all kinds of errors here
|
except:
|
||||||
# most probably SyntaxError
|
msg(sender, "&2=== Calc:&c Something went wrong while calculating - calulation aborted")
|
||||||
return None
|
|
||||||
return (expression, result)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
@hook.event("player.AsyncPlayerChatEvent", "monitor")
|
@hook.event("player.AsyncPlayerChatEvent", "monitor")
|
||||||
def on_calc_chat(event):
|
def on_calc_chat(event):
|
||||||
sender = event.getPlayer()
|
sender = event.getPlayer()
|
||||||
message = event.getMessage()
|
message = event.getMessage()
|
||||||
if not event.isCancelled() and uid(sender) in calc_users and sender.hasPermission(calc_perm):
|
if not event.isCancelled() and uid(sender) in calc_users and sender.hasPermission(calc_perm):
|
||||||
output = calc(message)
|
thread = threading.Thread(target=calc, args=(message, sender))
|
||||||
if output:
|
thread.daemon = True
|
||||||
msg(sender, "&2=== Calc: &e" + output[0] + " &2= &c" + output[1])
|
thread.start()
|
||||||
|
|
||||||
|
|
||||||
@hook.command("calc", description="Toggles chat calculations")
|
@hook.command("calc", description="Toggles chat calculations")
|
||||||
def on_calc_command(sender, command, label, args):
|
def on_calc_command(sender, command, label, args):
|
||||||
|
|||||||
Reference in New Issue
Block a user