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.
|
|
|
|
"""
|
2020-01-07 18:58:19 -05:00
|
|
|
if len(trigger.args) < 2:
|
2018-03-16 03:13:43 -04:00
|
|
|
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.")
|
2020-01-07 18:58:19 -05:00
|
|
|
query = ' '.join(trigger.args[1:])
|
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."
|
2022-03-21 07:12:23 -04:00
|
|
|
if output == None:
|
|
|
|
output = "No plain text results found."
|
2018-03-16 03:13:43 -04:00
|
|
|
|
|
|
|
output = output.replace('\n', ' | ')
|
|
|
|
if not output:
|
|
|
|
return query
|
|
|
|
return f"\x0310{query} \x03= \x0312{output}"
|