bitbot-3.11-fork/modules/wolframalpha.py

44 lines
1.5 KiB
Python
Raw Normal View History

#--depends-on commands
#--require-config wolframalpha-api-key
import json
from src import ModuleManager, utils
2016-03-29 11:56:58 +00:00
URL_WA = "https://api.wolframalpha.com/v2/query"
2016-03-29 11:56:58 +00:00
class Module(ModuleManager.BaseModule):
2016-03-29 11:56:58 +00:00
_name = "Wolfram|Alpha"
@utils.hook("received.command.wa", alias_of="wolframalpha")
@utils.hook("received.command.wolframalpha", min_args=1)
2016-03-29 11:56:58 +00:00
def wa(self, event):
"""
2019-10-01 22:37:59 +00:00
:help: Evaluate a given string on Wolfram|Alpha
:usage: <query>
"""
query = event["args"].strip()
try:
page = utils.http.request(URL_WA, timeout=10, get_params={
"input": query, "format": "plaintext",
"output": "JSON", "reinterpret": "true", "units": "metric",
"appid": self.bot.config["wolframalpha-api-key"]}).json()
except utils.http.HTTPTimeoutException:
page = None
2016-03-29 11:56:58 +00:00
if page:
if page["queryresult"]["numpods"]:
input = query
primaries = []
for pod in page["queryresult"]["pods"]:
text = pod["subpods"][0]["plaintext"]
if pod["id"] == "Input" and text:
input = text.replace("\n", " | ")
elif pod.get("primary", False):
primaries.append(text)
event["stdout"].write("%s: %s" % (input, " | ".join(primaries)))
2016-03-29 11:56:58 +00:00
else:
event["stdout"].write("No results")
2016-03-29 11:56:58 +00:00
else:
raise utils.EventResultsError()