2018-03-16 03:13:43 -04:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""
|
|
|
|
Querying Wolfram Alpha.
|
|
|
|
"""
|
|
|
|
import wolframalpha
|
|
|
|
|
2019-10-08 12:39:13 -04:00
|
|
|
import config
|
2018-03-16 03:13:43 -04:00
|
|
|
from module import commands, example
|
|
|
|
|
|
|
|
@commands('wa', 'wolfram')
|
|
|
|
@example('.wa 2+2', '[W|A] 2+2 = 4')
|
|
|
|
@example(".wa python language release date",
|
|
|
|
"[W|A] Python | date introduced = 1991")
|
|
|
|
def wa_command(bot, trigger):
|
|
|
|
"""
|
|
|
|
Queries WolframAlpha.
|
|
|
|
"""
|
|
|
|
if not trigger.group(2):
|
|
|
|
return bot.reply("You must provide a query.")
|
2019-10-08 12:39:13 -04:00
|
|
|
if not config.wolfram_app_id:
|
2018-03-16 03:13:43 -04:00
|
|
|
bot.reply("Wolfram|Alpha API app ID not configured.")
|
|
|
|
query = trigger.group(2).strip()
|
2019-10-08 12:39:13 -04:00
|
|
|
app_id = config.wolfram_app_id
|
|
|
|
units = config.wolfram_units
|
2018-03-16 03:13:43 -04:00
|
|
|
|
|
|
|
res = wa_query(query, app_id, units)
|
|
|
|
|
2018-05-25 15:21:18 -04:00
|
|
|
bot.msg(f"[\x0304Wolfram\x03] {res}")
|
2018-03-16 03:13:43 -04:00
|
|
|
|
|
|
|
|
|
|
|
def wa_query(query, app_id, units='nonmetric'):
|
|
|
|
"""Queries Wolfram."""
|
|
|
|
if not app_id:
|
|
|
|
return "Wolfram|Alpha API app ID not provided."
|
|
|
|
client = wolframalpha.Client(app_id)
|
|
|
|
params = (
|
|
|
|
('format', 'plaintext'),
|
|
|
|
('units', units),
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
res = client.query(input=query, params=params)
|
|
|
|
except AssertionError:
|
|
|
|
return "Temporary API issue. Try again in a moment."
|
|
|
|
except Exception as e:
|
|
|
|
print(e)
|
|
|
|
return "Error connecting to API. Please find an adult."
|
|
|
|
|
|
|
|
if int(res['@numpods']) == 0:
|
|
|
|
return "No results found."
|
|
|
|
|
|
|
|
texts = []
|
|
|
|
for pod in res.pods:
|
|
|
|
try:
|
|
|
|
texts.append(pod.text)
|
|
|
|
except AttributeError:
|
|
|
|
pass # pod with no text; skip it
|
|
|
|
except Exception as e:
|
|
|
|
print(e)
|
|
|
|
return "Weird result. Please find an adult."
|
|
|
|
if len(texts) >= 2:
|
|
|
|
break
|
|
|
|
# We only need two results (input and output)
|
|
|
|
|
|
|
|
try:
|
|
|
|
query, output = texts[0], texts[1]
|
|
|
|
except IndexError:
|
|
|
|
return "No text-representable result found."
|
|
|
|
|
|
|
|
output = output.replace('\n', ' | ')
|
|
|
|
if not output:
|
|
|
|
return query
|
|
|
|
return f"\x0310{query} \x03= \x0312{output}"
|