def test_error_appid(self): """ Test error response of a faulty appid """ client = tungsten.Tungsten('XXXX') result = client.query('pi') self.assertFalse(result.success) self.assertEqual(result.error, 'Invalid appid')
def get_nutrition(keyword): client = tungsten.Tungsten(T_API_KEY) result = client.query(keyword + ' food') cal = 'N/A' ch = 'N/A' fat = 'N/A' protein = 'N/A' for pod in result.pods: if pod.title == 'Calories': r = pod.format['plaintext'][0] l = r.split(' | ') for i in range(len(l)): if len(l[i]) >= 8: if l[i][-8:] == 'calories': cal = l[i + 1] break if pod.title == 'Carbohydrates': r = pod.format['plaintext'][0] l = r.split(' | ') for i in range(len(l)): if len(l[i]) >= 8: if l[i][-13:] == 'carbohydrates': ch = l[i + 1] break if pod.title == 'Fats and fatty acids': r = pod.format['plaintext'][0] l = r.split(' | ') for i in range(len(l)): if len(l[i]) >= 5: if l[i][-3:] == 'fat': fat = l[i + 1] break if pod.title == 'Protein and amino acids': r = pod.format['plaintext'][0] l = r.split(' | ') for i in range(len(l)): if len(l[i]) >= 5: if l[i][-7:] == 'protein': protein = l[i + 1] break if pod.title == 'Input interpretation': r = pod.format['plaintext'][0] amount = r.split(' | ') message = '' for a in amount: message += a message += ' ' message += ',' message += 'Calories: {0}; Carbohydrates: {1}; Fat: {2}; Protein: {3}'.format( cal, ch, fat, protein) return message
def do(query): #plugins with multiple cmds get passed the query+which command was called query = query[0] client = tungsten.Tungsten('49RXE9-H5QE4L98V5') result_obj = client.query(query) message = "" for pod in result_obj.pods: print pod.scanner message = message + "\n" + str(pod.format['plaintext']) #Formatting message = message.replace('[', '').replace("'", '').replace(']', '').replace( r'\xd7', ' x ') return message
def wolf(self, args, token): if args != "": waclient = tungsten.Tungsten(token) res = waclient.query(args) additional = "" em = discord.Embed(title='Wolfram Alpha', description="Query: "+args, colour=0x007AFF) em.set_author(name='{0}\'s Result'.format(message_object.author.name)) em.set_footer(text="Wolfram Alpha Module", icon_url=self.pm.client.user.avatar_url) if res.success: for pod in res.pods: try: em.add_field(name=pod.title, value=pod.format.get('plaintext')[0]) except: pass return em else: return discord.Embed(title='Wolfram Alpha', description="No results!", colour=0x007AFF)
def test_pi(self): """ Test repsonse of a standard query, namely the API functionality """ client = tungsten.Tungsten(appid) result = client.query('pi') self.assertTrue(result.success) self.assertEqual(result.error, None) # Pod information expected to be returned expected_titles = ['Input', 'Decimal approximation', 'Property', 'Number line', 'Continued fraction', 'Alternative representations', 'Series representations', 'Integral representations'] expected_ids = ['Input', 'DecimalApproximation', 'Property', 'NumberLine', 'ContinuedFraction', 'AlternativeRepresentations:MathematicalFunctionIdentityData', 'SeriesRepresentations:MathematicalFunctionIdentityData', 'IntegralRepresentations:MathematicalFunctionIdentityData'] expected_scanners = ['Identity', 'Numeric', 'Numeric', 'NumberLine', 'ContinuedFraction', 'MathematicalFunctionData', 'MathematicalFunctionData', 'MathematicalFunctionData'] # Returned pod information titles = [pod.title for pod in result.pods] ids = [pod.id for pod in result.pods] scanners = [pod.scanner for pod in result.pods] self.assertEqual(titles, expected_titles) self.assertEqual(ids, expected_ids) self.assertEqual(scanners, expected_scanners)
def test_params(self): """ Test query / response of query with specified parameters """ client = tungsten.Tungsten(appid) # Parameters as list and as string params = {'format': ['minput', 'moutput'], 'scanner': 'numeric'} result = client.query('pi', params) for pod in result.pods: self.assertIn(pod.scanner, ['Numeric']) for format in pod.format: self.assertIn(format, ['minput', 'moutput']) self.assertEqual(result.pods[0].format['minput'], ['N[Pi, 79]']) self.assertEqual(result.pods[1].format['minput'], ['Element[Pi, Algebraics]'])
def run(keyConfig, message, totalResults=1): requestText = str(message).strip() client = tungsten.Tungsten(keyConfig.get('Wolfram', 'WOLF_APP_ID')) result = client.query(requestText) allAnswers = result.pods if len(allAnswers) > 0: fullAnswer = '' for question in allAnswers[0].format['plaintext']: if question is not None: fullAnswer += question + '?\n' if len(allAnswers) > 1: for pod in allAnswers[1:]: for answer in pod.format['plaintext']: if answer is not None: fullAnswer += answer + '.\n' result = 'Dave' + fullAnswer else: result = 'I\'m sorry Dave, I\'m afraid I can\'t find any answers for ' + str(requestText) return result
def wa_query(bot, trigger): if not trigger.group(2): return bot.say('[Wolfram] You must provide a query') client = tungsten.Tungsten(bot.config.wolfram.app_id) try: result = client.query(trigger.group(2)) except Exception as e: return bot.say('[Wolfram] An error occurred ({})'.format(e.message)) for pod in result.pods: if pod.id not in output_ids: continue return bot.say('{}: {}'.format(pod.title, pod.format['plaintext'][0])) if len(result.pods) > 0: return bot.say( '[Wolfram] No text-representable result found, see http://wolframalpha.com/input/?i={}' .format(web.quote(trigger.group(2)))) return bot.say('[Wolfram] No results found.')
def run(bot, chat_id, user, keyConfig, message, totalResults=1): requestText = str(message).strip() client = tungsten.Tungsten(keyConfig.get('Wolfram', 'WOLF_APP_ID')) result = client.query(requestText) allAnswers = result.pods if len(allAnswers) > 0 and 'plaintext' in allAnswers[0].format: fullAnswer = '' for question in allAnswers[0].format['plaintext']: if question is not None: fullAnswer += question + '?\n' if len(allAnswers) > 1: for pod in allAnswers[1:]: if 'plaintext' in pod.format: for answer in pod.format['plaintext']: if answer is not None: fullAnswer += answer + '.\n' result = (user + ': ' if not user == '' else '') + fullAnswer else: result = 'I\'m sorry ' + (user if not user == '' else 'Dave') + ', I\'m afraid I can\'t find any answers for '\ + str(requestText) bot.sendMessage(chat_id=chat_id, text=result)
def main(tg): # Read keys.ini file at program start (don't forget to put your keys in there!) keyConfig = configparser.ConfigParser() keyConfig.read(["keys.ini", "config.ini", "..\keys.ini", "..\config.ini"]) chat_id = tg.message['chat']['id'] message = tg.message['text'] user = tg.message['from']['username'] \ if not tg.message['from']['username'] == '' \ else tg.message['from']['first_name'] + (' ' + tg.message['from']['last_name']) \ if not tg.message['from']['last_name'] == '' \ else '' botName = tg.misc['bot_info']['username'] message = message.replace(botName, "") splitText = message.split(' ', 1) requestText = splitText[1] if ' ' in message else '' bot = telegram.Bot(keyConfig['BOT_CONFIG']['token']) client = tungsten.Tungsten(keyConfig.get('Wolfram', 'WOLF_APP_ID')) result = client.query(requestText) if len(result.pods) >= 1: fullAnswer = '' for pod in result.pods: for answer in pod.format['plaintext']: if not answer == None: fullAnswer += answer bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING) return bot.sendMessage(chat_id=chat_id, text=(user + ': ' if not user == '' else '') + fullAnswer) bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING) return bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \ ', I\'m afraid I can\'t find any answers for ' + \ requestText)
from pushbullet.pushbullet import Pushbullet #import wolframalpha import json import tungsten pb = Pushbullet(api_key="PUSHBULLET_API_KEY") wolf_api = "WOLFRAMALPHA_API_KEY" #client = wolframalpha.Client(wolf_api) client = tungsten.Tungsten(wolf_api) pushes = pb.get_pushes() f = open("sent.json") sent = json.loads(f.read()) f.close() for push in pushes: if 'body' in push.keys() and push['body'].startswith( 'Hey Jarvis') and push['iden'] not in sent: try: sent.append(push['iden']) res = client.query(push['body'][11:]) if res.success: print "Success" print[pod.format['plaintext'][0] for pod in res.pods] results = [ pod.format['plaintext'][0] for pod in res.pods if type(pod.format['plaintext'][0]) is not None ] if len(results) != 0: pb.push_note(title=push['body'][11:],
def onStart(s, a): global state, app, client, waApp state = s app = a client = tungsten.Tungsten("77QKHJ-R6QEKHE4YA") waApp = WolframAlpha()
import tungsten client = tungsten.Tungsten('LTQ79R-2QP6YAAJ9A') params = { 'format': ['plaintext', 'image'], 'scanner': 'data', 'units': 'metric' } result = client.query('How far is New York from Los Angeles', params) for pod in result.pods: print "scanner-->", pod.scanner print "ans-->", pod.format
def __init__(self): self.client = tungsten.Tungsten(self.app_id)