#!/usr/bin/env python import string, math, cmath, sys import types, signal, StringIO def get_commands (bot): return { "calc": evalmath, "mathinit": mathinit, } mathenv = None def mathalarm (sig, frame): raise RuntimeError, "calculation took too long" def mathinit (msg, args): global mathenv mathenv = {} for i in dir (math): if i[:2] != '__': mathenv[i] = getattr (math, i) for i in dir (cmath): if i[:2] != '__': mathenv[i] = getattr (cmath, i) mathenv['pow'] = pow def evalmath (msg, args): global mathenv if not mathenv: mathinit (msg, args) mathenv ["__builtins__"] = {} if not msg.command: return mathstuff = string.strip (args) if not mathstuff: return code = None result = None error = None try: code = compile (mathstuff, "", 'eval') except: try: code = compile (mathstuff, "", 'single') except: exc = sys.exc_info () error = exc[0].__name__ + ": " + str (exc[1]) if not error: tmptxt = StringIO.StringIO () try: oldalrm = signal.signal (signal.SIGALRM, mathalarm) signal.alarm (2) oldstdout = sys.stdout sys.stdout = tmptxt try: result = eval (code, mathenv) if type (result) == types.ComplexType and result.imag == 0: result = result.real except: exc = sys.exc_info () error = getattr (exc[0], '__name__', str (exc[0])) if exc[1]: error = error + ": " + str (exc[1]) finally: signal.alarm (0) signal.signal (signal.SIGALRM, oldalrm) sys.stdout = oldstdout textresult = tmptxt.getvalue() if result == None: if string.strip (textresult): result = string.strip (textresult) result = "".join (string.split (result, '\r')) result = " ; ".join (string.split (result, '\n')) else: result = "Ok!" result = str (result) if error: msg.client.reply (msg, error) else: msg.client.reply (msg, result)