From cbdf9ebd7312bf570a212057ad793ae520bac38f Mon Sep 17 00:00:00 2001 From: "Sean B. Palmer" Date: Sat, 23 Feb 2008 12:17:06 +0000 Subject: And some new modules too... --- modules/calc.py | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 modules/calc.py (limited to 'modules/calc.py') diff --git a/modules/calc.py b/modules/calc.py new file mode 100644 index 0000000..6768035 --- /dev/null +++ b/modules/calc.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# coding=utf-8 +""" +calc.py - Phenny Calculator Module +Copyright 2008, Sean B. Palmer, inamidst.com +Licensed under the Eiffel Forum License 2. + +http://inamidst.com/phenny/ +""" + +import re +import web + +r_result = re.compile(r'(?i)(.*?)') +r_tag = re.compile(r'<\S+.*?>') + +subs = [ + (' 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)') +] + +def calc(phenny, input): + q = input.group(2) + + query = q[:] + for a, b in subs: + query = re.sub(a, b, query) + query = query.rstrip(' \t') + + precision = 5 + if query[-3:] in ('GBP', 'USD', 'EUR', 'NOK'): + precision = 2 + query = web.urllib.quote(query.encode('utf-8')) + + uri = 'http://futureboy.homeip.net/fsp/frink.fsp?fromVal=' + bytes = web.get(uri + query) + m = r_result.search(bytes) + if m: + result = m.group(1) + result = r_tag.sub('', result) # strip span.warning tags + result = result.replace('>', '>') + result = result.replace('(undefined symbol)', '(?) ') + + if '.' in result: + try: result = str(round(float(result), precision)) + except ValueError: pass + + if not result.strip(): + result = '?' + elif ' in ' in q: + result += ' ' + q.split(' in ', 1)[1] + + phenny.say(q + ' = ' + result) + else: phenny.reply("Sorry, can't calculate that.") +calc.commands = ['calc'] + +if __name__ == '__main__': + print __doc__.strip() -- cgit v1.2.3-1-g7c22