Advertisement
urbanslug

mudule_wolfram.py

Oct 22nd, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. from __future__ import unicode_literals, print_function, division
  2. import urllib
  3. import logging
  4. import re
  5.  
  6. log = logging.getLogger('wolfram_alpha')
  7.  
  8. try:
  9. from lxml import etree
  10. log.debug("running with lxml.etree")
  11. except ImportError:
  12. log.debug("module_wolfram_alpha requires lxml.etree for xpath support")
  13.  
  14. appid = None
  15. query = "http://api.wolframalpha.com/v2/query?input=%s&appid=%s"
  16.  
  17.  
  18. def init(bot):
  19. global appid
  20. config = bot.config.get("module_wolfram_alpha", {})
  21. appid = config.get("appid", "")
  22. if appid:
  23. log.info("Using Wolfram Alpha appid %s" % appid)
  24. else:
  25. log.warning("Appid not found from config!")
  26.  
  27.  
  28. def command_wa(bot, user, channel, args):
  29. """Query Wolfram Alpha"""
  30. if not appid:
  31. log.warn("Appid not specified in configuration!")
  32. return
  33.  
  34. r = bot.get_url(query % (urllib.quote(args.encode('utf-8')), appid))
  35.  
  36. if r.status_code != 200:
  37. return
  38.  
  39. root = etree.fromstring(r.content)
  40. # find all pods
  41. pods = root.findall("pod")
  42.  
  43. # no answer pods found, check if there are didyoumeans-elements
  44. if not pods:
  45. didyoumeans = root.find("didyoumeans")
  46. # no support for future stuff yet, TODO?
  47. if not didyoumeans:
  48. return
  49.  
  50. options = []
  51. for didyoumean in didyoumeans:
  52. options.append("'%s'" % didyoumean.text)
  53. line = " or ".join(options)
  54. line = "Did you mean %s?" % line
  55. return bot.say(channel, line.encode("UTF-8"))
  56.  
  57. # first pod has the question as WA sees it
  58. question = pods[0].xpath("subpod/plaintext")[0].text.replace(' | ', ' ').replace('\n', ' ')
  59. # second one has the best answer
  60. answer = pods[1].xpath("subpod/plaintext")[0].text.replace(' | ', ': ').replace('\n', ' | ')
  61.  
  62. # First strip the question and answer of empty chars, then compress multiple spaces to one
  63. line = re.sub("[ ]{2,}", " ", "%s - %s" % (question.strip(), answer.strip()))
  64. return bot.say(channel, line.encode("UTF-8"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement