2018-08-31 09:50:37 +00:00
|
|
|
# --require-config wolframalpha-api-key
|
2016-03-30 18:31:23 +00:00
|
|
|
|
2016-03-29 11:56:58 +00:00
|
|
|
import re
|
|
|
|
import Utils
|
|
|
|
|
|
|
|
URL_WA = "http://api.wolframalpha.com/v2/query"
|
|
|
|
REGEX_CHARHEX = re.compile("\\\\:(\S{4})")
|
|
|
|
|
2018-08-31 09:50:37 +00:00
|
|
|
|
2016-03-29 11:56:58 +00:00
|
|
|
class Module(object):
|
|
|
|
_name = "Wolfram|Alpha"
|
2018-08-31 09:50:37 +00:00
|
|
|
|
2016-03-29 11:56:58 +00:00
|
|
|
def __init__(self, bot):
|
|
|
|
bot.events.on("received").on("command").on("wolframalpha", "wa"
|
2018-08-31 09:50:37 +00:00
|
|
|
).hook(self.wa, min_args=1,
|
|
|
|
help=
|
|
|
|
"Evauate a given string on Wolfram|Alpha",
|
|
|
|
usage="<query>")
|
2016-03-29 11:56:58 +00:00
|
|
|
self.bot = bot
|
|
|
|
|
|
|
|
def wa(self, event):
|
|
|
|
soup = Utils.get_url(URL_WA, get_params={"input": event["args"],
|
2018-08-31 09:50:37 +00:00
|
|
|
"appid": self.bot.config[
|
|
|
|
"wolframalpha-api-key"],
|
|
|
|
"format": "plaintext",
|
|
|
|
"reinterpret": "true"},
|
|
|
|
soup=True)
|
2016-03-29 11:56:58 +00:00
|
|
|
|
|
|
|
if soup:
|
|
|
|
if int(soup.find("queryresult").get("numpods")) > 0:
|
|
|
|
input = soup.find(id="Input").find("subpod").find("plaintext"
|
2018-08-31 09:50:37 +00:00
|
|
|
).text
|
2016-03-30 18:31:23 +00:00
|
|
|
answered = False
|
2016-03-29 11:56:58 +00:00
|
|
|
for pod in soup.find_all("pod"):
|
|
|
|
if pod.get("primary") == "true":
|
|
|
|
answer = pod.find("subpod").find("plaintext")
|
|
|
|
text = "(%s) %s" % (input.replace(" | ", ": "),
|
2018-08-31 09:50:37 +00:00
|
|
|
answer.text.strip().replace(" | ",
|
|
|
|
": "
|
|
|
|
).replace(
|
|
|
|
"\n", " | ").replace("\r", ""))
|
2016-03-29 11:56:58 +00:00
|
|
|
while True:
|
|
|
|
match = re.search(REGEX_CHARHEX, text)
|
|
|
|
if match:
|
|
|
|
text = re.sub(REGEX_CHARHEX, chr(int(
|
|
|
|
match.group(1), 16)), text)
|
|
|
|
else:
|
|
|
|
break
|
2016-03-30 18:31:23 +00:00
|
|
|
answered = True
|
2016-03-29 11:56:58 +00:00
|
|
|
event["stdout"].write(text)
|
|
|
|
break
|
2016-03-30 18:31:23 +00:00
|
|
|
if not answered:
|
|
|
|
event["stderr"].write("No results found")
|
2016-03-29 11:56:58 +00:00
|
|
|
else:
|
|
|
|
event["stderr"].write("No results found")
|
|
|
|
else:
|
|
|
|
event["stderr"].write("Failed to load results")
|