minetestbot-modules/calc.py

71 lines
1.8 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
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
2014-01-06 07:01:54 -08:00
class SomeObject(object):
pass
env = {
2014-01-06 11:40:40 -08:00
"bin": bin, "abs": abs, "oct": oct, "int": int, "sum": sum,
"tuple": tuple, "divmod": divmod, "hash": hash, "hex": hex,
"len": len, "list": list, "long": long, "max": max,
"range": range, "round": round, "min": min, "map": map,
"zip": zip, "xrange": xrange, "unicode": unicode,
"unichr": unichr, "type": type, "slice": slice, "ord": ord,
2014-03-08 11:06:52 -08:00
"chr": chr, "str": str, "float": float
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.")
q = input.group(2).encode('ascii', 'ignore')
if '__' in q:
2014-02-07 12:43:38 -08:00
return phenny.reply("Sorry, but no double underscores.")
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()
proc.join(2.0)
if proc.is_alive():
proc.terminate()
if 'math.pow' in q or '**' in q:
phenny.reply("Kindly go fuck yourself!")
antiabuse.ignore("*!*" + input.hostmask[input.hostmask.find("@"):])
log.log("action", "Auto-ignored %s for !c crash attempt" % log.fmt_user(input), phenny)
else:
phenny.reply("Took to long to calculate")
return
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-01-06 07:10:13 -08:00
print __doc__.strip()