minetestbot-modules/calc.py

80 lines
2.0 KiB
Python
Raw Normal View History

2013-01-07 10:00:44 -08:00
#!/usr/bin/env python
# coding=utf-8
"""
calc.py - Phenny Calculator Module
2014-01-06 07:01:54 -08:00
Copyright 2014, sfan5
Licensed under GNU General Public License v2.0
2013-01-07 10:00:44 -08:00
"""
2014-01-06 07:01:54 -08:00
import math
2014-01-18 08:36:09 -08:00
import random
2014-03-08 11:06:52 -08:00
import struct
2014-07-19 11:13:28 -07:00
import multiprocessing
from functools import reduce
2014-01-06 07:01:54 -08:00
class SomeObject(object):
pass
env = {
2014-07-20 07:13:59 -07:00
"abs": abs, "all": all, "any": any,
"ascii": ascii, "bin": bin, "bool": bool,
"bytearray": bytearray, "bytes": bytes,
"callable": callable, "chr": chr,
"complex": complex, "dict": dict,
"divmod": divmod, "enumerate": enumerate,
"filter": filter, "float": float,
"format": format, "frozenset": frozenset,
"hex": hex, "int": int,
2014-07-20 07:13:59 -07:00
"iter": iter, "len": len, "list": list,
"map": map, "max": max, "min": min,
"next": next,"oct": oct,
"ord": ord, "pow": pow, "range": range,
"reduce": reduce, "repr": repr,
2014-07-20 07:13:59 -07:00
"reversed": reversed, "round": round,
"set": set, "slice": slice,
"sorted": sorted, "str": str,
"sum": sum, "tuple": tuple,
"type": type, "zip": zip,
2014-01-06 11:40:40 -08:00
}
2014-01-06 07:01:54 -08:00
libs = [
2014-03-08 11:06:52 -08:00
'math', 'random', 'struct'
]
2014-01-06 11:40:40 -08:00
for lib in libs:
env[lib] = SomeObject()
for funcn in dir(globals()[lib]):
if funcn.startswith("_"):
continue
setattr(env[lib], funcn, getattr(globals()[lib], funcn))
2014-01-06 07:01:54 -08:00
def c(phenny, input):
if not input.group(2):
return phenny.reply("Nothing to calculate.")
2014-07-20 07:13:59 -07:00
q = input.group(2)
if '__' in q:
2015-10-01 13:16:11 -07:00
return phenny.reply("Sorry, double underscores are not allowed.")
2014-07-19 11:13:28 -07:00
log.log("event", "%s calculated '%s'" % (log.fmt_user(input), q), phenny)
o = multiprocessing.Queue()
def get_result(o, q):
try:
o.put(repr(eval(q, {'__builtins__': env}, {})))
except Exception as e:
o.put(type(e).__name__ + ": " + str(e))
proc = multiprocessing.Process(target=get_result, args=(o,q))
proc.start()
2015-10-01 13:16:11 -07:00
proc.join(3.0)
2014-07-19 11:13:28 -07:00
if proc.is_alive():
2015-10-01 13:16:11 -07:00
proc.terminate()
log.log("action", "Calculation by %s timed out." % log.fmt_user(input), phenny)
phenny.reply("Took to long to calculate")
2014-07-19 11:13:28 -07:00
else:
phenny.say(o.get())
2014-01-06 07:01:54 -08:00
2013-01-07 10:00:44 -08:00
c.commands = ['c']
c.example = '.c 5 + 3'
if __name__ == '__main__':
2014-07-20 07:13:59 -07:00
print(__doc__.strip())