info = { 'author': 'Jon Bergli Heier', 'title': 'WolframAlpha', 'description': 'WolframAlpha', } import urllib, urllib2, re from lxml.etree import ElementTree whitespace_re = re.compile(r'\s+') class Module(object): config_section = 'module/wolframalpha' def __init__(self, bot): self.irc = bot if self.irc: self.irc.register_keyword('!wa', self) def keyword(self, nick, channel, kw, msg): target = channel if not channel == self.irc.nickname else nick.split('!')[0] if not len(msg.strip()): self.irc.msg(target, 'Usage: !wa query') return query = { 'appid': config.get(self.config_section, 'api_key'), 'format': 'plaintext', 'input': msg, } if config.has_option(self.config_section, 'location'): query['location'] = config.get(self.config_section, 'location') u = urllib2.urlopen('http://api.wolframalpha.com/v2/query?%s' % urllib.urlencode(query)) xmldoc = ElementTree() xmldoc.parse(u) xml = xmldoc.getroot() if xml.attrib['success'] != 'true': # TODO: check didyoumean tags self.irc.msg(target, 'No result.') return results = [] for pod in xml.findall('pod'): #if pod.attrib['id'] == 'Result': result = pod.find('subpod/plaintext') if result is not None and result.text is not None: text = result.text text = whitespace_re.sub(' ', text) results.append('\002%s\002: %s' % (pod.attrib['title'].encode('utf-8'), text.encode('utf-8'))) if len(results): self.irc.msg(target, ' '.join(results)) else: self.irc.msg(target, 'Something failed.')