fulvia/modules/wolfram.py
2019-10-08 12:39:13 -04:00

74 lines
1.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Querying Wolfram Alpha.
"""
import wolframalpha
import config
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.")
if not config.wolfram_app_id:
bot.reply("Wolfram|Alpha API app ID not configured.")
query = trigger.group(2).strip()
app_id = config.wolfram_app_id
units = config.wolfram_units
res = wa_query(query, app_id, units)
bot.msg(f"[\x0304Wolfram\x03] {res}")
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}"