def process(input, entities): output = {} try: query = entities['wiki'][0]['value'] data = wikipedia.page(query) output['input'] = input template = TextTemplate('Wikipedia summary of ' + data.title + ':\n' + data.summary) text = template.get_text() template = ButtonTemplate(text) template.add_web_url('Wikipedia Link', data.url) output['output'] = template.get_message() output['success'] = True except wikipedia.exceptions.DisambiguationError as e: template = GenericTemplate() image_url = 'https://en.wikipedia.org/static/images/project-logos/enwiki-2x.png' pageids = set() for option in e.options: try: data = wikipedia.page(option) if data.pageid in pageids: continue pageids.add(data.pageid) buttons = ButtonTemplate() buttons.add_web_url('Wikipedia Link', data.url) payload = { 'intent': 'wiki', 'entities': { 'wiki': [ { 'value': option } ] } } buttons.add_postback('Wikipedia Summary', json.dumps(payload)) template.add_element(title=data.title, item_url=data.url, image_url=image_url, buttons=buttons.get_buttons()) except (wikipedia.exceptions.PageError, wikipedia.exceptions.DisambiguationError): pass # Some suggestions don't map to a page; skipping them.. output['input'] = input output['output'] = template.get_message() output['success'] = True except: error_message = 'I couldn\'t find any wikipedia results matching your query.' error_message += '\nPlease ask me something else, like:' error_message += '\n - wikipedia barack' error_message += '\n - html wiki' error_message += '\n - who is sachin tendulkar' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input, entities=None): help = '''\n Hi there. I'm Jarvis, your personal assistant.\nTell me things like the following:\n - define a superhero\n - iron man 2 movie plot\n - tell me a joke\n - wiki html\n - anything you want book\n - random quote\n I'm always learning, so do come back and say hi from time to time!\nHave a nice day.\n ''' output = { 'input': input, 'output': TextTemplate(help).get_message(), 'success': True } return output
def process(input, entities=None): request = ''' Kindly head over to https://github.com/swapagarwal/JARVIS-on-Messenger/issues/new to:\n - Report a bug (I couldn't handle the query and/or gave unexpected results), by including your search query and the expected result.\n - Request a new feature, by including some sample queries and their expected results.\n ''' output = { 'input': input, 'output': TextTemplate(request).get_message(), 'success': True } return output
def process(input, entities): output = {} try: r = requests.get('http://open.mapquestapi.com/nominatim/v1/search.php?key=' + MAPQUEST_CONSUMER_KEY + '&format=json&q='+ entities['weather_location'][0]['value'] + '&limit=1') location_data = r.json() r = requests.get('http://api.openweathermap.org/data/2.5/weather?lat='+ location_data[0]['lat'] + '&lon='+ location_data[0]['lon'] + '&units=metric&appid=' + OPEN_WEATHER_MAP_ACCESS_TOKEN) weather_data = r.json() output['input'] = input temperature_in_fahrenheit = weather_data['main']['temp'] * 1.8 + 32 degree_sign = u'\N{DEGREE SIGN}' output['output'] = TextTemplate('Location: ' + location_data[0]['display_name'] + '\nWeather: ' + weather_data['weather'][0]['description'] + '\nTemperature: ' + str(weather_data['main']['temp']) + ' ' + degree_sign + 'C / ' + str(temperature_in_fahrenheit) + ' ' + degree_sign + 'F\n- Info provided by OpenWeatherMap').get_message() output['success'] = True except: error_message = 'I couldn\'t get the weather info you asked for.' error_message += '\nPlease ask me something else, like:' error_message += '\n - tell me the weather in London' error_message += '\n - weather Delhi' error_message += '\n - What\'s the weather in Texas?' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input, entities=None): output = {} try: r = requests.get('http://numbersapi.com/random/trivia', headers={'Content-Type': 'application/json'}) data = r.json() output['input'] = input output['output'] = TextTemplate(data['text']).get_message() output['success'] = True except: output['success'] = False return output
def process(input): output = {} try: with open(config.QUOTES_SOURCE_FILE) as quotes_file: quotes = json.load(quotes_file) quotes_list = quotes['quotes'] output['input'] = input output['output'] = TextTemplate(choice(quotes_list)).get_message() output['success'] = True except: output['success'] = False return output
def process(input): output = {} try: with open(config.JOKES_SOURCE_FILE) as jokes_file: jokes = json.load(jokes_file) jokes_list = jokes['jokes'] output['input'] = input output['output'] = TextTemplate(choice(jokes_list)).get_message() output['success'] = True except: output['success'] = False return output
def process(input, entities): output = {} try: query = entities['wikipedia_search_query'][0]['value'] data = wikipedia.summary(query) output['input'] = input output['output'] = TextTemplate('Wikipedia Summary: ' + data).get_message() output['success'] = True except: output['success'] = False return output
def process(input, entities=None): messages = [ u"\u2764", # Red Heart Emoji 'You are welcome!', 'No problem. Will that be all?', ] output = { 'input': input, 'output': TextTemplate(random.choice(messages)).get_message(), 'success': True } return output
def process(input, entities): output = {} try: word = entities['word'][0]['value'] with requests_cache.enabled('dictionary_cache', backend='sqlite', expire_after=86400): r = requests.get('https://wordsapiv1.p.mashape.com/words/' + word + '/definitions', headers={'X-Mashape-Key': WORDS_API_KEY}) data = r.json() output['input'] = input output['output'] = TextTemplate( 'Definition of ' + word + ':\n' + data['definitions'][0]['definition']).get_message() output['success'] = True except: error_message = QUERY_ERROR.format('definition') + EXAMPLE_DEFINITIONS output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def search(input, sender=None, postback=False): x=input.split(' ') if x[0]=='mail' or x[0]=='solve': intent=x[0] entities=None elif postback: payload = json.loads(input) intent = payload['intent'] entities = payload['entities'] else: intent, entities = process_query(input) if intent is not None: if intent in src.__personalized__ and sender is not None: r = requests.get('https://graph.facebook.com/v2.6/' + str(sender), params={ 'fields': 'first_name', 'access_token': os.environ.get('ACCESS_TOKEN', config.ACCESS_TOKEN) }) if entities is None: entities = {} entities['sender'] = r.json() if intent=='mail' or intent=='solve' : if intent=='mail': sys.modules['modules.src.' + 'mail'].process(x[1],input) return TextTemplate('DATA SENT').get_message() else: k=sys.modules['modules.src.' + 'solve'].process(x[1]) return TextTemplate(k).get_message() else: data = sys.modules['modules.src.' +intent].process(intent,entities) if data['success']: return data['output'] else: if 'error_msg' in data: return data['error_msg'] else: return TextTemplate('Something didn\'t work as expected! I\'ll report this to my master.').get_message() else: return TextTemplate( 'I\'m sorry; I\'m not sure I uncccderstand what you\'re trying to say.\nTry typing "help" or "request"').get_message()
def process(input, entities): output = {} try: # math = entities['math'][0]['value'] app_id = "QQX2TL-VJ2HWY454T" client = wolframalpha.Client(app_id) response = "1*2" # res = client.query(response) input = input.replace("math", "") res = client.query(input) texts = "" counter = 0 for pod in res.pods: #if counter == 0: # texts = "input: " + pod.text + "\n" # texts = texts.encode('ascii', 'ignore') if counter > 0: texts += pod.text break counter += 1 #texts = texts.encode('ascii', 'ignore') #print(texts) #output['input'] = input output['input'] = '' output['output'] = TextTemplate('Result from WolframAlpha: ' + texts).get_message() #output['output'] = texts output['success'] = True except: error_message = 'I couldn\'t get the right answer for that.' error_message += '\nPlease ask me something else, like:' error_message += '\n - 3/2' error_message += '\n - 5 squared' error_message += '\n - 5*3' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def search(input, sender=None, postback=False): if postback: payload = json.loads(input) intent = payload['intent'] entities = payload['entities'] else: intent, entities = process_query(input) # TODO: Needs to be refactored out try: keen.project_id = os.environ.get('KEEN_PROJECT_ID', config.KEEN_PROJECT_ID) keen.write_key = os.environ.get('KEEN_WRITE_KEY', config.KEEN_WRITE_KEY) keen.add_event('logs', { 'intent': intent, 'entities': entities, 'input': input, 'sender': sender, 'postback': postback }) except: pass # Could not stream data for analytics if intent is not None: if intent in src.__personalized__ and sender is not None: r = requests.get('https://graph.facebook.com/v2.6/' + str(sender), params={ 'fields': 'first_name', 'access_token': os.environ.get('ACCESS_TOKEN', config.ACCESS_TOKEN) }) if entities is None: entities = {} entities['sender'] = r.json() data = sys.modules['modules.src.' + intent].process(input, entities) if data['success']: return data['output'] else: if 'error_msg' in data: return data['error_msg'] else: return TextTemplate('Something didn\'t work as expected! I\'ll report this to my master.').get_message() else: return TextTemplate( 'I\'m sorry; I\'m not sure I understand what you\'re trying to say.\nTry typing "help" or "request"').get_message()
def process(input, entities): output = {} try: book_title = entities['book'][0]['value'] response = requests.get('https://www.goodreads.com/book/title.xml?key=' + GOODREADS_ACCESS_TOKEN + '&title=' + book_title) data = ElementTree.fromstring(response.content) book_node = data.find('book') title = book_node.find('title').text description = book_node.find('description').text average_rating = book_node.find('average_rating').text link = book_node.find('link').text goodreads_attribution = '- Powered by Goodreads' template = TextTemplate() template.set_text('Title: ' + title + '\nDescription: ' + description) template.set_post_text('\nAverage Rating: ' + average_rating + ' / 5' + '\nLink: ' + link + '\n\n' + goodreads_attribution) output['input'] = input output['output'] = template.get_message() output['success'] = True except: error_message = 'I couldn\'t find any book matching your query.' error_message += '\nPlease ask me something else, like:' error_message += '\n - book timeline' error_message += '\n - harry potter book plot' error_message += '\n - little women book rating' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input): hello = [ 'Hi dude!', 'Hey there, dude!', 'Yo dude!', 'What\'s up, dude!' ] output = { 'input': input, 'output': TextTemplate(random.choice(hello)).get_message(), 'success': True } return output
def process(input): whatshouldido = [ 'You should learn to chill, dude!', 'Have a White Russian cocktail, dude!', 'Relax, dude!', 'Have fun, dude!' ] output = { 'input': input, 'output': TextTemplate(random.choice(whatshouldido)).get_message(), 'success': True } return output
def process(input, entities): output = {} try: word = entities['word'][0]['value'] r = requests.get('https://wordsapiv1.p.mashape.com/words/' + word + '/definitions', headers={'X-Mashape-Key': WORDS_API_KEY}) data = r.json() output['input'] = input output['output'] = TextTemplate( 'Definition of ' + word + ':\n' + data['definitions'][0]['definition']).get_message() output['success'] = True except: error_message = 'I couldn\'t find that definition.' error_message += '\nPlease ask me something else, like:' error_message += '\n - define comfort' error_message += '\n - cloud definition' error_message += '\n - what does an accolade mean?' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input): cuss = [ 'Damn! You need language lessons, dude!', 'Easy there, dude!', 'Relax, dude!', 'Control, dude!' ] output = { 'input': input, 'output': TextTemplate(random.choice(cuss)).get_message(), 'success': True } return output
def process(input, entities=None): output = {} try: # Programming quotes r = requests.get('http://quotes.stormconsultancy.co.uk/random.json') data = r.json() output['input'] = input output['output'] = TextTemplate(data['quote'] + ' - ' + data['author']).get_message() output['success'] = True except: output['success'] = False return output
def process(input, entities): output = {} try: stock_name = entities['stock'][0]['value'].upper() r = requests.get('http://www.google.com/finance?q='+stock_name+'&output=json') data = json.loads(r.text[3:]) stockprice = data[0]['l'] print('here') returnString = 'The last price of ' + stock_name + ' is: USD '+ stockprice output['input'] = input output['output'] = TextTemplate(returnString).get_message() output['success'] = True except: error_message = 'I couldn\'t find a stock price for that company name.' error_message += '\nPlease ask me something else, like:' error_message += '\n - What is the price of Apple' error_message += '\n - What is the price of Microsoft' error_message += '\n - Show me the price of Apple' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input, entities): output = {} try: music = entities['music'][0]['value'] with open(config.SPOTIFY_TOKEN_FILE) as token_file: token = json.load(token_file)['ACCESS_TOKEN'] r = api_search(token, music) if r.status_code == UNAUTHORIZED: auth_url = 'https://accounts.spotify.com/api/token' headers = {'Authorization': 'Basic ' + SPOTIFY_API_KEY} payload = {'grant_type': 'client_credentials'} r = requests.post(auth_url, headers=headers, data=payload) new_token = r.json()['access_token'] with open(config.SPOTIFY_TOKEN_FILE, 'w') as token_file: token_dict = {'ACCESS_TOKEN': new_token} json.dump(token_dict, token_file) r = api_search(new_token, music) data = r.json() assert (len(data['tracks']['items']) > 0) template = GenericTemplate() for track in data['tracks']['items']: title = track['name'] item_url = track['external_urls']['spotify'] image_url = track['album']['images'][0]['url'] artists = [] for artist in track['artists']: artists.append(artist['name']) duration = datetime.utcfromtimestamp(track['duration_ms'] / 1000).strftime('%M:%S') subtitle = 'By ' + ', '.join(artists) + ' | ' + track['album']['name'] + ' | ' + duration buttons = ButtonTemplate() buttons.add_web_url('Preview Track', track['preview_url']) buttons.add_web_url('Open in Spotify', 'https://embed.spotify.com/openspotify/?spuri=' + track['uri']) template.set_image_aspect_ratio_to_square() template.add_element(title=title, item_url=item_url, image_url=image_url, subtitle=subtitle, buttons=buttons.get_buttons()) output['input'] = input output['output'] = template.get_message() output['success'] = True except: error_message = 'I couldn\'t find any music matching your query.' error_message += '\nPlease ask me something else, like:' error_message += '\n - hymn for the weekend song' error_message += '\n - linkin park songs' error_message += '\n - play hotel california' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input, entities=None): greetings = [ 'Have a good day, sir.', 'Wonderful, I think it\'s time for my evening nap...', 'Bye to you as well, good sir.', 'It was my pleasure talking to you.', 'Oh, please do not go!', ] output = { 'input': input, 'output': TextTemplate(random.choice(greetings)).get_message(), 'success': True } return output
def wiki_response(search_query): try: data = wikipedia.page(search_query) text_template = TextTemplate('Wikipedia summary of ' + data.title + ':\n' + data.summary) text = text_template.get_message()['text'] button_template = ButtonTemplate(text) button_template.add_web_url('Wikipedia Link', data.url) response_message = button_template.get_message() except wikipedia.exceptions.DisambiguationError, e: generic_template = GenericTemplate() image_url = 'https://en.wikipedia.org/static/images/project-logos/enwiki-2x.png' pageids = set() for option in e.options: try: data = wikipedia.page(option) if data.pageid in pageids: continue pageids.add(data.pageid) buttons = ButtonTemplate() buttons.add_web_url('Wikipedia Link', data.url) '''@TODO: Figure Postbacks payload = { 'intent': 'wiki', 'entities': { 'tag': [ { 'value': option } ] } } buttons.add_postback('Wikipedia Summary', json.dumps(payload)) ''' generic_template.add_element(title=data.title, item_url=data.url, image_url=image_url, buttons=buttons.get_buttons()) except Exception, ex: pass
def process(input, entities): output = {} try: url = entities['url'][0]['value'] action = entities['url_action'][0]['value'] if action == 'expand': r = requests.get('https://www.googleapis.com/urlshortener/v1/url', params={ 'key': GOOGLE_URL_SHORTENER_API_KEY, 'shortUrl': url }) data = r.json() response = 'Here\'s the shortened URL:\n' + url response += '\nHere\'s your original URL:\n' + data['longUrl'] else: assert (action == 'shorten') r = requests.post('https://www.googleapis.com/urlshortener/v1/url?key=' + GOOGLE_URL_SHORTENER_API_KEY, data=json.dumps({ 'longUrl': url }), headers={ 'Content-Type': 'application/json' }) data = r.json() response = 'Here\'s your original URL:\n' + url response += '\nHere\'s your shortened URL:\n' + data['id'] output['input'] = input output['output'] = TextTemplate(response).get_message() output['success'] = True except: error_message = 'I couldn\'t perform that action.' error_message += '\nPlease ask me something else, like:' error_message += '\n - shorten google.com' error_message += '\n - give me a short version of bing.com' error_message += '\n - expand http://goo.gl/7aqe' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(action, parameter): output = {} help_message = "Hello I'm Monica Geller Bing, I am here to help you find great restaurants with the help of my skills :)" help_message += "\nSearch queries like" help_message += "\n - Search for hotels in Banglore" help_message += "\n - I wanna eat some chinese food" help_message += "\n - I'm hungry" help_message += "\n - Show me something to eat under 1000 Rs" help_message += "\n - Tell me a joke" help_message += "\n - I want a famous quote" help_message += "\n - Some facts?" try: template = TextTemplate(help_message) output['action'] = action output['success'] = True output['output'] = template.get_message() except Exception as E: print E exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print exc_type, fname, exc_tb.tb_lineno output['error_msg'] = TextTemplate(help_message).get_message() output['success'] = False return output
def process(input, entities): try: pattern = '^pick\s' choices = entities['choices'][0]['value'] choices = re.split(pattern, choices) choices = choices[1:].split(' ') if choices == []: raise ValueError("Empty List") output = { 'input': input, 'output': TextTemplate(random.choice(choices)).get_message(), 'success': True } except: error_message = 'I couldn\'t understand what you were saying.' error_message += '\nPlease ask me something else, like:' error_message += '\n - pick chinese japanese indian' error_message += '\n - pick soccer basketball' error_message += '\n - pick a b c' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input, entities): output = {} try: url = entities['url'][0]['value'] if not urlparse(url).scheme: url = "https://" + url hostname = urlparse(url).hostname if hostname is None: raise Exception( "Please enter a valid hostname to check availability.") r = requests.get('https://isitup.org/' + hostname + '.json') data = r.json() status = data['status_code'] if status == 1: text = hostname + ' is up.' image_url = 'http://fa2png.io/media/icons/font-awesome/4-7-0/check-circle/256/0/27ae60_none.png' elif status == 2: text = hostname + ' seems to be down!' image_url = 'http://fa2png.io/media/icons/font-awesome/4-7-0/times-circle/256/0/c0392b_none.png' elif status == 3: text = 'Please enter a valid domain to check availability.' image_url = 'http://fa2png.io/media/icons/font-awesome/4-7-0/exclamation-circle/256/0/f1c40f_none.png' else: raise Exception("Something unexpected happened!") buttons = ButtonTemplate() buttons.add_web_url('View more info', 'https://isitup.org/' + hostname) buttons.add_web_url('Go to website', hostname) template = GenericTemplate() template.set_image_aspect_ratio_to_square() template.add_element(title=text, image_url=image_url, buttons=buttons.get_buttons()) output['input'] = input output['output'] = template.get_message() output['success'] = True except: error_message = 'There seems to be a problem looking up that domain.' error_message += '\nPlease ask me something else, like:' error_message += '\n - is google.com up' error_message += '\n - google.com status' error_message += '\n - ping google.com' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input, entities): output = {} entities=entities[0] try: if entities["func"] == "next_match": output["input"] = input output["output"] = next_match(entities["team"]) output["success"] = True except: error_message = "Whoops! Something went wrong\n" error_message += "You may have requested a feature which is not yet existent in this bot." output["error_msg"] = TextTemplate(error_message).get_message() output["success"] = False return output
def process(input, entities): output = {} try: word = entities['word'][0]['value'] r = requests.get( 'https://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=' + word + '&pretty=true') data = r.json() output['input'] = input output['output'] = TextTemplate( 'Definition of ' + word + ':\n' + data['tuc'][0]['meanings'][0]['text']).get_message() output['success'] = True except: output['success'] = False return output
def process(input, entities=None): output = {} try: baseURL = "https://json.astrologyapi.com/v1/" resp = requests.post(url, auth=('601227', 'cf5463916fdd1cfa5b96889ec2590621')) print resp.json() except: error_message = 'There was some error while retrieving data from Crickbuzz.' output['error_msg'] = TextTemplate(error_message).get_message() output['success'] = False return output
def process(input, entities=None): greetings = [ 'Welcome home, sir...', 'All wrapped up here, sir. Will there be anything else?', 'Sir, I think I need to sleep now...', 'I seem to do quite well for a stretch, and then at the end of the sentence I say the wrong cranberry.', 'At your service, sir.', 'Oh hello, sir!', 'Perhaps, if you intend to visit other planets, we should improve the exosystems.', ] output = { 'input': input, 'output': TextTemplate(random.choice(greetings)).get_message(), 'success': True } return output
def process(input, entities): output = {} try: word = entities['word'][0]['value'] r = requests.get('https://wordsapiv1.p.mashape.com/words/' + word + '/definitions', headers={'X-Mashape-Key': WORDS_API_KEY}) data = r.json() output['input'] = input output['output'] = TextTemplate( 'Definition of ' + word + ':\n' + data['definitions'][0]['definition']).get_message() output['success'] = True except: output['success'] = False return output
def process(input, entities): output = {} try: query = entities['wikipedia_search_query'][0]['value'] data = wikipedia.page(query) template = TextTemplate() template.set_text('Wikipedia summary of ' + data.title + ':\n' + data.summary) template.set_post_text('\n' + data.url) output['input'] = input output['output'] = template.get_message() output['success'] = True except: output['success'] = False return output
def process(input, entities): output = {} try: movie = entities['movie'][0]['value'] r = requests.get('http://www.omdbapi.com/?t=' + movie + '&plot=full&r=json') data = r.json() output['input'] = input template = TextTemplate() template.set_text(data['Title'] + '\nPlot: ' + data['Plot']) template.set_post_text('\nIMDb Rating: ' + data['imdbRating']) output['output'] = template.get_message() output['success'] = True except: output['success'] = False return output
def process(input, entities=None): output = {} try: book_title = entities['book'][0]['value'] response = requests.get('https://www.goodreads.com/book/title.xml?key=' + GOODREADS_ACCESS_TOKEN + '&title=' + book_title) data = ElementTree.fromstring(response.content) book_node = data.find('book') title = book_node.find('title').text description = book_node.find('description').text average_rating = book_node.find('average_rating').text link = book_node.find('link').text goodreads_attribution = "- Powered by Goodreads" template = TextTemplate() template.set_text('Title: ' + title + '\nDescription: ' + description) template.set_post_text('\nAverage Rating: ' + average_rating + '\nLink: ' + link + '\n\n' + goodreads_attribution) output['input'] = input output['output'] = template.get_message() output['success'] = True except: output['success'] = False return output