This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/plugins/wolframalpha.py

54 lines
1.3 KiB
Python
Raw Normal View History

2011-11-20 10:23:31 +01:00
import re
from util import hook, http
@hook.command('wa')
@hook.command
def wolframalpha(inp, bot=None):
2012-02-28 03:03:43 +01:00
".wa <query> -- Computes <query> using Wolfram Alpha."
2011-11-20 10:23:31 +01:00
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
if api_key is None:
return "error: no api key set"
2011-11-20 10:23:31 +01:00
url = 'http://api.wolframalpha.com/v2/query?format=plaintext'
2011-11-20 10:23:31 +01:00
result = http.get_xml(url, input=inp, appid=api_key)
2011-11-20 10:23:31 +01:00
pod_texts = []
for pod in result.xpath("//pod"):
title = pod.attrib['title']
if pod.attrib['id'] == 'Input':
2011-11-20 10:23:31 +01:00
continue
results = []
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:
pod_texts.append(title + ': ' + '|'.join(results))
2011-11-20 10:23:31 +01:00
ret = '. '.join(pod_texts)
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)
if len(ret) > 430:
ret = ret[:ret.rfind(' ', 0, 430)]
ret = re.sub(r'\W+$', '', ret) + '...'
if not ret:
2012-02-15 19:18:56 +01:00
return 'No results.'
2011-11-20 10:23:31 +01:00
return ret