# HG changeset patch # User Teemu Piippo # Date 1417311570 -7200 # Node ID 84bd617a25204e5558082eec4d02a37046a99f0b # Parent 27294de7b0d30fb134e3765581aa1e567f695a44 - added .calc diff -r 27294de7b0d3 -r 84bd617a2520 mod_util.py --- 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': '', 'level': 'normal', }, + + { + 'name': 'calc', + 'description': 'Calculates a mathematical expression using apcalc', + 'args': '', + '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)