sopel/modules/wolfram.py

82 lines
2.3 KiB
Python
Executable File

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Wolfram|Alpha module for Sopel IRC bot framework
Forked from code by Max Gurela (@maxpowa):
https://github.com/maxpowa/inumuta-modules/blob/e0b195c4f1e1b788fa77ec2144d39c4748886a6a/wolfram.py
Updated and packaged for PyPI by dgw (@dgw)
"""
from config.types import StaticSection, ChoiceAttribute, ValidatedAttribute
from module import commands, example
import wolframalpha
@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.
"""
msg = None
if not trigger.group(2):
msg = 'You must provide a query.'
if not bot.config.wolfram.app_id:
msg = 'Wolfram|Alpha API app ID not configured.'
lines = (msg or wa_query(bot.config.wolfram.app_id, trigger.group(2), bot.config.wolfram.units)).splitlines()
for line in lines:
bot.say('[\x0304Wolfram\x03] {}'.format(line))
def wa_query(app_id, query, units='nonmetric'):
if not app_id:
return 'Wolfram|Alpha API app ID not provided.'
client = wolframalpha.Client(app_id)
query = query.encode('utf-8').strip()
params = (
('format', 'plaintext'),
('units', units),
)
try:
result = client.query(input=query, params=params)
except AssertionError:
return 'Temporary API issue. Try again in a moment.'
except Exception as e:
return 'Query failed: {} ({})'.format(type(e).__name__, e.message or 'Unknown error, try again!')
num_results = 0
try:
num_results = int(result['@numpods'])
finally:
if num_results == 0:
return 'No results found.'
texts = []
try:
for pod in result.pods:
try:
texts.append(pod.text)
except AttributeError:
pass # pod with no text; skip it
except Exception:
raise # raise unexpected exceptions to outer try for bug reports
if len(texts) >= 2:
break # len() is O(1); this cheaply avoids copying more strings than needed
except Exception as e:
return 'Unhandled {}; please report this query ("{}") at https://dgw.me/wabug'.format(type(e).__name__, query)
try:
input, output = texts[0], texts[1]
except IndexError:
return 'No text-representable result found; see http://wolframalpha.com/input/?i={}'.format(query)
output = output.replace('\n', ' | ')
if not output:
return input
return '\x0310{} \x03= \x0312{}'.format(input, output)