improved WA plugin (need to make it shorten once I make the web lib)
This commit is contained in:
parent
005bc0457e
commit
4777cfbcda
1 changed files with 14 additions and 9 deletions
|
@ -1,23 +1,28 @@
|
||||||
import re
|
import re
|
||||||
|
import urllib
|
||||||
|
|
||||||
from util import hook, http
|
from util import hook, http
|
||||||
|
|
||||||
|
|
||||||
@hook.command('wa')
|
@hook.command('wa')
|
||||||
@hook.command
|
@hook.command
|
||||||
def wolframalpha(inp, bot=None):
|
def wolframalpha(inp, bot=None):
|
||||||
".wa <query> -- Computes <query> using Wolfram Alpha."
|
".wa <query> -- Computes <query> using Wolfram Alpha."
|
||||||
|
|
||||||
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
|
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
|
||||||
if api_key is None:
|
|
||||||
return "error: no api key set"
|
if not api_key:
|
||||||
|
return "error: missing api key"
|
||||||
|
|
||||||
url = 'http://api.wolframalpha.com/v2/query?format=plaintext'
|
url = 'http://api.wolframalpha.com/v2/query?format=plaintext'
|
||||||
|
|
||||||
result = http.get_xml(url, input=inp, appid=api_key)
|
result = http.get_xml(url, input=inp, appid=api_key)
|
||||||
|
|
||||||
|
# get the URL for a user to view this query in a browser
|
||||||
|
query_url = "http://www.wolframalpha.com/input/?i=" + \
|
||||||
|
urllib.quote(inp.encode('utf-8'))
|
||||||
|
|
||||||
pod_texts = []
|
pod_texts = []
|
||||||
for pod in result.xpath("//pod"):
|
for pod in result.xpath("//pod[@primary='true']"):
|
||||||
title = pod.attrib['title']
|
title = pod.attrib['title']
|
||||||
if pod.attrib['id'] == 'Input':
|
if pod.attrib['id'] == 'Input':
|
||||||
continue
|
continue
|
||||||
|
@ -29,9 +34,9 @@ def wolframalpha(inp, bot=None):
|
||||||
if subpod:
|
if subpod:
|
||||||
results.append(subpod)
|
results.append(subpod)
|
||||||
if results:
|
if results:
|
||||||
pod_texts.append(title + ': ' + '|'.join(results))
|
pod_texts.append(title + ': ' + ','.join(results))
|
||||||
|
|
||||||
ret = '. '.join(pod_texts)
|
ret = ' | '.join(pod_texts)
|
||||||
|
|
||||||
if not pod_texts:
|
if not pod_texts:
|
||||||
return 'No results.'
|
return 'No results.'
|
||||||
|
@ -43,11 +48,11 @@ def wolframalpha(inp, bot=None):
|
||||||
|
|
||||||
ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)
|
ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)
|
||||||
|
|
||||||
if len(ret) > 430:
|
if len(ret) > 380:
|
||||||
ret = ret[:ret.rfind(' ', 0, 430)]
|
ret = ret[:ret.rfind(' ', 0, 380)]
|
||||||
ret = re.sub(r'\W+$', '', ret) + '...'
|
ret = re.sub(r'\W+$', '', ret) + '...'
|
||||||
|
|
||||||
if not ret:
|
if not ret:
|
||||||
return 'No results.'
|
return 'No results.'
|
||||||
|
|
||||||
return ret
|
return "%s - %s" % (ret, query_url)
|
||||||
|
|
Reference in a new issue