From 795c03a5ee6fbd8038aaa7defb3f31fb1f21adb3 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Tue, 19 Apr 2011 22:25:26 -0400 Subject: [PATCH] adding a calculator module, based on frink --- irc/commands/calc.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 irc/commands/calc.py diff --git a/irc/commands/calc.py b/irc/commands/calc.py new file mode 100644 index 0000000..ceaca78 --- /dev/null +++ b/irc/commands/calc.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- + +# A somewhat advanced calculator: http://futureboy.us/fsp/frink.fsp. + +import re +import urllib + +from irc.base_command import BaseCommand + +class Calc(BaseCommand): + def get_hooks(self): + return ["msg"] + + def get_help(self, command): + return "A somewhat advanced calculator: see http://futureboy.us/fsp/frink.fsp for details." + + def check(self, data): + if data.is_command and data.command == "calc": + return True + return False + + def process(self, data): + if not data.args: + self.connection.reply(data, "What do you want me to calculate?") + return + + query = ' '.join(data.args) + query = self.cleanup(query) + + url = "http://futureboy.us/fsp/frink.fsp?fromVal=%s" % urllib.quote(query) + result = urllib.urlopen(url).read() + + r_result = re.compile(r'(?i)(.*?)') + r_tag = re.compile(r'<\S+.*?>') + + match = r_result.search(result) + if not match: + self.connection.reply(data, "Calculation error.") + return + + result = match.group(1) + result = r_tag.sub("", result) # strip span.warning tags + result = result.replace(">", ">") + result = result.replace("(undefined symbol)", "(?) ") + result = result.strip() + + if not result: + result = '?' + elif " in " in query: + result += " " + query.split(" in ", 1)[1] + + res = "%s = %s" % (query, result) + self.connection.reply(data, res) + + def cleanup(self, query): + fixes = [ + (' in ', ' -> '), + (' over ', ' / '), + (u'£', 'GBP '), + (u'€', 'EUR '), + ('\$', 'USD '), + (r'\bKB\b', 'kilobytes'), + (r'\bMB\b', 'megabytes'), + (r'\bGB\b', 'kilobytes'), + ('kbps', '(kilobits / second)'), + ('mbps', '(megabits / second)') + ] + + for original, fix in fixes: + query = re.sub(original, fix, query) + return query.strip()