- added .calc

Sun, 30 Nov 2014 03:39:30 +0200

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Sun, 30 Nov 2014 03:39:30 +0200
changeset 105
84bd617a2520
parent 104
27294de7b0d3
child 106
31583e5b2f49

- 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)

mercurial