def run(self, dispatcher, tracker, domain): loc = tracker.get_slot('location') country = 'Australia' city = 'Sydney' condition = 'Sunny' temperature_c = '25' humidity = '20' wind_mph = '20' response = """It is currently {} in {} at the moment. The temperature is {} degrees, the humidity is {}% and the wind speed is {} mph.""".format( condition, city, temperature_c, humidity, wind_mph) dispatcher.utter_message(response) return [SlotSet('location', loc)]
def run(self, dispatcher, tracker, domain): from elasticsearch import Elasticsearch import json import requests uri = " " loc = tracker.get_slot('market') search_word = "Market_" + loc.capitalize() q = { "size": 5, "query": { "bool": { "must": [{ "term": { "plainTags": search_word } }] } } } query = json.dumps(q) response = requests.post(uri, query) result = json.loads(response.text) data = [doc for doc in result['hits']['hits']] url_list = [] for d in data: try: url_list.append(d['_source']['url']) except: pass if url_list: for i in range(len(url_list)): if i == 0: r = "News of {} market are {}".format(loc, url_list[i]) dispatcher.utter_message(r) else: r = "{}".format(url_list[i]) dispatcher.utter_message(r) else: r = "Sorry, No news currently available" dispatcher.utter_message(r) return [SlotSet('market', loc)]
def run(self, dispatcher, tracker, domain): feature = tracker.get_slot('feature type') config = tracker.get_slot('configuration') print(SlotSet('feature type', feature)) print(SlotSet('configuration', config)) output1 = SlotSet('feature type', feature) output2 = SlotSet('configuration', config) output = output1.update(output2) response = """action_inform_configuration""" dispatcher.utter_message(response)
def run( self, dispatcher, # type: CollectingDispatcher tracker, # type: Tracker domain, # type: Dict[Text, Any] ): # type: (...) -> List[Dict[Text, Any]] user_horoscope_sign = tracker.get_slot('horoscope_sign') url = f'http://horoscope-api.herokuapp.com/horoscope/today/{user_horoscope_sign}' res = requests.get(url) todays_horoscope = res.json()['horoscope'] response = f"Here's your horoscope for today:\n {todays_horoscope}" dispatcher.utter_message(response) return [SlotSet('horoscope_sign', user_horoscope_sign)]
def run(self, dispatcher, tracker, domain): # type: (Dispatcher, DialogueStateTracker, Domain) -> List[Event] user_artist_name = tracker.get_slot('artist_name') client = SpotifyAPI(client_id, client_secret) artist_object = client.search(user_artist_name) artist_id = artist_object['artists']['items'][0]['id'] tracks_object = client.get_track(artist_id) tracks_object = client.get_track(artist_id)['tracks'] track_object = tracks_object[random.randin(0, len(tracks_object))] track_name = track_object['name'] track_url_preview = track_object['preview_url'] dispatcher.utter_message(track_name) return [SlotSet("artist_name", user_artist_name)]
def run(self, dispatcher, tracker, domain): hol = tracker.get_slot('holidays') # replace with API call ... # switch (hol): # case 'Herbstferien': # response = 'Im Herbst' # break # ... # ... until here! response = 'Ich weiss nix von ' + hol dispatcher.utter_message(response) return [SlotSet('holidays', hol)]
def validate(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: """Validate extracted requested slot else reject the execution of the form action """ # extract other slots that were not requested # but set by corresponding entity slot_values = self.extract_other_slots(dispatcher, tracker, domain) # extract requested slot slot_to_fill = tracker.get_slot(REQUESTED_SLOT) if slot_to_fill: slot_values.update( self.extract_requested_slot(dispatcher, tracker, domain)) if not slot_values: # reject form action execution # if some slot was requested but nothing was extracted # it will allow other policies to predict another action raise ActionExecutionRejection( self.name(), "Failed to validate slot {0} " "with action {1}" "".format(slot_to_fill, self.name())) # we'll check when validation failed in order # to add appropriate utterances for slot, value in slot_values.items(): if slot == 'account_type': if value.lower() not in self.account_db(): dispatcher.utter_template('utter_wrong_account', tracker) # validation failed, set slot to None slot_values[slot] = None elif slot == 'account_number': if not self.is_int(value) or int(value) <= 0: dispatcher.utter_template('utter_wrong_account', tracker) # validation failed, set slot to None slot_values[slot] = None elif slot == 'branch': if not self.is_int(value) or int(value) <= 0: dispatcher.utter_template('utter_wrong_branch', tracker) # validation failed, set slot to None slot_values[slot] = None # validation succeed, set the slots values to the extracted values return [SlotSet(slot, value) for slot, value in slot_values.items()]
def run( self, dispatcher, # type: CollectingDispatcher tracker, # type: Tracker domain, # type: Dict[Text, Any] ): # type: (...) -> List[Dict[Text, Any]] subscribe = tracker.get_slot('subscribe') if subscribe: response = "You've been successfully subscribed" else: response = "You've been successfully unsubscribed" dispatcher.utter_message(response) return [SlotSet('subscribe', subscribe)]
def run(self, dispatcher, tracker, domain): orig = tracker.get_slot('from') dest = tracker.get_slot('to') date = tracker.get_slot('from_date') to_date = tracker.get_slot('to_date') filter_str = tracker.get_slot('filter') flight_no = tracker.get_slot('flight_no') connection = filter_str if connection == "direct" or connection == "fastest": connection = "False" elif connection == "cheaper": connection = "True" if not to_date: to_date = date date = datetime.datetime.strptime(date, '%d/%m/%Y').date() to_date = datetime.datetime.strptime(to_date, '%d/%m/%Y').date() data = [] ref_no = "" flag = 0 with open("ticket.json") as f: data = json.loads(f.read()) for item in data: #print(item) item_date = datetime.datetime.strptime(item["Date"], '%d/%m/%Y').date() if preprocess_text(item["From"]) == preprocess_text( orig ) and preprocess_text(item["To"]) == preprocess_text( dest ) and item_date >= date and item_date <= to_date and preprocess_text( item["Flight No"]) == preprocess_text(flight_no): ref_no = item['Ref_no'] if not connection: flag = 1 elif item['Connection'] == connection: flag = 1 if flag == 1: dispatcher.utter_message( "Your booking is accepted!\n Please tell me your name.") return [SlotSet('ref_no', ref_no)] else: dispatcher.utter_message("Sorry! There are no seats available.") return []
def run(self, dispatcher, tracker, domain): # the entity can be one of two entities from duckling, # number or amount-of-money budget = next(tracker.get_latest_entity_values('number'), None) if not budget: budget = next(tracker.get_latest_entity_values('amount-of-money'), None) # as a fallback, if no entity is recognised (e.g. in a sentence # like "I have no money") we store the whole user utterance in the slot # In future this should be stored in a `budget_unconfirmed` slot where # the user will then be asked to confirm this is there budget if not budget: budget = tracker.latest_message.get('text') return [SlotSet('budget', budget)]
def run(self, dispatcher, tracker, domain): # type: (Dispatcher, DialogueStateTracker, Domain) -> List[Event] user_horoscope_sign = tracker.get_slot('horoscope_sign') # open-source horoscope api: code can be @https://github.com/tapasweni-pathak/Horoscope-API # download the codebase and host it on heroku. base_url = http://horoscope-api.herokuapp.com/horoscope/{day}/{sign} url = base_url.format(**{'day': 'today', 'sign': user_horoscope_sign}) # http://horoscope-api.herokuapp.com/horoscope/today/capricorn res = requests.get(url) todays_horoscope = res.json()['horoscope'] response = "Your today's horoscope: \n{}".format(todays_horoscope) dispatcher.utter_message(response) return [SlotSet("horoscope_sign", user_horoscope_sign)]
def run(self, dispatcher, tracker, domain): jobRef = tracker.get_slot("jobRef") user_id = (tracker.current_state())["sender_id"] #user_id = "189c6a81-abde-4388-a757-a50da959e8da" sub_role = (tracker.get_slot("sub_role")) role_id = getRoleID(sub_role) # creates a list out of the existing jobs. possible_jobs = list_jobs(user_id, role_id) if(possible_jobs): message = "These are the available positions that i know about!" else: message= " We don't have an open position in "+ sub_role+", please try again" # generates a list of buttons from the list of possible_jobs buttons = generate_job_buttons(possible_jobs) dispatcher.utter_button_message(message, buttons) return [SlotSet("jobRef", jobRef)]
def run(self, dispatcher, tracker, domain): corr = tracker.get_slot('_correction') newSlot = None # If we land here, then we found a correction # but we don't know what the entity is to correct if (corr): print("entity not recognized mode") print(corr) # Get list of events and reverse it events = tracker.current_state()['events'][::-1] is_set = False for event in events: # We want only user events that changed entities if (event["event"] == "user" and len(event['parse_data']['entities']) > 0): # TODO: A different strategy has to be employed if there were multiple # public entities found in the last event for entity in event['parse_data']['entities']: if (not entity['entity'].startswith("_")): print("I guess I should change:") print(entity['entity']) print("from value:") print(entity['value']) print("to value:") print(corr) print(event['text']) newSlot = SlotSet(entity['entity'], corr) is_set = True break # If we have found the entity then we break the loop if (is_set): break # If we land here then the nlu has found a specific # entity and we have to find out which it is else: print("entity recognized mode") print(tracker.current_state()['latest_message']) for entity in tracker.current_state( )['latest_message']['entities']: print(entity['value']) print(entity['entity']) return [newSlot]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List['Event']: # Fallback caused by TwoStageFallbackPolicy if (len(tracker.events) >= 4 and tracker.events[-4].get('name') == 'action_default_ask_affirmation'): return [ SlotSet('feedback_value', 'negative'), Form('feedback_form'), FollowupAction('feedback_form') ] # Fallback caused by Core else: dispatcher.utter_template('utter_default', tracker) return [UserUtteranceReverted()]
def run(self, dispatcher: 'Dispatcher', tracker: 'DialogueStateTracker', domain: 'Domain'): try: loc = tracker.get_slot('location') weather = Weather(loc) response = """It is currently {} in {} at the moment. The temperature is {:.1f} degrees Celsius. Humidity is {}%, wind speed is {} meters per second\n""".format( weather.get_weather(), loc.capitalize(), weather.get_temperature(), weather.get_humidity(), weather.get_wind_speed()) dispatcher.utter_message(response) return [SlotSet('location', loc)] except NoLocationRecognized: response = "Didn't get what the location you are asking for" dispatcher.utter_message(response)
class ActionTorrent(Action): def name(self): return 'action_torrent' def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = '...' client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getcurrent(q=loc) link = current response = """Your torrent link is {}""".format(link) dispatcher.utter_message(response) return [SlotSet('location',loc)]
def run(self, dispatcher, tracker, domain): street = next(tracker.get_latest_entity_values('street'), None) house_number = next(tracker.get_latest_entity_values('house_number'), None) if not street: dispatcher.utter_message( "Bitte geben Sie den Straßennamen zusätzlich zu Ihrer Hausnummer an" ) return [UserUtteranceReverted()] elif not house_number: dispatcher.utter_message( "Bitte geben Sie die Hausnummer zusätzlich zu Ihrem Straßennamen an" ) return [UserUtteranceReverted()] return [SlotSet("street_address", str(street + " " + house_number))]
def run(self, dispatcher, tracker, domain): spacy_entities = ['place', 'date', 'name', 'organisation'] duckling = [ 'money', 'duration', 'distance', 'ordinals', 'time', 'amount-of-money' ] entity_to_extract = next(tracker.get_latest_entity_values('entity'), None) extractor = 'ner_crf' if entity_to_extract in spacy_entities: extractor = 'ner_spacy' elif entity_to_extract in duckling: extractor = 'ner_duckling_http' return [SlotSet('entity_extractor', extractor)]
def run(self, dispatcher, tracker, domain): return_slots = [] #print(tracker.slots[0]) for slot in tracker.slots: if tracker.slots[slot] != None: #print(tracker.slots[slot]) return_slots.append(SlotSet(slot, None)) file = open("history.txt", "a") file.write("Story \n") for item in story: file.write(str(item) + "\n") story.clear() file.write("\n") file.close() return return_slots
def request_next_slot( self, dispatcher, # type: CollectingDispatcher tracker, # type: Tracker domain # type: Dict[Text, Any] ): # type: (...) -> Optional[List[Dict]] """Request the next slot and utter template if needed, else return None""" for slot in self.required_slots(tracker): if self._should_request_slot(tracker, slot): logger.debug("Request next slot '{}'".format(slot)) dispatcher.utter_template("utter_ask_{}".format(slot), tracker) return [SlotSet(REQUESTED_SLOT, slot)] logger.debug("No slots left to request") return None
def run(self, dispatcher, tracker, domain): plant = tracker.get_slot('plant') if plant == "kangkung": response = """Pupuk untuk tanaman {} adalah pupuk hidroponik seperti AB Mix hidroponik sayur kak""".format( plant) elif plant == "sawi": response = """Pupuk yang cocok untuk tanaman {} adalah pupuk organik atau pupuk kandang""".format( plant) elif plant == "tomat": response = """Untuk tumbuhan {} gunakan pupuk kandang yang sudah didekomposisi dengan EM4 lalu dicmpur dengan PHONSKA dan SP36 dengan perbandingan 2:1""".format( plant) elif plant == "cabai" or plant == "cabe": response = """Pupuk yang cocok untuk tanaman {} adalah campuran tanah humus, arang sekam, dan pupuk kandang kering""".format( plant) dispatcher.utter_message(response) return [SlotSet('plant', plant)]
def run(self, dispatcher, tracker, domain): try: subscribe_slot = tracker.get_slot('subscribe') subscribe = (tracker.latest_message)['text'] if subscribe == 'True': response = 'You are successfully subscribed' else: response = 'You are not subscribed' # else: # response='not subscribed' except: response = 'subscribed' #subscribe = 'not working' dispatcher.utter_message(response) dispatcher.utter_message(subscribe_slot) return [SlotSet('subscribe', subscribe)]
def run(self, dispatcher, tracker, domain): cat = tracker.get_slot('cat'); cat_url = 'https://api.thecatapi.com/v1/breeds/search?q=' + cat; response = requests.get(cat_url); cat_content = response.content.decode(); cat_json = json.loads(cat_content); try: answer = 'This is the information about {} I could find for you: {}'.format(cat_json[0]['name'], cat_json[0]['description']); except: answer = "Pawrdon me, human. I haven't been able to find infurrmation about your desired cat."; dispatcher.utter_message(answer); return [SlotSet('cat', cat)];
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = '2ba4cf94bbc2427791294257191205' #your apixu key client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.current(q=loc) country = current['location']['country'] city = current['location']['name'] condition = current['current']['condition']['text'] temperature_c = current['current']['temp_c'] humidity = current['current']['humidity'] wind_mph = current['current']['wind_mph'] response = """It is currently {} in {} at the moment. The temperature is {} degrees, the humidity is {}% and the wind speed is {} mph.""".format(condition, city, temperature_c, humidity, wind_mph) ##loc = tracker.get_slot('location') ##response = "weather is absolutely fantastic" dispatcher.utter_message(response) return [SlotSet('location',loc)]
def run(self, dispatcher, tracker, domain): curs, conn = connection() scheme_name = tracker.get_slot('scheme_name') query = "select scheme_name, scheme_detail, scheme_link from schemes where scheme_name='%s'" % ( scheme_name, ) curs.execute(query) results = curs.fetchall() for r in results: dispatcher.utter_message("Scheme Name: " + r[0] + "\nScheme Details: " + r[1]) # send the message back to the user dispatcher.utter_message( "For more information of this scheme, please visit: " + r[2]) curs.close() conn.close() gc.collect() return [SlotSet('scheme_name', scheme_name)] #syntax: SlotSet('slot_name', var_name)
def run(self, dispatcher, tracker, domain): # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict[Text, Any]] coin = tracker.get_slot('coin')[0] coin_map = {"bitcoin": 1, "ether": 1027} response = get( f"https://api.coinmarketcap.com/v2/ticker/{coin_map[coin]}/") try: price = response.json()['data']['quotes']['USD']['price'] except Exception as e: price = None if price: response = f"El valor de {coin} es actualmente USD{price:.2f}" else: response = f"No pude obtener el valor de {coin}" dispatcher.utter_message(response) return [SlotSet("coin", coin)]
def run(self, dispatcher, tracker, domain): plant = tracker.get_slot('plant') if plant == "kangkung": response = """Siram {} 1x tiap hari dengan campuran 1 liter air dan 7-9 ml nutrisi AB Mix.""".format( plant) elif plant == "sawi": response = """Siram {} 2x tiap hari pada saat pagi dan sore, tetapi jika dilihat masih dalam keadaan lembab, maka tidak perlu disiram lagi, kak.""".format( plant) elif plant == "tomat": response = """Untuk perawatan {}, kakak bisa menggunakan gembor manual atau selang fertilisasi. Disarankan menggunakan selang fertilisasi karena prosesnya akan lebih mudah.""".format( plant) elif plant == "cabai" or plant == "cabe": response = """Kakak bisa menyiram {} 1x tiap hari. Bisa juga ditambahkan nutrisi 5 ml nutrisi A + 5 ml nutrisi B dicampur dengan 1 liter air tiap 10 hari sekali""".format( plant) dispatcher.utter_message(response) return [SlotSet('plant', plant)]
def run(self, dispatcher, tracker, domain): dispatcher.utter_message( "You're looking for information related to modules. Would you give me some " "more information on what you are looking for?") return [ SlotSet("mensaName", None), SlotSet("menuCourse", None), SlotSet("price", 0.0), SlotSet("vegetarian", False), SlotSet("vegan", False), SlotSet("mensaMatch", None) ]
def run(self, dispatcher, tracker, domain): buttons = [] for t in FACILITY_TYPES: r = FACILITY_TYPES[t] payload = "/inform{\"selected_type_slot\": \"" + r.get( "resource") + "\"}" buttons.append({ "title": "{}".format(r.get("name").title()), "payload": payload }) dispatcher.utter_button_template("utter_greet", buttons, tracker, button_type="custom") return [ SlotSet("provider_types_slot", FACILITY_TYPES if FACILITY_TYPES is not None else []) ]
def validate(self, dispatcher, tracker, domain): # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict] """Extract and validate value of requested slot. If nothing was extracted reject execution of the form action. Subclass this method to add custom validation and rejection logic """ # extract other slots that were not requested # but set by corresponding entity or trigger intent mapping slot_values = self.extract_other_slots(dispatcher, tracker, domain) # extract requested slot slot_to_fill = tracker.get_slot(REQUESTED_SLOT) if slot_to_fill: slot_values.update(self.extract_requested_slot(dispatcher, tracker, domain)) if not slot_values: # reject to execute the form action # if some slot was requested but nothing was extracted # it will allow other policies to predict another action raise ActionExecutionRejection( self.name(), "Failed to extract slot {0} " "with action {1}" "".format(slot_to_fill, self.name()), ) for slot, value in list(slot_values.items()): validate_func = getattr( self, "validate_{}".format(slot), lambda *x: {slot: value} ) validation_output = validate_func(value, dispatcher, tracker, domain) if not isinstance(validation_output, dict): logger.warning( "Returning values in helper validation methods is deprecated. " + "Your method should return a dict of {'slot_name': value} instead." ) validation_output = {slot: validation_output} slot_values.update(validation_output) # validation succeed, set slots to extracted values return [SlotSet(slot, value) for slot, value in slot_values.items()]