async def validate_insurance_policy_type( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validates value of 'insurance_policy_type' slot""" if tracker.get_intent_of_latest_message() == "get_a_quote": return {"insurance_policy_type": None} insurance_policy_type = tracker.get_slot("insurance_policy_type") if isinstance(insurance_policy_type, list): insurance_policy_type = next( tracker.get_latest_entity_values("quote_insurance_type"), None ) # insurance_policy_type = insurance_policy_type[0] print(value, insurance_policy_type) categories = [category.lower() for category in list_categories()] x = "{}, " * (len(categories) - 1) + "{}." if insurance_policy_type.lower() not in categories: dispatcher.utter_message( f"You can only select from these available policies. {x} \nPlease choose one of those options.".format( *categories ) ) return {"insurance_policy_type": None} return {"insurance_policy_type": insurance_policy_type}
async def validate_annual_income( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validates whether the annual income entered is valid.""" if tracker.get_intent_of_latest_message() == "get_a_quote": return {"annual_income": None} print(f"annual income: {value}") try: float(value) except TypeError: dispatcher.utter_message(f"Annual income aerned should be a number.") return {"annual_income": None} except ValueError: dispatcher.utter_message("You must answer with a number.") return {"annual_income": None} if float(value) <= 10.0: dispatcher.utter_message("Annual income must be greater than 10") return {"annual_income": None} return {"annual_income": value}
def validate_quote_number_persons( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validates the number of persons entered is valid.""" if tracker.get_intent_of_latest_message() == "stop": return {"quote_number_persons": None} try: int(value) except TypeError: dispatcher.utter_message(f"Number of persons must be a number.") return {"quote_number_persons": None} except ValueError: dispatcher.utter_message("You must answer with a number.") return {"quote_number_persons": None} if int(value) <= 0: dispatcher.utter_message("Number of people on policy must be >= 1.") return {"quote_number_persons": None} return {"quote_number_persons": value}
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: """Quick replies are sent from here""" intent = str( tracker.get_intent_of_latest_message( skip_fallback_intent=True)).lower() # Getting the intent if intent is not None and not intent.startswith( "c_" ): #Cheks that the intent is Not none and doesnot starts with c_. "c_" indicates that the intent is in confused state result = getattr(dbconnector.load, "getQuickReplies")(intent=intent) dispatcher.utter_message(text=result[0], image=result[1]) elif intent is not None and intent.startswith("c_"): only_intent = intent[2:intent.rfind("_")] slotname = intent[intent.rfind("_") + 1:] slotname = tracker.get_slot(slotname) finalName = extras.changeName(nameOfDepartment=slotname) if finalName is not None: result = getattr(dbconnector.load, "getQuickReplies")(only_intent + "_" + finalName) dispatcher.utter_message(text=result[0], image=result[1]) else: #If there is no proper department defined it asks for the department dispatcher.utter_message( text= "Please ask the same question again with proper Department Name" ) return []
async def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: intent = tracker.get_intent_of_latest_message( ) # Get intent of latest message # EMAIL if (intent == "inform_submission_type_email"): dispatcher.utter_message(template="utter_submission_type_email") # UPLOAD TO BOT elif (intent == "inform_submission_type_upload_to_bot"): dispatcher.utter_message( template="utter_submission_type_upload_to_bot") # POST MAIL elif (intent == "inform_submission_type_post_mail"): dispatcher.utter_message( template="utter_submission_type_post_mail") # ECLAIM FACILITY elif (intent == "inform_submission_type_eclaim_facility"): dispatcher.utter_message( template="utter_submission_type_eclaim_facility") else: dispatcher.utter_message( text="BOT DID NOT UNDERSTAND SUBMISSION TYPE") return []
async def validate_policy_duration( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain ): """Validates the number of years of Policy duration.""" if tracker.get_intent_of_latest_message() == "get_a_quote": return {"policy_duration": None} duration = tracker.get_slot("policy_duration") if duration is None: dispatcher.utter_message(f"Policy duration needs to be a number.") return {"policy_duration": None} if isinstance(duration, str): duration = duration.split()[0] print(f"policy duraion: ({value}, {duration})") try: int(duration) except TypeError: dispatcher.utter_message(f"The policy duration must be a number.") return {"policy_duration": None} except ValueError: dispatcher.utter_message("You must answer with a number of years.") return {"policy_duration": None} if int(duration) not in [3, 5, 10]: dispatcher.utter_message( "policy_duration must be either 3, 5, or 10 years. Try again" ) return {"policy_duration": None} return {"policy_duration": duration}
async def validate_coverage( self, value: Any, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validates whether the annual income entered is valid.""" if tracker.get_intent_of_latest_message() == "get_a_quote": return {"coverage": None} print(f"coverage {value}") try: float(value) except TypeError: dispatcher.utter_message(f"Coverage should be a number.") return {"coverage": None} except ValueError: dispatcher.utter_message("You must answer with a number.") return {"coverage": None} if float(value) not in [40000.0, 70000.0, 100000.0]: dispatcher.utter_message( "Enter an appropriate coverage as shown in the above list" ) return {"coverage": None} return {"coverage": value}
async def extract_sports_category_spelled_correctly( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict) -> Dict[Text, Any]: intent = tracker.get_intent_of_latest_message() text_of_last_user_message = tracker.latest_message.get("text") # print(f"intent: {intent}, text_of_last_user_message: {text_of_last_user_message}") # print(intent == "affirm") return {"sports_category_spelled_correctly": intent == "affirm"}
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: """Status of the user will be changed from here""" intent = tracker.get_intent_of_latest_message( skip_fallback_intent=True) #Get the latest intent change_status = tracker.get_slot( "change_status") # Value that the user wants to change authenticate = tracker.get_slot( "Authenticate") # Checking whether thr user is logged in or not if authenticate is not None: # If logged in if change_status is not None: # if user already said status to be changed # Creating dictionary that needs to be changed to_change = { "$set": { "Status": change_status, "last_change": str(datetime.datetime.now()) } } find = {"ID": tracker.get_slot("ID")} # Sending the data to the DataBase initial, chenged_tp = getattr( dbconnector.load, "change_status")(change=to_change, Type=tracker.get_slot("Type"), find=find) dispatcher.utter_message( text=f"Status has been changed to <b>{change_status}</b>") #Setting the slots to required formats return [ SlotSet("Status", change_status), SlotSet("last_change", str(datetime.datetime.now())), SlotSet("change_status", None) ] else: #If the user didn't enter anything about the status then the bot pops up with some values from database #Creating dropdown menu data = extras.createDropdown(intent=intent, slot_name="change_status", values=getattr( dbconnector.load, "get_extras")(intent=intent)) message = {"payload": "dropDown", "data": data} dispatcher.utter_message( text= "Please select the status that is to be changed from below list", json_message=message) else: # If the user didn't login then it doesn't allow the user to login dispatcher.utter_message( text="You have not logged in. Please log in and try again", buttons=extras.createbuttons(intent="greet", slot_name="dummy", values=["Login"])) return []
async def extract_user_received_alert( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict, ) -> Dict[Text, Any]: # Return an empty dictionary if the bot isn't asking to fill the slot if tracker.get_intent_of_latest_message() == self.activation_intent: return {} if get_last_bot_event(tracker) != 'utter_ask_user_received_alert': return {} # Set the alert and data slots to true if the user confirms they have an alert if tracker.get_intent_of_latest_message() == 'user_confirm': return {"user_received_alert": True, "user_receiving_data": True} elif tracker.get_intent_of_latest_message() == 'user_deny': return {"user_received_alert": False, "user_receiving_data": None} else: dispatcher.utter_template('utter_doesnt_answer', tracker) return {}
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: last_intent = tracker.get_intent_of_latest_message() if last_intent == 'exit': return [FollowupAction('utter_goodbye')] elif last_intent == 'set_time': return [FollowupAction('action_set_time')] dispatcher.utter_message(text=f'last intent: {last_intent}') return []
async def extract_user_receiving_data( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict, ) -> Dict[Text, Any]: # Return an empty dictionary if the bot isn't asking to fill the slot if tracker.get_intent_of_latest_message() == self.activation_intent: return {} if get_last_bot_event(tracker) != 'utter_ask_user_receiving_data': return {} # Set the data to true if the user is receiving data and reset the alert slot so the bot requests it again if tracker.get_intent_of_latest_message() == 'user_confirm': dispatcher.utter_template('utter_check_for_fid', tracker) return {"user_received_alert": None, "user_receiving_data": True} elif tracker.get_intent_of_latest_message() == 'user_deny': dispatcher.utter_template('utter_swap_transmitter', tracker) return {"user_receiving_data": None} else: dispatcher.utter_template('utter_doesnt_answer', tracker) return {}
async def validate_number_of_persons( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validates the number of persons entered is valid.""" print(value) if tracker.get_intent_of_latest_message() == "stop": return {"number_of_persons": None} if tracker.get_intent_of_latest_message() == "get_a_quote": return {"number_of_persons": None} n_persons = tracker.get_slot("number_of_persons") if isinstance(n_persons, list): n_persons = n_persons[0].split()[0] else: n_persons = n_persons.split()[0] try: int(n_persons) except TypeError: dispatcher.utter_message(f"Number of persons must be a number.") return {"number_of_persons": None} except ValueError: dispatcher.utter_message("You must answer with a number.") return {"number_of_persons": None} print(f"number of persons: {n_persons}") if int(n_persons) <= 0: dispatcher.utter_message("Number of people on policy must be >= 1.") return {"number_of_persons": None} return {"quote_number_persons": n_persons}
async def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: intent = tracker.get_intent_of_latest_message( ) # Get intent of latest message # INTENT AFFIRM if (intent == "affirm"): dispatcher.utter_message( text= "Your request to chat with our live agent has been processed.") dispatcher.utter_message( text="Transferring your chat to the live agent") # generate summary list try: slotState = tracker.current_state()["slots"] # get slot states dispatcher.utter_message( text= "conversation handed off to chat agent with the following summary:" ) summarylist = [] # List to story filled slots for key, value in slotState.items(): # check if slot is filled if value: string = key + ": " + value + "<br>" summarylist.append(string) finalList = '\n'.join( summarylist ) # Generate string with newline for each slot item in list for bot utterance dispatcher.utter_message(text=finalList) except: dispatcher.utter_message(text="summary list generation error") # INTENT DENY elif (intent == "deny"): #dispatcher.utter_message(text="What else would you like to know?") dispatcher.utter_message(template="utter_ask_main_topic") # generate buttons here return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: #print(tracker.slots) print(tracker.get_slot("cuisine")) print(tracker.get_intent_of_latest_message()) #print(tracker.events_after_latest_restart()) entity = tracker.get_slot("cuisine") if entity not in Restaurant_List.keys(): dispatcher.utter_message(response = "utter_sorry_cuisine") return [SlotSet("cuisine",None)] else: restaurants = Restaurant_List[entity] dispatcher.utter_message(text = f"Let me find some restaurants for {entity} cuisine for you") return [SlotSet("restaurants",restaurants)]
def validate_firstname( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ): if tracker.get_intent_of_latest_message() == "buy_insurance": return {"firstname": None} firstname = tracker.get_slot("firstname") if isinstance(firstname, str): firstname = firstname.split()[0] else: dispatcher.utter_message("First name should be a string") return {"firstname": None} return {"firstname": firstname}
async def validate_fullname( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validates value of 'insurance-provider' slot""" print(value) if tracker.get_intent_of_latest_message() == "stop": return {"fullname": None} fullname = value if fullname is None or len(fullname) == 0: dispatcher.utter_message("Name cannot be empty") return {"fullname": None} return {"fullname": fullname}
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: """ Executes GET, PUT, POST, DELETE Http requests and curates and returns the user defined output. :param dispatcher: Rasa provided Dispatcher to send messages back to the user. :param tracker: Rasa provided Tracker to maintain the state of a dialogue between the assistant and the user in the form of conversation sessions. :param domain: Rasa provided Domain to specify the intents, entities, slots, and actions your bot should know about. :return: Curated Http response for the configured Http URL. """ response = {} try: logger.debug(tracker.current_slot_values()) intent = tracker.get_intent_of_latest_message() logger.debug("intent: " + str(intent)) logger.debug("tracker.latest_message: " + str(tracker.latest_message)) bot_id = tracker.get_slot("bot") action = tracker.get_slot("http_action_config" + "_" + intent) if ActionUtility.is_empty(bot_id) or ActionUtility.is_empty(action): raise HttpActionFailure("Bot id and HTTP action configuration name not found in slot") db_url = ActionUtility.get_db_url() http_action_config: HttpActionConfig = ActionUtility.get_http_action_config(db_url=db_url, bot=bot_id, action_name=action) request_body = ActionUtility.prepare_request(tracker, http_action_config['params_list']) logger.debug("request_body: " + str(request_body)) http_response = ActionUtility.execute_http_request(auth_token=http_action_config['auth_token'], http_url=http_action_config['http_url'], request_method=http_action_config['request_method'], request_body=request_body) logger.debug("http response: " + str(http_response)) response = ActionUtility.prepare_response(http_action_config['response'], http_response) logger.debug("response: " + str(response)) # deepcode ignore W0703: General exceptions are captured to raise application specific exceptions except Exception as e: logger.error(str(e)) response = "I have failed to process your request" dispatcher.utter_message(response) return [SlotSet(response)]
def validate_goal_actions( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validate goal actions""" goal_intent = tracker.get_intent_of_latest_message() print (goal_intent) # Check if asking to explain action if goal_intent == "explain": dispatcher.utter_message(response="utter_explain_strategy") return {"goal_actions": None} return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: from_city_code = tracker.get_slot("departure") to_city_code = tracker.get_slot("destination") intent = tracker.get_intent_of_latest_message() print("得到的slot是") print(tracker.get_slot("departure")) print(tracker.get_slot("destination")) print("识别意图结果是" + intent) # if intent == "query_covid19_fromtopolicy": # from_city_code = next(tracker.get_latest_entity_values(entity_type="city", entity_role='departure')) # to_city_code = next(tracker.get_latest_entity_values(entity_type="city", entity_role='destination')) print(from_city_code, to_city_code) request_path = _create_path(ENDPOINTS["covid19_fromtopolicy"], from_city_code, to_city_code) results = requests.get(request_path) results = results.content.decode('utf-8') results = json.loads(results) results = results['data'] print(results) if results: from_city_name = results['depart_place']['city_name'] from_city_policy = results['depart_place']['leave_policy'] to_city_name = results['destination']['city_name'] to_city_policy = results['destination']['entrance_policy'] print(from_city_name, '\n', from_city_policy, '\n', to_city_name, '\n', to_city_policy) return [ SlotSet("from_city_name", from_city_name), SlotSet("from_city_policy", from_city_policy), SlotSet("to_city_name", to_city_name), SlotSet("to_city_policy", to_city_policy) ] else: print("No policy found.") return [ SlotSet("from_city_policy", "not found"), SlotSet("to_city_policy", "not found") ]
def prepare_request( tracker: Tracker, http_action_config_params: List[HttpActionRequestBody]): """ Prepares request body: 1. Fetches value of parameter from slot(Tracker) if parameter_type is slot and adds to request body 2. Adds value of parameter directly if parameter_type is value 3. Adds value of parameter as the sender_id. 4. Adds value of parameter as user_message. :param tracker: Tracker for the Http Action :param http_action_config_params: User defined request body parameters <key, value, parameter_type> :return: Request body for the HTTP request """ request_body = {} for param in http_action_config_params or []: if param['parameter_type'] == ActionParameterType.sender_id.value: value = tracker.sender_id elif param['parameter_type'] == ActionParameterType.slot.value: value = tracker.get_slot(param['value']) elif param[ 'parameter_type'] == ActionParameterType.user_message.value: value = tracker.latest_message.get('text') elif param['parameter_type'] == ActionParameterType.intent.value: value = tracker.get_intent_of_latest_message() elif param['parameter_type'] == ActionParameterType.chat_log.value: iat, msg_trail = ActionUtility.prepare_message_trail( tracker.events) value = { 'sender_id': tracker.sender_id, 'session_started': iat, 'conversation': msg_trail } else: value = param['value'] request_body[param['key']] = value logger.debug("value for key " + param['key'] + ": " + str(value)) return request_body
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: ultimo_intent = tracker.get_intent_of_latest_message() try: ultima_entidad = tracker.latest_message['entities'][0]['value'] except: dispatcher.utter_message( text='Es una buena pregunta, la verdad que no tengo idea.') return [] utter_a_responder = 'utter_' + ultimo_intent + '/' + ultima_entidad lista_acciones = domain['responses'] if utter_a_responder in lista_acciones: dispatcher.utter_message(response=utter_a_responder) else: dispatcher.utter_message( text= 'Es una buena pregunta, la verdad que no tengo idea. Preguntame alguna otra cosa, la segunda es la vencida.' ) return []
def validate_challenging_goal( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validate challenging goal""" goal_intent = tracker.get_intent_of_latest_message() print (goal_intent) # Check if challenging goal is no and ask them to restate the goal if value: return {"challenging_goal": True} else: if goal_intent == "deny": dispatcher.utter_message(response="utter_make_challenging_goal") return {"goal": None, "challenging_goal": None} else: dispatcher.utter_message(response="utter_explain_effortful") return {"challenging_goal": None}
def validate_persistent_goal( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validate persistent goal""" goal_intent = tracker.get_intent_of_latest_message() print (goal_intent) # Check if persistent goal is no if value: return {"persistent_goal": True} else: if goal_intent == "deny": dispatcher.utter_message(response="utter_make_persistent_goal") return {"persistent_goal": False} else: dispatcher.utter_message(response="utter_explain_persistence") return {"persistent_goal": None}
async def extract_city_spelled_correctly(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict) -> Dict[Text, Any]: intent = tracker.get_intent_of_latest_message() return {"city_spelled_correctly": intent == "affirm"}