async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict) -> List[EventType]: bind_logger(tracker) events = [SlotSet(SELF_ASSESS_DONE_SLOT, True)] ## Filling empty slots with previous day values slots_to_add = {} for last_slot in LAST_ASSESSMENT_SLOTS: current_slot = last_slot.replace(LAST_PREFIX, "") if tracker.get_slot(current_slot) is None: value = tracker.get_slot(last_slot) slots_to_add.update({current_slot: value}) try: save_assessment({**tracker.current_slot_values(), **slots_to_add}) except: logger.warn("Failed to save assessment", exc_info=True) if tracker.get_slot(SYMPTOMS_SLOT) == Symptoms.SEVERE: try: cancel_reminder(tracker.current_slot_values()) except: logger.warn("Failed to cancel reminder", exc_info=True) return events + [ SlotSet(key, value) for key, value in slots_to_add.items() ]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print(tracker.current_slot_values()) if(tracker.current_slot_values()['name'] != None): greet_msg=self.timeGreeting()+" !! "+tracker.current_slot_values()['name']+", "+self.randGreeting() else: greet_msg = self.timeGreeting() +" !!," + self.randGreeting() return [BotUttered(text=greet_msg)]
def generate_report_payload(tracker: Tracker) -> dict: """ Creates a filtration payload from report form slots. Parameters ---------- tracker: The state of conversation. Returns ------- Filtration payload. """ slots = tracker.current_slot_values() payload = dict() for slot in slots: if f"{slot}_selection" in slots: try: payload[slot] = loads(slots[f"{slot}_selection"]) except (JSONDecodeError, TypeError): payload[slot] = slots[f"{slot}_selection"] elif slot == "period": payload[slot] = loads(slots[slot]) return payload
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain): recipe_url = tracker.latest_message['text'] print(recipe_url) global recipe_manager recipe_manager = RecipeManager(recipe_url) print(recipe_url) print(tracker.current_state()) print(tracker.current_slot_values()) return_slots = [] if is_url_valid(recipe_url): print("is valid") validity = True dispatcher.utter_message(text="Url {} is valid".format(recipe_url)) return_slots.append(SlotSet("recipe_valid", validity)) return_slots.append(SlotSet("step_num", 0)) else: validity = False print("aint valid") dispatcher.utter_message( text="Url {} is invalid".format(recipe_url)) return_slots.append(SlotSet("recipe_valid", validity)) return return_slots
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: if tracker.get_slot(DO_ENROLL_SLOT) is True: try: ci_enroll(tracker.current_slot_values()) dispatcher.utter_message( template="utter_daily_ci_enroll__enroll_done_1") dispatcher.utter_message( template="utter_daily_ci_enroll__enroll_done_2") dispatcher.utter_message( template="utter_daily_ci_enroll__enroll_done_3") except: dispatcher.utter_message( template="utter_daily_ci_enroll__enroll_fail_1") dispatcher.utter_message( template="utter_daily_ci_enroll__enroll_fail_2") dispatcher.utter_message( template="utter_daily_ci_enroll__enroll_fail_3") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slot_dict = tracker.current_slot_values() #for slot_entry in slot_dict: # dispatcher.utter_message(str(slot_entry)) # dispatcher.utter_message(str(slot_dict[slot_entry])) ranked_col = tracker.get_slot("ranked_col") year = tracker.get_slot("year") top_bottom = tracker.get_slot("top_bottom") genre = tracker.get_slot("genre") if top_bottom == 'top': ascend_direction = False else: ascend_direction = True csv_row = int(tracker.get_slot('row_number')) sort_col = tracker.get_slot("sort_col") if genre == None: dispatcher.utter_message("genre is None") str1 = "COMMENT: getting "+ str(ranked_col) + " for year "+str(year) dispatcher.utter_message(str1) df=df_dict['movies'] ranked_col = slot_map[ranked_col] result = (df[df['release_date'].str[:4] == year].sort_values(by = [sort_col],ascending=ascend_direction))[ranked_col] limiter = int(csv_row) i = 0 str2 = "COMMENT: number of elements to show is "+str(limiter) dispatcher.utter_message(str2) for item in result: dispatcher.utter_message(str(item)) i = i+1 if i >= limiter: break dispatcher.utter_message("COMMENT: end of transmission") 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() if "dataset" in entities.keys() or "target" in entities.keys(): slots = {key:None for key,value in slots.items()} for name,value in entities.items(): slots[name] = value is_available, message, slots = required_data_available(slots) if is_available: dataset = slots["dataset"] graph_data = DataStorage.dataset_properties[dataset]["basicPlot"] message = DataStorage.dataset_properties[dataset]["message"] dispatcher.utter_message(json.dumps({"graph_data":graph_data, "message": message})) events = [SlotSet(slot_name,slot_value) for slot_name, slot_value in graph_data.items()] 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]]: slots = tracker.current_slot_values() print(tracker.latest_message['entities']) if not slots['recipe']: dispatcher.utter_message(text="Please input a valid recipe url before going over recipe steps.") return [] try: idx = slots['current_step'] + 1 steps = slots['recipe']['directions'] if len(tracker.latest_message['entities']) > 0: nth_value = tracker.latest_message['entities'][0]['value'].lower() # parse step from latest message for i in range(len(str_count_lookup)): if nth_value in str_count_lookup[i]: idx = i break dispatcher.utter_message(text="The " + translate_number(idx+1) + " step is: " + steps[idx]) return [SlotSet("current_step", idx)] except: dispatcher.utter_message(text="The nth step is out of range for this recipe. The recipe has a maximum of " + str(len(slots['recipe']['directions'])) + " steps.") return []
async def fetch_slots(tracker: Tracker) -> List[EventType]: """Add user profile to the slots if it is not set.""" slots = [] # Start by copying all the existing slots for key in tracker.current_slot_values().keys(): slots.append(SlotSet(key=key, value=tracker.get_slot(key))) user_channel = tracker.get_latest_input_channel() sender_id = tracker.sender_id user_profile = tracker.get_slot("user_profile") user_name = tracker.get_slot("user_name") db = Store() if user_profile is None: id = get_user_id_from_event(tracker) if id == anonymous_profile.get("id"): user_profile = anonymous_profile slots.append(SlotSet(key="user_profile", value=user_profile)) if user_name is None: slots.append( SlotSet(key="user_name", value=user_profile.get("name"))) return slots
async def fetch_slots(tracker: Tracker) -> List[EventType]: """Add user profile to the slots if it is not set.""" slots = [] # Start by copying all the existing slots for key in tracker.current_slot_values().keys(): slots.append(SlotSet(key=key, value=tracker.get_slot(key))) user_profile = tracker.get_slot("user_profile") user_name = tracker.get_slot("user_name") if user_profile is None: id = get_user_id_from_event(tracker) if id == anonymous_profile.get("id"): user_profile = anonymous_profile else: # Make an actual call to Snow API. user_profile = await snow.get_user_profile(id) slots.append(SlotSet(key="user_profile", value=user_profile)) if user_name is None: slots.append( SlotSet(key="user_name", value=user_profile.get("name"))) return slots
async def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: bind_logger(tracker) current_slot_values = tracker.current_slot_values() user_slots = _get_user_info(current_slot_values, domain) if user_slots is None: dispatcher.utter_message( template="utter_daily_ci_invalid_id_invalid_link") dispatcher.utter_message( template="utter_daily_ci_invalid_id_try_again") return [SlotSet(INVALID_REMINDER_ID_SLOT, True)] assessment_slots = _get_last_assessment_slots(current_slot_values) return [ SlotSet(name, value) for name, value in { **user_slots, **assessment_slots }.items() ]
def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: dispatcher.utter_message(template="utter_prompt_verse2") rhyme_with = tracker.current_slot_values()["where"] dispatcher.utter_message(text=format_rhymes(get_rhymes(rhyme_with))) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slots = tracker.current_slot_values() message = tracker.latest_message['text'].lower() base_url = 'https://www.youtube.com/results?' params = parse.urlencode({'search_query': message}) dispatcher.utter_message(text="No worries. I found a reference for you: " + base_url + params) return []
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: img_url = tracker.current_slot_values()["img"] res_string = await search_anime(img_url) dispatcher.utter_message(text=res_string) clear_slots = domain.get("forms", {})["搜动漫_form"]["required_slots"].keys() slots_data = domain.get("slots") print(f"cs: {clear_slots}") print(f"sd: {slots_data}") return [SlotSet(slot_name, slots_data.get(slot_name)['initial_value']) for slot_name in clear_slots]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slot_dict = tracker.current_slot_values() #for slot_entry in slot_dict: # dispatcher.utter_message(str(slot_entry)) # dispatcher.utter_message(str(slot_dict[slot_entry])) ranked_col = tracker.get_slot("ranked_col") language = tracker.get_slot("language") keyword = tracker.get_slot("keyword") castmember = tracker.get_slot("castmember") top_bottom = tracker.get_slot("top_bottom") csv_row = int(tracker.get_slot('row_number')) genre = tracker.get_slot("genre") sort_col = tracker.get_slot("sort_col") str1 = "COMMENT: getting "+ str(ranked_col) + " for cast "+str(castmember[0]) dispatcher.utter_message(str1) ''' df_movies=df_dict['movies'] df_keywords = df_dict['keywords'] ranked_col = slot_map[ranked_col] # interpret string of list from CSV as a Python list - moved to loading section to avoid copy being redone # df_keywords['keywords'] = df_keywords['keywords'].apply(lambda x: ast.literal_eval(x)) ## TODO this is gross - need a better way to get the list of ids output = list(filter(None,df_keywords.apply(lambda x: check_keyword_dict(dispatcher, x['id'],x['keywords'],keyword),axis=1))) #str3 = "here output " + str(len(output)) #str3 = "here 0 "+str(output[0]) +" here 1 "+ str(output[1]) #str5 = "len output "+ str(len(output)) # result = (df[df['release_date'].str[:4] == year].sort_values(by = [sort_col],ascending=ascend_direction))[ranked_col] result_big = df_movies.loc[df_movies['id'].isin(output)] result = df_movies[ranked_col][df_movies['id'].isin(output)] limiter = int(csv_row) str4 = "result len " + str(len(result)) #dispatcher.utter_message(str(str4)) i = 0 for item in result: dispatcher.utter_message(str(item)) i = i+1 if i >= limiter: break #dispatcher.utter_message(str(str3)) dispatcher.utter_message("COMMENT: genre sublist") if genre != None: genre = slot_map[genre] str5 = "genre is "+genre dispatcher.utter_message(str(str5)) genre_output = list(filter(None,result_big.apply(lambda x: check_keyword_dict(dispatcher, x[ranked_col],x['genres'],genre),axis=1))) for item in genre_output: dispatcher.utter_message(str(item)) i = i+1 if i >= limiter: break dispatcher.utter_message("COMMENT: end of transmission") ''' return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slots = tracker.current_slot_values() if not slots['recipe']: dispatcher.utter_message(text="Please input a valid recipe url before going over recipe steps.") return [] steps = slots['recipe']['directions'] idx = 0 dispatcher.utter_message(text="The 1st step is: " + steps[idx]) return [SlotSet("current_step", idx)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slots = tracker.current_slot_values() if not slots['recipe']: dispatcher.utter_message(text="Please input a valid recipe url first!") return [] idx = slots['current_step'] + 1 dispatcher.utter_message(text="Should I continue to the " + translate_number(idx+1) + " step?") return []
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: print(f"Result Slot Values: {tracker.current_slot_values()}") dispatcher.utter_message( "Thanks for getting in touch, we’ll contact you soon") with open(f'saves/saved_data{time.time()}.yml', 'w+') as save_file: yaml.dump(tracker.current_slot_values()) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slots = tracker.current_slot_values() if not slots['recipe']: dispatcher.utter_message(text="Please input a valid recipe url before going over ingredients.") return [] ingredients = slots['recipe']['ingredients'] # transform ingredients dict to string ingredients_str = '\n\n'.join(ingredients) dispatcher.utter_message(text="Here are the ingredients for \"" + slots['recipe']['title'] + "\":\n\n" + ingredients_str) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: ticket_attributes = {} for key, value in tracker.current_slot_values().items(): if value: ticket_attributes[key] = value response = requests.post('http://dummy_rest/Tickets/ticket', json=json.dumps(ticket_attributes)) response_text = json.loads(response.text) dispatcher.utter_message( response_text['ticketID'] + " has been logged successfully :simple_smile:") return []
def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: bind_logger(tracker) dispatcher.utter_message( template="utter_daily_ci__early_opt_out__acknowledge_cancel_ci") dispatcher.utter_message( template="utter_daily_ci__early_opt_out__cancel_ci_recommendation") cancel_reminder(tracker.current_slot_values()) return [SlotSet(CONTINUE_CI_SLOT, False)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slots = tracker.current_slot_values() if not slots['recipe']: dispatcher.utter_message(text="Please input a valid recipe url before going over recipe steps.") return [] steps = slots['recipe']['directions'] idx = slots['current_step'] - 1 if idx < 0: dispatcher.utter_message(text="First step has been reached. Cannot go further backwards.") return [] else: dispatcher.utter_message(text="The " + translate_number(idx+1) + " step is: " + steps[idx]) return [SlotSet("current_step", idx)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slots = tracker.current_slot_values() if not slots['recipe']: dispatcher.utter_message(text="Please input a valid recipe url before going over recipe steps.") return [] steps = slots['recipe']['directions'] idx = slots['current_step'] + 1 if idx >= len(steps): dispatcher.utter_message(text="Last step has been reached. Resetting back to beginning step if asked again.") return [SlotSet("current_step", -1)] else: dispatcher.utter_message(text="The " + translate_number(idx+1) + " step is: " + steps[idx]) return [SlotSet("current_step", idx)]
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 "time" in entities.keys(): time = entities["time"] filter_name = "period" filter_value = self.create_time_filter_string(time["from"], time["to"]) elif "filter_name" in entities.keys() and "filter_value" in entities.keys(): filter_name = entities["filter_name"] filter_value = entities["filter_value"] else: # TODO return filter_new = {"filter_name":filter_name, "filter_value": filter_value} filter_old = slots["filter_list"] if filter_old is not None: filter_new = filter_old + [filter_new] else: filter_new = [filter_new] graph_data = slots graph_data["filter_list"] = filter_new graph_data["data_type"] = data_type dispatcher.utter_message(json.dumps({"graph_data":graph_data, "message": None})) events = [SlotSet("filter_list", filter_new), 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
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict) -> List[EventType]: bind_logger(tracker) extracted_slots: Dict[Text, Any] = tracker.form_slots_to_validate() validation_events: List[EventType] = [] for slot_name, slot_value in extracted_slots.items(): slot_events = [SlotSet(slot_name, slot_value)] if slot_name == FIRST_NAME_SLOT: slot_events = _validate_first_name(slot_value, dispatcher) elif slot_name == PHONE_NUMBER_SLOT: slot_events = await _validate_phone_number( slot_value, dispatcher, tracker) elif slot_name == VALIDATION_CODE_SLOT: slot_events = await _validate_validation_code( slot_value, dispatcher, tracker) elif slot_name == NO_CODE_SOLUTION_SLOT: slot_events = await _validate_no_code_solution( slot_value, dispatcher, tracker) elif slot_name == PRECONDITIONS_SLOT: slot_events = _validate_preconditions(slot_value, dispatcher, tracker) elif slot_name == HAS_DIALOGUE_SLOT: # last slot, enrollment completed try: ci_enroll(tracker.current_slot_values()) dispatcher.utter_message( template="utter_daily_ci_enroll_form_done_1") dispatcher.utter_message( template="utter_daily_ci_enroll_form_done_2") dispatcher.utter_message( template="utter_daily_ci_enroll_form_done_3") except: dispatcher.utter_message( template="utter_daily_ci_enroll_form_fail_1") dispatcher.utter_message( template="utter_daily_ci_enroll_form_fail_2") dispatcher.utter_message( template="utter_daily_ci_enroll_form_fail_3") validation_events.extend(slot_events) return validation_events
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logging.info( json.dumps(tracker.current_slot_values(), indent=2, ensure_ascii=False)) prop = lambda attr: tracker.get_slot(attr ) if attr in tracker.slots else '' object_type = tracker.get_slot('object_type') dispatcher.utter_message( json_message={ 'result': 'success', 'media_list': ['first song', 'second song'], 'media_type': object_type, 'sents': prop('sents') }) # return [SlotSet("media_type", object_type)] return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logger.info( json.dumps(tracker.current_slot_values(), indent=2, ensure_ascii=False)) # entities = tracker.latest_message.get("entities", []) # entity_type='verb_domains' # additional_info=next(x.get("additional_info") for x in entities if x.get("entity") == entity_type) # logger.info(json.dumps(additional_info, indent=2, ensure_ascii=False)) dump_ents_info(tracker) dispatcher.utter_message(json_message={ 'result': 'success', 'product_list': ['first prod', 'second prod'], }) return []
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)]
async def fetch_slots( tracker: Tracker, dispatcher: CollectingDispatcher) -> List[EventType]: """ Add user profile to the slots if it is not set. """ slots = [] # Start by copying all the existing slots for key in tracker.current_slot_values().keys(): slots.append(SlotSet(key=key, value=tracker.get_slot(key))) user_profile = tracker.get_slot("user_profile") user_name = tracker.get_slot("user_name") user_email = tracker.get_slot("user_email") if user_profile is None: # id = get_user_id_from_event(tracker) # Injecting sys_id so that I can work in Rasa shell # id = "a8f98bb0eb32010045e1a5115206fe3a" # Abraham Lincoln id = "0a826bf03710200044e0bfc8bcbe5d7a" # Adela Cervantsz if id == anonymous_profile.get("id"): user_profile = anonymous_profile else: # Make an actual call to Snow API. user_profile = await snow.get_user_profile(id) if user_profile is None: dispatcher.utter_message(template="utter_no_connection") user_profile = anonymous_profile slots.append(SlotSet(key="user_profile", value=user_profile)) if user_name is None: slots.append(SlotSet(key="user_name", value=user_profile.get("name"))) if user_email is None: slots.append(SlotSet(key="user_email", value=user_profile.get("email"))) return slots
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print("Getting COVID-19 API results!!!") tracker_obj = COVID_Tracker() bot_response = tracker_obj.get_bot_response( tracker.current_slot_values(), tracker.latest_message['entities']) print(bot_response) if bot_response["status"]: file_path = bot_response["file_name"] dispatcher.utter_message(text=bot_response["bot_msg"], image=file_path) else: dispatcher.utter_message( text="Please try after some time. ", image= "http://ec2-13-126-127-146.ap-south-1.compute.amazonaws.com:5020/img/minion-oops.jpg" ) return [AllSlotsReset()]