[ddg/wolframalpha] extract wolframalpha module and dusting

This commit is contained in:
nemunaire 2015-06-03 21:05:28 +02:00
commit 2e55ba5671
3 changed files with 39 additions and 43 deletions

View file

@ -1,71 +0,0 @@
# coding=utf-8
from urllib.parse import quote
from nemubot.tools import web
class WFASearch:
def __init__(self, terms):
self.terms = terms
try:
url = ("http://api.wolframalpha.com/v2/query?input=%s&appid=%s" %
(quote(terms), CONF.getNode("wfaapi")["key"]))
self.wfares = web.getXML(url)
except (TypeError, KeyError):
print ("You need a Wolfram|Alpha API key in order to use this "
"module. Add it to the module configuration file:\n<wfaapi"
" key=\"XXXXXX-XXXXXXXXXX\" />\nRegister at "
"http://products.wolframalpha.com/api/")
self.wfares = None
@property
def success(self):
try:
return self.wfares["success"] == "true"
except:
return False
@property
def error(self):
if self.wfares is None:
return "An error occurs during computation."
elif self.wfares["error"] == "true":
return ("An error occurs during computation: " +
self.wfares.getNode("error").getNode("msg").getContent())
elif self.wfares.hasNode("didyoumeans"):
start = "Did you mean: "
tag = "didyoumean"
end = "?"
elif self.wfares.hasNode("tips"):
start = "Tips: "
tag = "tip"
end = ""
elif self.wfares.hasNode("relatedexamples"):
start = "Related examples: "
tag = "relatedexample"
end = ""
elif self.wfares.hasNode("futuretopic"):
return self.wfares.getNode("futuretopic")["msg"]
else:
return "An error occurs during computation"
proposal = list()
for dym in self.wfares.getNode(tag + "s").getNodes(tag):
if tag == "tip":
proposal.append(dym["text"])
elif tag == "relatedexample":
proposal.append(dym["desc"])
else:
proposal.append(dym.getContent())
return start + ', '.join(proposal) + end
@property
def nextRes(self):
try:
for node in self.wfares.getNodes("pod"):
for subnode in node.getNodes("subpod"):
if subnode.getFirstNode("plaintext").getContent() != "":
yield (node["title"] + " " + subnode["title"] + ": " +
subnode.getFirstNode("plaintext").getContent())
except IndexError:
pass

View file

@ -13,17 +13,6 @@ from more import Response
from . import DDGSearch
from . import UrbanDictionnary
from . import WFASearch
def load(context):
WFASearch.CONF = context.config
def reload():
imp.reload(DDGSearch)
imp.reload(UrbanDictionnary)
imp.reload(WFASearch)
imp.reload(Wikipedia)
@hook("cmd_hook", "define")
def define(msg):
@ -76,22 +65,3 @@ def udsearch(msg):
res.append_message(d)
return res
@hook("cmd_hook", "calculate")
def calculate(msg):
if len(msg.cmds) <= 1:
return Response("Indicate a calcul to compute",
msg.channel, nick=msg.nick)
s = WFASearch.WFASearch(' '.join(msg.cmds[1:]))
if s.success:
res = Response(channel=msg.channel, nomore="No more results")
for result in s.nextRes:
res.append_message(result)
if (len(res.messages) > 0):
res.messages.pop(0)
return res
else:
return Response(s.error, msg.channel)