#!/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 len(trigger.args) < 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 = ' '.join(trigger.args[1:]) 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." if output == None: output = "No plain text results found." output = output.replace('\n', ' | ') if not output: return query return f"\x0310{query} \x03= \x0312{output}"