def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # check email status email = tracker.get_slot('email') if email is not None: from validate_email import validate_email if not validate_email( email_address=email, check_regex=True, check_mx=False): dispatcher.utter_template('utter_request_valid_email', tracker) return [ SlotSet("email", None), FollowupAction('action_listen') ] elif not validate_email(email_address=email, check_regex=False, check_mx=True, smtp_timeout=5, dns_timeout=5): dispatcher.utter_template('utter_request_exist_email', tracker) return [ SlotSet("email", None), FollowupAction('action_listen') ] else: return [] # check phone number phone_number = tracker.get_slot('phone_number') if phone_number is not None: if not self.check_phone_number(phone_number): dispatcher.utter_template('utter_request_valid_phone_number', tracker) return [ SlotSet("phone_number", None), FollowupAction('action_listen') ] return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: events = [] entities = {entity["entity"]: entity["value"] for entity in tracker.latest_message['entities']} slots = tracker.current_slot_values() is_available, message, slots = required_data_available(slots) if is_available: data_type = DataStorage.dataset_properties[slots["dataset"]]["data_type"] if data_type=="dataset": if "chart_type" in entities.keys(): chart_type = entities["chart_type"] else: # TODO return graph_data = slots graph_data["chart_type"] = chart_type graph_data["data_type"] = data_type dispatcher.utter_message(json.dumps({"graph_data":graph_data, "message": message})) events = [SlotSet("chart_type", entities["chart_type"]), SlotSet("data_type",data_type)] else: message = "This operation can not be applied to this data." dispatcher.utter_message(json.dumps({"graph_data": None, "message":message})) else: dispatcher.utter_message(json.dumps({"graph_data": None, "message":message})) return events
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: data_path = os.path.join("data", "cldf-datasets-wals-014143f", "cldf", "languages.csv") wals_data = pd.read_csv(data_path) entities = list(tracker.get_latest_entity_values("language")) if len(entities) > 0: query_lang = entities.pop() query_lang = query_lang.lower().capitalize() print(query_lang) try: gs = goslate.Goslate() final = gs.translate(query_lang, 'en') print(final) out_row = wals_data[wals_data["Name"] == final].to_dict( "records") if len(out_row) > 0: out_row = out_row[0] out_text = "%s भाषा %s परिवार से संबंधित है।\nइसका जीनस %s है।\nइसका ISO कोड %s है।" % ( query_lang, out_row["Family"], out_row["Genus"], out_row["ISO_codes"]) dispatcher.utter_message(text=out_text) else: dispatcher.utter_message( text= "क्षमा करें! हमारे पास %s भाषा के रिकॉर्ड नहीं हैं।" % query_lang) except: dispatcher.utter_message( text= "Google API से संपर्क करने में असमर्थ, पुनः प्रयास करें।") return []
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: video_game = tracker.get_slot("video_game") if (not video_game): dispatcher.utter_template("utter_not_found", tracker) else: video_game = video_game.lower() requirements = get_requirements(video_game) if (not requirements[0][5]): dispatcher.utter_template("utter_not_found", tracker) else: if (requirements[0][0]): mac_ok = "Oui" else: mac_ok = "Non" if (requirements[0][1]): linux_ok = "Oui" else: linux_ok = "Non" if (requirements[0][2]): windows_ok = "Oui" else: windows_ok = "Non" dispatcher.utter_template( "utter_give_requirements", tracker, linux_ok=linux_ok, mac_ok=mac_ok, windows_ok=windows_ok, mac_requirements=requirements[0][3], linux_requirements=requirements[0][4], windows_requirements=requirements[0][5]) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: nric_regex_template = '^[SFTG]\d{7}[A-Z]$' # except value from slot try: nric = tracker.get_slot("nric_regex") # validate NRIC saved in slot to check if it fits the format of a valid NRIC value if (re.search(nric_regex_template, nric)): dispatcher.utter_message(text="Okay, your NRIC is " + nric) return [SlotSet("nric_regex", nric)] else: dispatcher.utter_message( text="Your NRIC is invalid, please enter the correct NRIC") return [SlotSet("nric_regex", None) ] # Sets the value of the slot 'nric_regex' to None except: dispatcher.utter_message( text= "NRIC validation intent is triggered but action not carried out" ) return [SlotSet("nric_regex", None)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: account_number = random.randint(1000, 9999) DataUpdate(tracker.get_slot("name"), tracker.get_slot("cmnd"), account_number) text = ("Bạn có muốn tiếp tục không ?") buttons = [ { "payload": "/affirm", "title": "Yes" }, { "payload": "/deny", "title": "No" }, ] dispatcher.utter_message(text=text, buttons=buttons) dispatcher.utter_message( "bạn đã tạo tài khoản cho {} thành công".format( tracker.get_slot("others_person_sex"))) dispatcher.utter_message( "your account number is {}".format(account_number)) return []
def validate_food_count( self, slot_value: Any, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: if slot_value.isnumeric(): basket_counts.append(slot_value) if len(basket_names) > 0: dispatcher.utter_message("Sepetinizdeki ürünler:") i = 0 while i < len(basket_names): dispatcher.utter_message(basket_names[i] + " " + basket_counts[i] + " adet") i = i + 1 return {"food_count": None, "food": None} else: dispatcher.utter_message(template="utter_wrong_food_count") return {"food_count": None, "food": None}
async def utter_objects( self, dispatcher: CollectingDispatcher, object_type: Text, objects: List[Dict[Text, Any]], ) -> None: """ Utters a response to the user that lists all found objects. Args: dispatcher: the dispatcher object_type: the object type objects: the list of objects """ if objects: dispatcher.utter_message( text=f"Folgendes ist in der '{object_type}' versichert:" ) if utils.is_coroutine_action( self.knowledge_base.get_representation_function_of_object ): repr_function = await self.knowledge_base.get_representation_function_of_object( object_type ) else: repr_function = self.knowledge_base.get_representation_function_of_object( object_type ) for i, obj in enumerate(objects, 1): dispatcher.utter_message(text=f"{i}: {repr_function(obj)}") else: dispatcher.utter_message( text=f"Ich konnte leider nichts zu '{object_type}' finden." )
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: result = init_code(dispatcher, tracker, domain) print("run ActionAtar") if result is None: return [] elif result.is_type('c'): atar = result.get_atar() if atar is None: dispatcher.utter_message( 'Admission for {} {} is not based on ATAR. For more info, visit {}' .format(result.code(), result.get_name(), result.url())) else: dispatcher.utter_message( '{} {} has a ATAR requirement of {}.'.format( result.code(), result.get_name(), atar)) else: dispatcher.utter_message('{} {} is not a course.'.format( result.code(), result.get_name())) return [SlotSet("code", result.just_code())]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: api_address = 'http://api.openweathermap.org/data/2.5/weather?appid=d98a9aede73d2bfa92fd53cabc6a3497&q=' city = tracker.get_slot('location') url = api_address + city json_data = requests.get(url).json() format_add = json_data['weather'][0]['description'] temp = json_data['main']['temp'] temp_min = json_data['main']['feels_like'] temp_max = json_data['main']['temp_max'] temp_pree = json_data['main']['pressure'] temp_hum = json_data['main']['humidity'] vis = json_data['wind'] cun = json_data['sys']['country'] response = """It is currently {} in {} at the moment. The temperature is {} farenhite, the humidity is {} and the wind speed is {} mph.""".format( format_add, city, temp, temp_hum, temp_pree) dispatcher.utter_message(response) #dispatcher.utter_message(text="temperature in kalvin") #dispatcher.utter_message(temp) #dispatcher.utter_message(text="feels like") #dispatcher.utter_message(temp_min) #dispatcher.utter_message(text="temperture maximum") #dispatcher.utter_message(temp_max) #dispatcher.utter_message(text="pressure") #dispatcher.utter_message(temp_pree) #dispatcher.utter_message(text="humidity") #dispatcher.utter_message(temp_hum) #dispatcher.utter_message(text="visibility") #dispatcher.utter_message(vis) #dispatcher.utter_message(text="country") dispatcher.utter_message(text="The country of this city is") dispatcher.utter_message(cun) return
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: nombre_pokemon = tracker.get_slot("nombre_pokemon") numero_pokemon = tracker.get_slot("numero_pokemon") if nombre_pokemon and not numero_pokemon: req = requests.get(POKEAPI_URL + "pokemon/" + nombre_pokemon.lower()) elif numero_pokemon and not nombre_pokemon: req = requests.get(POKEAPI_URL + "pokemon/" + numero_pokemon) if req.status_code == 404: dispatcher.utter_message(template="utter_pokemon_no_encontrado") return [AllSlotsReset()] info = req.json() info_numero_pokemon = str(info.get("id")) info_nombre_pokemon = info.get("name").title() info_tipos_pokemon = ", ".join([ POKEMON_TIPOS.get(t.get("type").get("name")) for t in info.get("types") ]) info_imagen_pokemon = info.get("sprites").get("front_default") if info_imagen_pokemon: dispatcher.utter_message(template="utter_info_pokemon", numero=info_numero_pokemon, nombre=info_nombre_pokemon, tipos=info_tipos_pokemon, imagen=info_imagen_pokemon) else: dispatcher.utter_message(template="utter_info_pokemon_sin_imagen", numero=info_numero_pokemon, nombre=info_nombre_pokemon, tipos=info_tipos_pokemon) return [AllSlotsReset()]
async def utter_objects( self, dispatcher: CollectingDispatcher, object_type: Text, objects: List[Dict[Text, Any]], ) -> None: """ Utters a response to the user that lists all found objects. Args: dispatcher: the dispatcher object_type: the object type objects: the list of objects """ if objects: dispatcher.utter_message( text=f"Found the following objects of type '{object_type}':" ) if utils.is_coroutine_action( self.knowledge_base.get_representation_function_of_object ): repr_function = await self.knowledge_base.get_representation_function_of_object( object_type ) else: repr_function = self.knowledge_base.get_representation_function_of_object( object_type ) for i, obj in enumerate(objects, 1): dispatcher.utter_message(text=f"{i}: {repr_function(obj)}") else: dispatcher.utter_message( text=f"I could not find any objects of type '{object_type}'." )
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: if random_bool(): dispatcher.utter_message( text= "<speak><emphasis level='strong'>Nice escape!</emphasis></speak>" ) return [SlotSet("current_monster", None)] current_monster = tracker.get_slot("current_monster") message = "Oh no, the " + current_monster + " is following you!!" life = int(tracker.get_slot("life")) life -= 1 if life == 0: message += " You don't have any more lives. You lost!" dispatcher.utter_message(text=message) return [Restarted()] else: message += " You now have " if int(life) > 1: message += str(life) + " lives" elif int(life) == 1: message += "1 life." dispatcher.utter_message(text=message) return [SlotSet("next_action", None), SlotSet("life", life)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: user, room = get_current_user_room(tracker) choice, result = room.move(user) slots = [SlotSet("weapons", user.weapons)] if choice == MONSTER: dispatcher.utter_message(text="You encountered a " + result + " what do you want to do?") slots.append(SlotSet("current_monster", result)) elif choice == EXIT: dispatcher.utter_message( text="You found the door to room number " + str(result) + ". What do you want to do?") slots.append(SlotSet("object", result)) else: slots.append(SlotSet("object", None)) dispatcher.utter_message(text="You found " + result + ". What do you want to do next?") slots.append(SlotSet("direction", None)) slots.append(SlotSet("next_action", None)) return slots
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ): name = tracker.get_slot("personname") price = tracker.get_slot("campaignprice") closingprice = 0.6 * price bargainprice = tracker.get_slot("bargainprice") # RNN to utter bargain messages if bargainprice <= closingprice: dispatcher.utter_message( "All right i can work at {}".format(closingprice)) tracker.trigger_followup_action(self.utter_priceagreedfollowup) return events else: dispatcher.utter_message("No {}".format(name)) dispatcher.utter_message( "Like I said earlier, we are low on funds and that price point would not be affordable at this point of time" ) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: #condition on intents intent_name = tracker.latest_message["intent"]["name"] special_items = pd.read_csv( "/Users/User/Desktop/learning/Rasa/Consolidated/actions/special_item_list.csv" ) #see if randomly put item is a special item dispatch the appropriate message #check the buy item and item cost converstaion flow. if intent_name == "open_buy_item" and len( tracker.latest_message['entities']) != 0: for dic in tracker.latest_message['entities']: if dic["entity"] == "items": item = dic["value"] if dic["value"] in special_items["special_items"].tolist(): buttons = [{ "title": "That was helpful!", "payload": "helpful" }, { "title": "That was unhelpful!", "payload": "unhelpful" }] dispatcher.utter_message( text= f"{item} is a special item that uses a special procedure. Please... Was that helpful?", buttons=buttons) else: dispatcher.utter_message( text="How much does it cost in total?") else: dispatcher.utter_message( text= "Sorry did not understand what you were saying, could you try saying it in another way?" ) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: result = init_code(dispatcher, tracker, domain) print("run ActionProfPrac") if result is None: return [] elif result.is_type('c'): if result.is_prof_prac(): dispatcher.utter_message( '{} {} comes with a Diploma in Professional Practice.'. format(result.code(), result.get_name())) else: dispatcher.utter_message( '{} {} does not come with a Diploma in Professional Practice.' .format(result.code(), result.get_name())) else: dispatcher.utter_message( '{} {} is not a course at UTS. It is a a {} at UTS. It contains:' .format(result.code(), result.get_name(), result.get_type())) return [SlotSet("code", result.just_code())]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): disease = tracker.get_slot("disease") pre_disease = tracker.get_slot("sure") print("pre_disease::::" + str(pre_disease)) possible_diseases = retrieve_disease_name(disease) if disease == pre_disease or len(possible_diseases) == 1: a = [x['s.name'] for x in graph.run("MATCH (p:Disease{name: {disease}})-[r:has_symptom]->\ (s:Symptom) RETURN s.name", disease=disease).data()] template = "{0}的症状可能有:{1}" retmsg = template.format(disease, "、".join(a)) dispatcher.utter_message(retmsg) elif len(possible_diseases) > 1: buttons = [] for d in possible_diseases: buttons.append(make_button(d, '/search_symptom{{"disease":"{0}", "sure":"{1}"}}'.format(d, d))) dispatcher.utter_button_message("请点击选择想查询的疾病,若没有想要的,请忽略此消息", buttons) else: dispatcher.utter_message("知识库中暂无与 {0} 相关的症状记录".format(disease)) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: cp = tracker.get_slot("currency_pair") # cp= currency_pair.replace("/","") clist = [ "inr", "jpy", "usd", "nzd", "cnh", "cad", "aud", "eur", "gbp", "chf", "cny", "sgd", "thb", "mxn" ] while (len(cp)) <= 6: s = ([cp[i:i + 3] for i in range(0, len(cp), 3)]) buy_currency = s[0] sell_currency = s[1] if buy_currency not in clist: dispatcher.utter_message("Please enter a valid buy currency") return [FollowupAction("action_listen")] if sell_currency not in clist: dispatcher.utter_message("Please enter a valid sell currency") return [FollowupAction("action_listen")] dispatcher.utter_message("Fetching current exchange rates...") return [ SlotSet("sell_currency", sell_currency), SlotSet("buy_currency", buy_currency) ]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: file = open("outputRomana.csv", "a") data = pd.read_csv("date.csv", sep=',') dataDf = pd.DataFrame(data) last_message = tracker.latest_message.get("text", "") file.write(str(last_message)) file.write(",") weather = next(tracker.get_latest_entity_values('weather'), None) today = next(tracker.get_latest_entity_values('today'), None) tomorrow = next(tracker.get_latest_entity_values('tomorrow'), None) if (today is None or today is not None) and tomorrow is None: if weather is not None: dispatcher.utter_message("Vremea este " + str(dataDf.get_value(0, 'weather'))) file.write("Vremea este " + str(dataDf.get_value(0, 'weather'))) file.write("\n") file.close() return [] elif tomorrow is not None: if weather is not None: dispatcher.utter_message("Vremea va fi " + str(dataDf.get_value(2, 'weather'))) file.write("Vremea va fi " + str(dataDf.get_value(2, 'weather'))) file.write("\n") file.close() return [] dispatcher.utter_message(template="utter_repeat") file.close() return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: artwork_id = tracker.get_slot('artwork_id') if is_valid_artwork_id(artwork_id): artwork = db_handler.get_artwork_info(artwork_id) if artwork is None: dispatcher.utter_message( text= f"Sorry, there is no artwork with ID code {artwork_id}. Please try again." ) return [SlotSet('artwork_id', None)] # empty the artwork_id slot else: text = f"{artwork_id} is the ID code for the artwork \"{artwork.title}\" by {artwork.artist_name}. " \ f"The minimum bid is ${artwork.min_bid}." dispatcher.utter_message(text=text) else: # not a valid artwork id code dispatcher.utter_message( text= f"Sorry, {artwork_id} is not a valid artwork ID code. Make sure you use " f"capital letters (e.g. ABC123 or WEB563).") return [SlotSet('artwork_id', None)] # empty the artwork_id slot return [SlotSet('artwork_id', None)]
def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: dispatcher.utter_message( "Thanks for getting in touch, we’ll contact you soon") return []
def default_dispatcher(): return CollectingDispatcher()
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): dispatcher.utter_message("I can't help you with that currently.") return [FollowupAction('action_restart')]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message("Hello World!") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: try: # Getting the slot values. f = tracker.get_slot("fever") c = tracker.get_slot("cough") ti = tracker.get_slot("tiredness") c = tracker.get_slot("contact") tr = tracker.get_slot("travel") result_list = [f, c, ti, c, tr] # Counting for the presence of "yes" in slot values. threshold = 0 for i in result_list: if "yes" in i.lower(): threshold += 1 print(threshold) # Giving the message based on number of times "yes" appeared. if (threshold == 5): dispatcher.utter_message( "It is more likely that you have Covid-19.\n\n Better to go for a Covid Test and consult a doctor." ) if (threshold == 4): dispatcher.utter_message( "I think you might have Covid-19. Better to go for a Covid test and consult doctor." ) if (threshold == 3): dispatcher.utter_message( "I feel there is 50:50 chances that you are suffering from COVID-19.\n Better stay away in isolation for 3-5 days and if problem persists, consult a doctor." ) if (threshold == 2 or threshold == 1): dispatcher.utter_message( "I think you do not have corona most probably. \n But it is better you stay in isolation for 6-7 days and if poblem persists, consult a doctor" ) if (threshold == 0): dispatcher.utter_message( "I feel you are alright. \n You do not have any symptoms of Covid-19. Stay safe!" ) except: dispatcher.utter_message("Sorry ! Some internal error happened :}") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: try: facility = tracker.get_slot("facility_type") location = tracker.get_slot("location") print("Tracked Facility: " + facility) print("Tracked Location: " + location) # Validating the type of facility user asks for and gives the details of free food availabilty. if facility == "free food": facilities_state = get_freefoods_by_state(location.title()) if len(facilities_state) != 0: allfacilities = "\n".join(facilities_state) dispatcher.utter_message( "Hey, here is the address of the {} facilities in {}:- \n {}" .format(facility, location, allfacilities)) else: dispatcher.utter_message("Sorry! No {} found in {}".format( facility, location)) # Validating the type of facility user asks for and gives the details of hospitals. if facility == "hospital": facilities_state = get_hospitals_by_state(location.title()) if len(facilities_state) != 0: allfacilities = "\n".join(facilities_state) dispatcher.utter_message( "Hey, here is the address of the {} facilities in {} :- \n {} " .format(facility, location, allfacilities)) else: dispatcher.utter_message("Sorry! No {} found in {}".format( facility, location)) # Validating the type of facility user asks for and gives the details of testcenters. if facility == "test center": facilities_state = get_testcenters_by_state(location.title()) if len(facilities_state) != 0: allfacilities = "\n".join(facilities_state) dispatcher.utter_message( "Hey, here is the address of the {} facilities in {} :- \n {}" .format(facility, location, allfacilities)) else: dispatcher.utter_message("Sorry! No {} found in {}".format( facility, location)) # Validating the type of facility user asks for and gives the details of shelter homes. if facility == "shelter home": facilities_state = get_shelterhomes_by_state(location.title()) if len(facilities_state) != 0: allfacilities = "\n".join(facilities_state) dispatcher.utter_message( "Hey, here is the address of the {} facilities in {} :- \n {} " .format(facility, location, allfacilities)) else: dispatcher.utter_message("Sorry! No {} found in {}".format( facility, location)) except: dispatcher.utter_message("Sorry ! Some internal error happened :}") return []
def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: city = tracker.slots.get('city') date = tracker.slots.get('date') time = tracker.slots.get('time') status = tracker.slots.get('status') day_of_week = tracker.slots.get('day_of_week') idx, target_date = self.find_time_idx(date, time, day_of_week) if target_date != None: searched_date = f'{date_formating(target_date.month)}/{date_formating(target_date.day)}/{target_date.year}' searched_time = f'{date_formating(target_date.hour)}:{date_formating(target_date.minute)}' now = datetime.now() today = datetime(now.year, now.month, now.day, now.hour, now.minute) if status: response = self.find_weather_info(idx, city, target_date) if status == 'snow': snow = response.get('snow') if snow: hourly = snow.get('1h') if target_date == today: dispatcher.utter_message( text= f'It\'s snowing in {city}. {hourly}mm/hour. Please be careful for slippery floor!' ) else: dispatcher.utter_message( text= f'It will snow in {city} at {searched_date} {searched_time}. {hourly}mm/hour. Please be careful for slippery floor!' ) else: if target_date == today: dispatcher.utter_message( text=f'It\'s not snowing in {city}!') else: dispatcher.utter_message( text= f'It will not snow in {city} at {searched_date} {searched_time}!' ) elif status == 'rain': rain = response.get('rain') if rain: hourly = rain.get('1h') if target_date == today: dispatcher.utter_message( text= f'It\'s raining in {city}. {hourly}mm/hour. please take your umbrella!' ) else: dispatcher.utter_message( text= f'It will rain in {city} at {searched_date} {searched_time}. {hourly}mm/hour. please take your umbrella!' ) else: if target_date == today: dispatcher.utter_message( text=f'It\'s not raining in {city}!') else: dispatcher.utter_message( text= f'It will not rain in {city} at {searched_date} {searched_time}!' ) elif status == 'clear': clear = response.get('description') if 'clear' in clear: if target_date == today: dispatcher.utter_message(text=f'It\'s a nice day!') else: dispatcher.utter_message( text=f'It will be a nice day!') else: dispatcher.utter_message(text=f'It seems cloudy.') elif status == 'temperature': temperature = response.get('temperature') dispatcher.utter_message( text= f'{searched_date} {searched_time} {city}\'s temperature is {temperature:0.1f}°C' ) elif status == 'wind': wind = self.find_weather_info(0, city, target_date).get('wind') dispatcher.utter_message( text= f'{searched_date} {searched_time} {city}\'s wind speed is {wind}m/s' ) elif status == 'humidity': humidity = response.get('humidity') dispatcher.utter_message( text= f'{searched_date} {searched_time} {city}\'s wind humidity is {humidity}m/s' ) if target_date == today: return [ SlotSet("status", None), SlotSet("day_of_week", None), SlotSet("date", searched_date), SlotSet("time", None) ] return [ SlotSet("status", None), SlotSet("day_of_week", None), SlotSet("date", searched_date), SlotSet("time", searched_time) ] if idx != None and idx != 'IMPOSSIBLE': dispatcher.utter_message(text=self.find_weather_info( idx, city, target_date).get('text')) if target_date == today: print(target_date == today) return [ SlotSet("day_of_week", None), SlotSet("date", searched_date), SlotSet("time", None) ] return [ SlotSet("day_of_week", None), SlotSet("date", searched_date), SlotSet("time", searched_time) ] if date == 'historical' or idx == 'IMPOSSIBLE': dispatcher.utter_message( text= f'I\'m really sorry:( I can\'t find weather information at this time.' ) return [SlotSet("time", None)] return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message(text=f"you are welcome :)") return [AllSlotsReset()]
def utter_attribute_value( self, dispatcher: CollectingDispatcher, object_name: Text, attribute_name: Text, attribute_value: Text, ): """ Utters a response that informs the user about the attribute value of the attribute of interest. Args: dispatcher: the dispatcher object_name: the name of the object attribute_name: the name of the attribute attribute_value: the value of the attribute """ #dispatcher.utter_message(attachment = "") if attribute_value: if attribute_name in ['city']: dispatcher.utter_message( text= f"{chatbot_name} -> Sure. The {attribute_name} of '{object_name}' is '{attribute_value}'." ) elif attribute_name in ['careers', 'link', 'scholarship']: dispatcher.utter_message( text=f"{chatbot_name} -> Let me check (...). ") dispatcher.utter_message( text=f"You can get all the info in : ", attachment=attribute_value) elif attribute_name in ['ranking']: dispatcher.utter_message( text= f"{chatbot_name} -> Ok. '{object_name}' is the '{attribute_value}' best in the world. Awesome!" ) elif attribute_name in ['cost']: if 'http' in attribute_value and '//' in attribute_value: dispatcher.utter_message( text= f"{chatbot_name} -> All the information about costs of {object_name} is in the following link : ", attachment=attribute_value) else: dispatcher.utter_message( text= f"{chatbot_name} -> The costs of '{object_name}' are: '{attribute_value}'." ) else: dispatcher.utter_message( text= f"{chatbot_name} -> '{object_name}' has the value '{attribute_value}' for attribute '{attribute_name}'." ) else: dispatcher.utter_message( text= f"{chatbot_name} -> Did not find a valid value for attribute '{attribute_name}' for object '{object_name}'." )