2010-02-01 05:49:52 +00:00
|
|
|
import re
|
|
|
|
|
2010-04-23 03:47:41 +00:00
|
|
|
from util import hook, http
|
2010-02-01 05:49:52 +00:00
|
|
|
|
2010-03-01 02:32:41 +00:00
|
|
|
|
2010-02-01 05:49:52 +00:00
|
|
|
@hook.command('wa')
|
2010-05-07 23:16:44 +00:00
|
|
|
@hook.command
|
2012-02-10 21:04:05 +00:00
|
|
|
def wolframalpha(inp, bot=None):
|
|
|
|
".wa/.wolframalpha <query> -- computes <query> using Wolfram Alpha"
|
2010-02-01 05:49:52 +00:00
|
|
|
|
2012-02-10 21:04:05 +00:00
|
|
|
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
|
|
|
|
if api_key is None:
|
|
|
|
return "error: no api key set"
|
2010-02-01 05:49:52 +00:00
|
|
|
|
2012-02-10 21:04:05 +00:00
|
|
|
url = 'http://api.wolframalpha.com/v2/query?format=plaintext'
|
2010-02-01 05:49:52 +00:00
|
|
|
|
2012-02-10 21:04:05 +00:00
|
|
|
result = http.get_xml(url, input=inp, appid=api_key)
|
2010-02-01 05:49:52 +00:00
|
|
|
|
|
|
|
pod_texts = []
|
2012-02-10 21:04:05 +00:00
|
|
|
for pod in result.xpath("//pod"):
|
|
|
|
title = pod.attrib['title']
|
|
|
|
if pod.attrib['id'] == 'Input':
|
2010-02-02 04:52:09 +00:00
|
|
|
continue
|
|
|
|
|
2010-02-01 05:49:52 +00:00
|
|
|
results = []
|
2012-02-10 21:04:05 +00:00
|
|
|
for subpod in pod.xpath('subpod/plaintext/text()'):
|
|
|
|
subpod = subpod.strip().replace('\\n', '; ')
|
|
|
|
subpod = re.sub(r'\s+', ' ', subpod)
|
|
|
|
if subpod:
|
|
|
|
results.append(subpod)
|
2010-02-01 05:49:52 +00:00
|
|
|
if results:
|
2012-02-10 21:04:05 +00:00
|
|
|
pod_texts.append(title + ': ' + '|'.join(results))
|
2010-02-01 05:49:52 +00:00
|
|
|
|
2010-03-01 02:32:41 +00:00
|
|
|
ret = '. '.join(pod_texts)
|
2010-02-01 05:49:52 +00:00
|
|
|
|
2010-02-02 05:41:51 +00:00
|
|
|
if not pod_texts:
|
|
|
|
return 'no results'
|
2010-02-01 05:49:52 +00:00
|
|
|
|
2010-02-17 23:24:52 +00:00
|
|
|
ret = re.sub(r'\\(.)', r'\1', ret)
|
|
|
|
|
|
|
|
def unicode_sub(match):
|
|
|
|
return unichr(int(match.group(1), 16))
|
|
|
|
|
|
|
|
ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)
|
|
|
|
|
2010-03-01 02:32:41 +00:00
|
|
|
if len(ret) > 430:
|
2010-02-01 05:49:52 +00:00
|
|
|
ret = ret[:ret.rfind(' ', 0, 430)]
|
|
|
|
ret = re.sub(r'\W+$', '', ret) + '...'
|
|
|
|
|
|
|
|
if not ret:
|
2012-02-10 21:04:05 +00:00
|
|
|
return 'no results'
|
2010-02-01 05:49:52 +00:00
|
|
|
|
|
|
|
return ret
|