Sun, 30 Nov 2014 03:39:30 +0200
- added .calc
mod_util.py | file | annotate | diff | comparison | revisions |
--- a/mod_util.py Sat Nov 29 10:45:51 2014 -0500 +++ b/mod_util.py Sun Nov 30 03:39:30 2014 +0200 @@ -1,6 +1,8 @@ import math import urllib2 import json +import subprocess +import re from modulecore import command_error import modulecore as ModuleCore @@ -34,6 +36,13 @@ 'args': '<command>', 'level': 'normal', }, + + { + 'name': 'calc', + 'description': 'Calculates a mathematical expression using apcalc', + 'args': '<expression...>', + 'level': 'normal', + }, ] } @@ -108,3 +117,31 @@ command_error ('you may not use %s' % cmd['name']) bot.privmsg (replyto, '%s %s: %s' % (cmd['name'], cmd['args'], cmd['description'])) + +def cmd_calc (bot, replyto, args, **rest): + expr = args['expression'] + + try: + # I want pi around so yeah + pirex = re.compile (r'^(.*)\bpi\b(.*)$') + match = pirex.match (expr) + + while match: + expr = match.group(1) + '3.14159265358979323846264338327950288' + match.group(2) + match = pirex.match (expr) + + result = subprocess.check_output (['calc', expr], stderr=subprocess.STDOUT) \ + .replace ('\t', '') \ + .replace ('\n', '') + + errmatch = re.compile (r'^.*\bError\b.*$').match (result) + + if errmatch: + command_error ('math error') + return + + bot.privmsg (replyto, 'Result: %s' % result) + except subprocess.CalledProcessError as e: + command_error (e.output.split('\n')[0]) + except OSError as e: + command_error ('failed to execute calc: ' + e.strerror)