2011-11-20 10:23:31 +01:00
|
|
|
import re
|
|
|
|
|
2012-10-13 00:49:42 +02:00
|
|
|
from util import hook, http, text, web
|
2012-04-21 06:03:08 +02:00
|
|
|
|
|
|
|
|
2011-11-20 10:23:31 +01:00
|
|
|
@hook.command('wa')
|
|
|
|
@hook.command
|
2012-02-15 19:01:41 +01:00
|
|
|
def wolframalpha(inp, bot=None):
|
2012-05-16 05:07:27 +02:00
|
|
|
"wa <query> -- Computes <query> using Wolfram Alpha."
|
2011-11-20 10:23:31 +01:00
|
|
|
|
2012-02-15 19:01:41 +01:00
|
|
|
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
|
2012-04-21 18:26:24 +02:00
|
|
|
|
2012-04-20 17:36:06 +02:00
|
|
|
if not api_key:
|
|
|
|
return "error: missing api key"
|
2011-11-20 10:23:31 +01:00
|
|
|
|
2012-02-15 19:01:41 +01:00
|
|
|
url = 'http://api.wolframalpha.com/v2/query?format=plaintext'
|
2011-11-20 10:23:31 +01:00
|
|
|
|
2012-02-15 19:01:41 +01:00
|
|
|
result = http.get_xml(url, input=inp, appid=api_key)
|
2012-04-21 18:26:24 +02:00
|
|
|
|
2012-04-20 17:36:06 +02:00
|
|
|
# get the URL for a user to view this query in a browser
|
|
|
|
query_url = "http://www.wolframalpha.com/input/?i=" + \
|
2012-10-13 00:49:42 +02:00
|
|
|
http.quote_plus(inp.encode('utf-8'))
|
2012-04-21 06:03:08 +02:00
|
|
|
try:
|
2012-10-13 00:49:42 +02:00
|
|
|
short_url = web.isgd(query_url)
|
2012-10-13 01:10:02 +02:00
|
|
|
except (web.ShortenError, http.HTTPError):
|
2012-04-21 06:03:08 +02:00
|
|
|
short_url = query_url
|
2011-11-20 10:23:31 +01:00
|
|
|
|
|
|
|
pod_texts = []
|
2012-04-20 17:36:06 +02:00
|
|
|
for pod in result.xpath("//pod[@primary='true']"):
|
2012-02-15 19:01:41 +01:00
|
|
|
title = pod.attrib['title']
|
|
|
|
if pod.attrib['id'] == 'Input':
|
2011-11-20 10:23:31 +01:00
|
|
|
continue
|
|
|
|
|
|
|
|
results = []
|
2012-02-15 19:01:41 +01: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)
|
2011-11-20 10:23:31 +01:00
|
|
|
if results:
|
2012-04-23 11:41:51 +02:00
|
|
|
pod_texts.append(title + ': ' + ', '.join(results))
|
2011-11-20 10:23:31 +01:00
|
|
|
|
2012-04-21 18:26:24 +02:00
|
|
|
ret = ' - '.join(pod_texts)
|
2011-11-20 10:23:31 +01:00
|
|
|
|
|
|
|
if not pod_texts:
|
2012-02-15 19:18:56 +01:00
|
|
|
return 'No results.'
|
2011-11-20 10:23:31 +01: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)
|
|
|
|
|
2012-10-13 00:49:42 +02:00
|
|
|
ret = text.truncate_str(ret, 250)
|
|
|
|
|
2011-11-20 10:23:31 +01:00
|
|
|
if not ret:
|
2012-02-15 19:18:56 +01:00
|
|
|
return 'No results.'
|
2011-11-20 10:23:31 +01:00
|
|
|
|
2012-04-21 06:03:08 +02:00
|
|
|
return "%s - %s" % (ret, short_url)
|