def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: tracker.get_slot("nationality") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict) -> List[EventType]: return [SlotSet("detailed_faq", not tracker.get_slot("detailed_faq"))]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print(tracker.get_slot('cust_name')) print(tracker.get_slot('cust_cmnd')) print(tracker.get_slot('cust_account_number')) return [SlotSet("name", None)]
def required_slots(tracker: Tracker) -> List[Text]: objective = tracker.get_slot("selected_objective") if objective: return ["kr_title", "kr_start_value", "kr_goal_value"] else: # skip this form if objective is not selected return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: post_package = tracker.get_slot('post_package') duration = tracker.get_slot('duration') duration, duration_value, duration_unit, _ = convert_duration(duration) vip_type = convert_post_package(post_package) fee_table = self.fee_table if vip_type is not None: # nếu chỉ bắt được post_package if duration == None: dispatcher.utter_message( text="Giá gói {} hiện tại là {}đ/tin/ngày ạ.".format( fee_table[vip_type]['name'], price_format(fee_table[vip_type]['fee'][1]))) message = 'Ngoài ra MeeyLand còn có các gói' for package in fee_table: if package != vip_type: message += ' {} với giá {}đ/tin/ngày,'.format( fee_table[package]['name'], price_format(fee_table[package]['fee'][1])) message = message[:-1] + ' ạ.' dispatcher.utter_message(message) return [ SlotSet("post_package", None), SlotSet("duration", None) ] # nếu bắt dc cả 2 else: cost = fee_table[vip_type]['fee'][ 1] * duration_value * self.coefficient[duration_unit][ 'coef'] text_unit = self.coefficient[duration_unit]['text'] message = 'Gói {} trong {} {} có giá {}đ ạ'.format( fee_table[vip_type]['name'], duration_value, text_unit, price_format(cost)) dispatcher.utter_message(message) return [ SlotSet("post_package", None), SlotSet("duration", None) ] # Nếu chỉ bắt dc duration elif duration != None: message = 'Không biết bạn muốn hỏi về gói vip nào ạ' dispatcher.utter_message(message) message = 'Hiện tại bên em đang có 3 gói đăng tin vip là VIP1, VIP2 và VIP3 ạ.' dispatcher.utter_message(message) return [SlotSet("post_package", None), SlotSet("duration", None)] # Còn lại là trường hợp không bắt được gì text = tracker.get_last_event_for('user')['text'] if 'vip' in text: message = 'Hiện tại Meeyland cung cấp {} gói tin VIP là'.format( len(fee_table)) for package in fee_table: message += ' gói {} giá {}đ/tin/ngày,'.format( fee_table[package]['name'], price_format(fee_table[package]['fee'][1])) message = message[:-1] + ' ạ.' dispatcher.utter_message(message) dispatcher.utter_message( "Bạn có thể tham khảo chi tiết bảng giá tại [đây](https://meeyland.com/page/bao-gia)" ) return [SlotSet("post_package", None), SlotSet("duration", None)] else: message = 'Hiện tại Meeyland cung cấp {} gói tin là'.format( len(fee_table) + 1) for package in fee_table: message += ' gói {} giá {}đ/tin/ngày,'.format( fee_table[package]['name'], price_format(fee_table[package]['fee'][1])) message = message[:-1] + ' và gói tin thường miễn phí ạ.' dispatcher.utter_message(message) dispatcher.utter_message( "Bạn có thể tham khảo chi tiết bảng giá tại [đây](https://meeyland.com/page/bao-gia)" ) return [SlotSet("post_package", None), SlotSet("duration", None)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # url = str.__add__('http://data.fixer.io/api/latest?access_key=', 'AWPO998N8W05HK1K') # c = Currency_convertor(url); dola = ['đô','đô la','đô la mỹ','usd','$'] bang = ['bảng','bảng anh','gbp'] yen = ['yên','yên nhật','jpy'] ndt = ['nhân dân tệ','cny'] eur = ['eur','euro','€'] vnd = ['tiền việt','vnd'] from_country = tracker.get_slot('currency_from') to_country = tracker.get_slot('currency_to') # from_country = next(from_country) # to_country = next(to_country) print(from_country) if from_country == None: dispatcher.utter_message(text=f'Xin lỗi, tôi không tìm thấy tỉ giá ') return [] else: if from_country.lower() in dola: from_country = 'usd' elif from_country.lower() in bang: from_country = 'gbp' elif from_country.lower() in yen: from_country = 'jpy' elif from_country.lower() in ndt: from_country = 'cny' elif from_country.lower() in eur: from_country = 'eur' elif from_country.lower() in vnd: from_country = 'vnd' else: dispatcher.utter_message(text=f'Xin lỗi, tôi không tìm thấy tỉ giá này') return [] if to_country == None: to_country = 'vnd' else: if to_country.lower() in dola: to_country = 'usd' elif to_country.lower() in bang: to_country = 'gbp' elif to_country.lower() in yen: to_country = 'jpy' elif to_country.lower() in ndt: to_country = 'cny' elif to_country.lower() in eur: to_country = 'eur' elif to_country.lower() in vnd: to_country = 'vnd' else: dispatcher.utter_message(text=f'Xin lỗi, tôi không tìm thấy tỉ giá này') return [] amount = tracker.get_latest_entity_values(entity_type="number"); amount = next(amount) if (amount == None): amount = 1 # Where USD is the base currency you want to use url = 'https://v6.exchangerate-api.com/v6/1787641525100381f898281f/latest/'+ from_country.upper() # Making our request print(to_country.upper()) response = requests.get(url) data = response.json() rate = data['conversion_rates'][to_country.upper()] dispatcher.utter_message(text=f'{amount} {from_country.upper()} = {amount*rate} {to_country.upper()}') return[SlotSet("currency_to", 'vnd')]
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: """Define what the form has to do after all required slots are filled""" email = tracker.get_slot(EntitySlotEnum.EMAIL) incident_title = tracker.get_slot(EntitySlotEnum.INCIDENT_TITLE) incident_description = tracker.get_slot( EntitySlotEnum.INCIDENT_DESCRIPTION) # priority = tracker.get_slot(EntitySlotEnum.PRIORITY) itilcategory_id = tracker.get_slot(EntitySlotEnum.ITILCATEGORY_ID) events = [ SlotSet(EntitySlotEnum.EMAIL, None), SlotSet(EntitySlotEnum.INCIDENT_TITLE, None), SlotSet(EntitySlotEnum.INCIDENT_DESCRIPTION, None), # SlotSet(EntitySlotEnum.PRIORITY, None), SlotSet(EntitySlotEnum.ITILCATEGORY_ID, None), SlotSet(EntitySlotEnum.CONFIRM, None), ] if tracker.get_slot(EntitySlotEnum.CONFIRM): # Check priority and set number value accordingly # priorities = GLPIService.priority_values() # priority_values = list(priorities.keys()) # if priority in priority_values: # glpi_priority = priorities[priority] # else: # logger.warning(f'Priority value not found: {priority}. Setting it to default: (media)') # glpi_priority = priorities[priority_values[1]] ticket: Ticket = Ticket({ "username": "******", # TODO: set the actual logged in user "title": incident_title, "description": remove_accents(incident_description), # 'priority': glpi_priority "itilcategories_id": int(itilcategory_id), "alternative_email": email, # TODO: set as conditional if username is not logged in }) if local_mode: dispatcher.utter_message( f"Esta acción crearía un ticket con la siguiente información: {ticket}" ) ticket_id = "DUMMY" events.append(SlotSet(EntitySlotEnum.TICKET_NO, ticket_id)) else: # TODO: integrate with GLPI try: response = glpi.create_ticket(ticket) ticket_id = response["id"] # This is not actually required as its value is sent directly to the utter_message events.append(SlotSet(EntitySlotEnum.TICKET_NO, ticket_id)) except GlpiException as e: logger.error("Error when trying to create a ticket", e) logger.error(f"Ticket: {ticket}") dispatcher.utter_message( template=UtteranceEnum.PROCESS_FAILED) return events dispatcher.utter_message(template=UtteranceEnum.TICKET_NO, ticket_no=ticket_id) dispatcher.utter_message(template=UtteranceEnum.CONFIRM_REQUEST) else: events.append(SlotSet(EntitySlotEnum.TICKET_NO, None)) dispatcher.utter_message(template=UtteranceEnum.PROCESS_CANCELLED) return events
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: """Define what the form has to do after all required slots are filled""" search_type = tracker.get_slot("search_type") transaction_history = tracker.get_slot("transaction_history") transactions_subset = transaction_history.get(search_type, {}) vendor = tracker.get_slot("vendor_name") if vendor: transactions = transactions_subset.get(vendor.lower()) vendor = f" with {vendor}" else: transactions = [ v for k in list(transactions_subset.values()) for v in k ] vendor = "" time_range = tracker.get_slot("time") if ("to" not in time_range) or ("from" not in time_range): from_date = date.fromisoformat(time_range.split("T")[0]) to_date = date.today() else: from_date = date.fromisoformat( time_range.get("from").split("T")[0]) to_date = date.fromisoformat(time_range.get("to").split("T")[0]) for i in range(len(transactions) - 1, -1, -1): transaction = transactions[i] transaction_date = date.fromisoformat(transaction.get("date")) if transaction_date < from_date or transaction_date > to_date: transactions.pop(i) numtransacts = len(transactions) total = sum([t.get("amount") for t in transactions]) slotvars = { "total": f"{total:.2f}", "numtransacts": numtransacts, "start_time": tracker.get_slot("start_time"), "end_time": tracker.get_slot("end_time"), "grain": tracker.get_slot("grain"), "vendor_name": vendor, } dispatcher.utter_message( template=f"utter_searching_{search_type}_transactions", **slotvars) dispatcher.utter_message( template=f"utter_found_{search_type}_transactions", **slotvars) return [ SlotSet("time", None), SlotSet("start_time", None), SlotSet("end_time", None), SlotSet("grain", None), SlotSet("search_type", None), SlotSet("vendor_name", None), ]
async 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. """ bot_response = None http_response = None exception = None action = None request_body = None status = "SUCCESS" http_url = None 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" ) http_action_config: HttpActionConfig = ActionUtility.get_http_action_config( bot=bot_id, action_name=action) http_url = http_action_config['http_url'] 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)) bot_response = ActionUtility.prepare_response( http_action_config['response'], http_response) logger.debug("response: " + str(bot_response)) # deepcode ignore W0703: General exceptions are captured to raise application specific exceptions except Exception as e: exception = str(e) logger.error(exception) status = "FAILURE" bot_response = "I have failed to process your request" finally: dispatcher.utter_message(bot_response) HttpActionLog(intent=tracker.get_intent_of_latest_message(), action=action, sender=tracker.sender_id, url=http_url, request_params=request_body, api_response=str(http_response), bot_response=str(bot_response), exception=exception, bot=tracker.get_slot("bot"), status=status).save() return [SlotSet(KAIRON_ACTION_RESPONSE_SLOT, bot_response)]
def run( self, dispatcher, tracker: Tracker, domain: "DomainDict", ) -> List[Dict[Text, Any]]: # cid=DataUpdate(tracker.get_slot("name"),tracker.get_slot("number"),tracker.get_slot("lname"),tracker.get_slot("branch"),tracker.get_slot("cgpa"),tracker.get_slot("email"),tracker.get_slot("lang")) # print(cid) # SlotSet("cid",cid) dispatcher.utter_message(template="utter_details_thanks", FName=tracker.get_slot("name"), LName=tracker.get_slot("lname"), Branch=tracker.get_slot("branch"), CGPA=tracker.get_slot("cgpa"), Email=tracker.get_slot("email"), Coding_Language=tracker.get_slot("lang"), Mobile_number=tracker.get_slot("number"), Candidate_id=tracker.get_slot("cid")) # return(SlotSet("cid",cid)) DataUpdate(tracker.get_slot("name"), tracker.get_slot("number"), tracker.get_slot("lname"), tracker.get_slot("branch"), tracker.get_slot("cgpa"), tracker.get_slot("email"), tracker.get_slot("lang"))
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: object_name = tracker.get_slot('object_name') object_color = tracker.get_slot('object_color') placement = tracker.get_slot('placement') if placement in valid_placements: placement_origin = placement else: placement_origin = "middle" # # dispatcher.utter_message(text="Hang on, I'll try to search in the {} area of the table for the object you want me to learn".format( # placement_origin # )) if ENABLE_ROS: nlp_node.send_command(action="show", object=object_name, obj_color=object_color, placement_origin=placement_origin, placement_destination=None) response = nlp_node.wait_for_response() try: msg, path_2dimg, path_3dimg = response except Exception: msg, path_2dimg = response if msg is not None: imgpath = path_2dimg print("Image saved at {}".format(imgpath)) print("Found object: {}".format(msg.desired_color, msg.found_obj)) imgurl = "http://localhost:8888/{}?time={}".format( imgpath, int(time.time())) dispatcher.utter_attachment(None, image=imgurl) if msg.found_obj: # dispatcher.utter_message(text="I found the {} {} in the {} area of the platform.".format( # msg.desired_color, # object_name, # placement_origin)) dispatcher.utter_message(template="utter_got_description") update_known_objects([object_name]) update_known_colors([object_color]) else: dispatcher.utter_message( text= "Sorry, I didn't find any object. Make sure the {} {} you want to show me is in the {} area of the platform." .format(msg.desired_color, object_name, placement_origin)) else: dispatcher.utter_message(template="utter_command_failed") # dispatcher.utter_message(text="Error: {}".format(info)) return [AllSlotsReset()] else: dispatcher.utter_message(template="utter_got_description") return [AllSlotsReset()]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: """ Trả về generic template 6 sản phẩm hot + quick replies đòi xem thêm :param dispatcher: :param tracker: :param domain: :return: """ # debug('\n_________act_shoe_new_shoe_________') print('_____' + self.name()) prefix_name = tracker.get_slot(Entities.prefix_name) customer_name = tracker.get_slot(Entities.customer_name) bot_position = tracker.get_slot(Entities.bot_position) err_message = f'Xin lỗi {prefix_name}{customer_name}, hệ thống đã xảy ra lỗi. ' query = ''' select distinct mainapp_shoe.id as shoe_id, mainapp_shoe.shoeName, mainapp_shoe.shoeModel, mainapp_shoe.viewCount, mainapp_shoe.quantitySold, mainapp_shoe.image_static, mainapp_shoe.favouriteCount, mainapp_shoe.shoeThumbnail, mainapp_category.categoryName, mainapp_detailshoe.newPrice, sum(mainapp_detailshoe.quantityAvailable) as totalQuantityAvailable, (mainapp_shoe.viewCount + mainapp_shoe.quantitySold + mainapp_shoe.favouriteCount) as hotCount, datediff(curdate(), mainapp_shoe.dateCreated) as days, ((mainapp_shoe.viewCount + mainapp_shoe.quantitySold + mainapp_shoe.favouriteCount)/datediff(curdate(), mainapp_shoe.dateCreated)) as hotRate from mainapp_shoe inner join mainapp_detailshoe on mainapp_shoe.id = mainapp_detailshoe.shoe_id inner join mainapp_category on mainapp_shoe.category_id = mainapp_category.id where active = 1 group by mainapp_shoe.id, mainapp_shoe.shoeName, mainapp_shoe.shoeModel, mainapp_shoe.viewCount, mainapp_shoe.quantitySold, mainapp_shoe.favouriteCount, mainapp_shoe.shoeThumbnail, mainapp_shoe.image_static, mainapp_category.categoryName, mainapp_detailshoe.newPrice having totalQuantityAvailable > 0 order by hotRate desc limit 0, 5; ''' shoes = SqlUtils.get_result(query, Shoe) detail_shoes = SqlUtils.get_result(query, DetailShoe) if len(shoes) == 0: err_code = ErrorCode.ERR_IN_ACT_GET_NEW_SHOE err_message = err_message + 'error code=' + err_code dispatcher.utter_message(err_message) else: dispatcher.utter_message( text='Dưới đây là top những đôi đc mọi người xem và mua nhiều nhất đó ' + prefix_name + customer_name) # horizontal_template_elements = [] # for index in range(len(shoes)): # shoe = shoes[index] # detail_shoe = detail_shoes[index] # # buttons = [ # PostBackButton( # title='Xem đôi này ' + shoe.shoeModel, # str_send_to_webhook='tôi muốn xem mẫu ' + shoe.shoeModel # ), # UrlButton( # title='Xem trên website', # url_access=MyWebUrl.get_detail_shoe_url(shoe.shoe_id) # ), # ] # # element = HorizontalTemplateElement( # image_url=shoe.shoeThumbnail, # title=shoe.shoeName, # subtitle=price_format(detail_shoe.newPrice), # default_action='', # list_buttons=buttons, # ) # horizontal_template_elements.append(element) # horizontal_template = HorizontalTemplate(horizontal_template_elements) horizontal_template = HorizontalTemplate.from_shoes_detail_shoe(shoes=shoes, detail_shoes=detail_shoes) dispatcher.utter_message(json_message=horizontal_template.to_json_message()) # xem tiep quick_reply_elements = [ QuickReplyElement(QuickReplyElement.TEXT, 'Xem thêm', 'còn đôi nào khác k?'), QuickReplyElement(QuickReplyElement.TEXT, 'Xem lại menu', 'tôi muốn xem menu'), ] quick_replies = QuickReplies(text_before_template='', list_quick_reply_elements=quick_reply_elements) dispatcher.utter_message(json_message=quick_replies.to_json_message()) # xem tiep quick_reply_elements = [ QuickReplyElement(QuickReplyElement.TEXT, 'Xem thêm', 'còn đôi nào khác k?'), QuickReplyElement(QuickReplyElement.TEXT, 'Thôi', 'tôi muốn xem menu'), ] quick_replies = QuickReplies(text_before_template='Xin hãy chọn một hành động', list_quick_reply_elements=quick_reply_elements) dispatcher.utter_message(json_message=quick_replies.to_json_message()) return []
def required_slots(tracker: Tracker) -> List[Text]: objectives_list = tracker.get_slot("objectives_list") if objectives_list: return ["selected_objective_number"] else: return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: """ Trả về generic template san pham cuoi va ask them vao gio hang/thanh toan :param dispatcher: :param tracker: :param domain: :return: """ # debug('\n_________act_shoe_new_shoe_________') print('_____' + self.name()) prefix_name = tracker.get_slot(Entities.prefix_name) customer_name = tracker.get_slot(Entities.customer_name) customer_id = tracker.current_state()["sender_id"] bot_position = tracker.get_slot(Entities.bot_position) shoe_id = tracker.get_slot(Entities.shoe_id) shoe_model = tracker.get_slot(Entities.shoe_model) shoe_size = tracker.get_slot(Entities.shoe_size) color_id = tracker.get_slot(Entities.color_id) color_name = tracker.get_slot(Entities.shoe_color) # get user id by messenger id query = f''' select id as user_id from account_user where messengerId = {customer_id}; ''' users = SqlUtils.get_result(query, User) if len(users) == 0: # chua tao tai khoan cho user err_code = ErrorCode.ERR_IN_ACT_ADD_TO_CARD err_message = f'Xin lỗi {prefix_name}{customer_name}, hệ thống đã xảy ra lỗi. Không thể thêm vào giỏ hàng.' \ f' error code={err_code}' dispatcher.utter_message(text=err_message) return [] # neu them vao gio hang ma chua chon size, color thi chon size, color mac dinh if shoe_size is None or color_id is None: query = f''' select mainapp_shoe.shoeName, mainapp_shoe.shoeThumbnail, mainapp_shoe.image_static, mainapp_detailshoe.newPrice, mainapp_detailshoe.size, mainapp_color.colorName, mainapp_color.id as color_id from mainapp_detailshoe inner join mainapp_shoe on (mainapp_shoe.id = mainapp_detailshoe.shoe_id) inner join mainapp_color on (mainapp_color.id = mainapp_detailshoe.color_id) where mainapp_shoe.active = 1 and mainapp_detailshoe.quantityAvailable > 0 and mainapp_shoe.id = 8 ; ''' detail_shoes, shoes, colors = SqlUtils.get_result( query, DetailShoe, Shoe, Color) if len(detail_shoes) > 0: shoe_size = detail_shoes[0].size color_id = colors[0].color_id user = users[0] debug.debug_print_content('________act add to cart________') debug.debug_print_content(f'user id: {user.user_id}') debug.debug_print_content(f'color id: {color_id}') debug.debug_print_content(f'size id: {shoe_size}') result = MyWebApi.add_to_cart(user.user_id, shoe_id, color_id, shoe_size) debug.debug_print_content(f'result: {result}') if result.status_code == 201: text = 'Thêm vào giỏ hàng thành công' else: text = 'Thêm vào giỏ hàng thất bại' dispatcher.utter_message(text=text) # xem tiep quick_reply_elements = [ QuickReplyElement(QuickReplyElement.TEXT, 'Xem giỏ hàng', 'cho xem giỏ hàng'), QuickReplyElement(QuickReplyElement.TEXT, 'Đặt hàng luôn', 'đặt hàng luôn'), QuickReplyElement(QuickReplyElement.TEXT, 'Xem lại menu', 'tôi muốn xem menu'), ] quick_replies = QuickReplies( text_before_template='Tùy chọn khác', list_quick_reply_elements=quick_reply_elements) # dispatcher.utter_message(json_message=quick_replies.to_json_message()) return []
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: """Define what the form has to do after all required slots are filled""" book_type = tracker.get_slot("book_type") start_time = tracker.get_slot("start_time") time2 = tracker.get_slot("time2") dispatcher.utter_message("date {}".format(start_time)) if book_type == "book" or book_type == "test": DataUpdate("update", tracker.get_slot("PERSON"), start_time, time2) dispatcher.utter_message(template="utter_name_time_confirm",) else: DataUpdate("delete", tracker.get_slot("PERSON"), None, None) dispatcher.utter_message(template="utter_name__confirm") return [] # def custom_request_next_slot( # form, # dispatcher: "CollectingDispatcher", # tracker: "Tracker", # domain: Dict[Text, Any], # ) -> Optional[List[EventType]]: # """Request the next slot and utter template if needed, # else return None""" # # for slot in form.required_slots(tracker): # if form._should_request_slot(tracker, slot): # logger.debug(f"Request next slot '{slot}'") # dispatcher.utter_message( # template=f"utter_ask_{form.name()}_{slot}", **tracker.slots # ) # return [SlotSet(REQUESTED_SLOT, slot)] # # return None # # # class TransactSearchForm(FormAction): # """Transaction search form""" # def name(self) -> Text: # """Unique identifier of the form""" # return "transact_search_form" # # def request_next_slot( # self, # dispatcher: "CollectingDispatcher", # tracker: "Tracker", # domain: Dict[Text, Any], # ) -> Optional[List[EventType]]: # return custom_request_next_slot(self, dispatcher, tracker, domain) # # @staticmethod # def required_slots(tracker: Tracker) -> List[Text]: # """A list of required slots that the form has to fill""" # return ["search_type", "time"] # # def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]: # """A dictionary to map required slots to # - an extracted entity # - intent: value pairs # - a whole message # or a list of them, where a first match will be picked""" # return { # # "vendor_name": self.from_entity(entity="vendor_name"), # "time": [self.from_entity(entity="time")], # "search_type": [ # self.from_trigger_intent( # intent="book_appointment", value="spend" # ), # self.from_trigger_intent( # intent="check_earnings", value="deposit" # ), # ], # } # # def validate_time( # self, # value: Text, # dispatcher: CollectingDispatcher, # tracker: Tracker, # domain: Dict[Text, Any], # ) -> Dict[Text, Any]: # """Validate time value.""" # timeentity = get_entity_details(tracker, "time") # parsedinterval = parse_duckling_time_as_interval(timeentity) # if not parsedinterval: # dispatcher.utter_message(template="utter_no_transactdate") # return {"time": None} # return parsedinterval # # def submit( # self, # dispatcher: CollectingDispatcher, # tracker: Tracker, # domain: Dict[Text, Any], # ) -> List[Dict]: # """Define what the form has to do # after all required slots are filled""" # search_type = tracker.get_slot("search_type") # # DataUpdate(tracker.get_slot("PERSON"),tracker.get_slot("time"),tracker.get_slot("time2")) # dispatcher.utter_message( # template=f"utter_", # ) # return [ # ] # # # class TransferForm(FormAction): # """Transaction search form""" # def name(self) -> Text: # """Unique identifier of the form""" # return "transfer_form" # # @staticmethod # def required_slots(tracker: Tracker) -> List[Text]: # """A list of required slots that the form has to fill""" # return ["PERSON"] # # def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]: # """A dictionary to map required slots to # - an extracted entity # - intent: value pairs # - a whole message # or a list of them, where a first match will be picked""" # return { # "PERSON": [self.from_entity(entity="PERSON")], # } # # def submit( # self, # dispatcher: CollectingDispatcher, # tracker: Tracker, # domain: Dict[Text, Any], # ) -> List[Dict]: # """Define what the form has to do # after all required slots are filled""" # DataUpdate(tracker.get_slot("PERSON")) # dispatcher.utter_message( # template="utter_name", # ) # return [ # ] # @staticmethod # def transactions_db() -> Dict[Text, Any]: # """Database of transactions""" # return { # "spend": { # "starbucks": [{"amount": 5.50}, {"amount": 9.10}], # "amazon": [ # {"amount": 35.95}, # {"amount": 9.35}, # {"amount": 49.50}, # ], # "target": [{"amount": 124.95}], # }, # "deposit": { # "employer": [{"amount": 1250.00}], # "interest": [{"amount": 50.50}], # }, # } # @staticmethod # def vendor_name_db() -> List[Text]: # return [ # "emergency", # "target", # "routine", # ] # def validate_vendor_name( # self, # value: Text, # dispatcher: CollectingDispatcher, # tracker: Tracker, # domain: Dict[Text, Any], # ) -> Dict[Text, Any]: # """Validate vendor_name value.""" # if value and value.lower() in self.vendor_name_db(): # return {"vendor_name": value} # else: # dispatcher.utter_message(template="utter_no_vendor_name") # return {"vendor_name": None} # transactions_subset = self.transactions_db().get(search_type, {}) # vendor = tracker.get_slot("vendor_name") # if vendor: # transactions = transactions_subset.get(vendor.lower()) # vendor = f" with {vendor}" # else: # transactions = [ # v for k in list(transactions_subset.values()) for v in k # ] # vendor = "" # numtransacts = len(transactions) # total = sum([t.get("amount") for t in transactions])
def required_slots(tracker: Tracker) -> List[Text]: if tracker.get_slot("first_time") == True: return ["first_time", "given_name", "location"] else: return ["first_time"]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("====Inside ActionAskCuisine====") print() # print("tracker: ",) channel=tracker.get_latest_input_channel() location=tracker.get_slot("location") cuisine=tracker.get_slot("cuisine") lat=tracker.get_slot("latitude") lon=tracker.get_slot("longitude") locationEntity=next(tracker.get_latest_entity_values("location"), None) cuisineEntity=next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity=next(tracker.get_latest_entity_values("user_location"), None) latEntity=next(tracker.get_latest_entity_values("latitude"), None) lonEntity=next(tracker.get_latest_entity_values("longitude"), None) location=tracker.get_slot("location") cuisine=tracker.get_slot("cuisine") lat=tracker.get_slot("latitude") lon=tracker.get_slot("longitude") entity_id=tracker.get_slot("location_id") entity_type=tracker.get_slot("location_type") city_id=tracker.get_slot("city_id") if(latEntity and lonEntity): lat=latEntity lon=lonEntity if(user_locationEntity or (latEntity and lonEntity) ): if(lat==None and lon==None): dispatcher.utter_message(text="Sure, please allow me to access your location 🧐",json_message={"payload":"location"}) return [] else: locationEntities=zomatoApi.getLocationDetailsbyCoordinates(lat,lon) location=locationEntities["title"] city_id=locationEntities["city_id"] entity_id=locationEntities["entity_id"] entity_type=locationEntities["entity_type"] SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) if(locationEntity): locationEntities=zomatoApi.getLocationDetailsbyName(locationEntity) entity_id=locationEntities["entity_id"] entity_type=locationEntities["entity_type"] city_id=locationEntities["city_id"] SlotSet("location", locationEntities["title"]) print("locationDetails: ",locationEntities) print() ## check if the restaurants are available in the user provided location if(locationEntities["restaurants_available"]=="no"): dispatcher.utter_message("Sorry, No restaurants available in the location you have provided 🤯") return [UserUtteranceReverted()] else: locationDetails=zomatoApi.getLocationDetails(locationEntities["entity_id"],locationEntities["entity_type"]) if channel=="slack": dispatcher.utter_message(template="utter_ask_cuisine",buttons=locationDetails["top_cuisines"]) else: dispatcher.utter_message(template="utter_ask_cuisine",json_message={"payload":"quickReplies","data":locationDetails["top_cuisines"]}) return [SlotSet("city_id", locationEntities["city_id"]),SlotSet("location_id", locationEntities["entity_id"]),SlotSet("location_type", locationEntities["entity_type"])]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slot_name = tracker.get_slot('field_name') return [SlotSet(slot_name, None)]
def submit(self,dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text,Any],)->List[Dict]: print(tracker.get_slot('fback')) dispatcher.utter_message(template="utter_submit",name=tracker.get_slot('name'),email=tracker.get_slot('email'),fback=tracker.get_slot('fback')) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: email = tracker.get_slot('email') phone_number = tracker.get_slot('phone_number') return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("====Inside ActionSearchRestaurants====") print() ## extract the required slots location=tracker.get_slot("location") cuisine=tracker.get_slot("cuisine") lat=tracker.get_slot("latitude") lon=tracker.get_slot("longitude") entity_id=tracker.get_slot("location_id") entity_type=tracker.get_slot("location_type") city_id=tracker.get_slot("city_id") ## extract the entities locationEntity=next(tracker.get_latest_entity_values("location"), None) cuisineEntity=next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity=next(tracker.get_latest_entity_values("user_location"), None) latEntity=next(tracker.get_latest_entity_values("latitude"), None) lonEntity=next(tracker.get_latest_entity_values("longitude"), None) ## if we latitude & longitude entities are found, set it to slot if(latEntity and lonEntity): lat=latEntity lon=lonEntity ## if user wants to search restaurants in his current location if(user_locationEntity or (latEntity and lonEntity) ): ##check if we already have the user location coordinates stoed in slots if(lat==None and lon==None): dispatcher.utter_message(text="Sure, please allow me to access your location 🧐",json_message={"payload":"location"}) return [] else: locationEntities=zomatoApi.getLocationDetailsbyCoordinates(lat,lon) location=locationEntities["title"] city_id=locationEntities["city_id"] entity_id=locationEntities["entity_id"] entity_type=locationEntities["entity_type"] ## store the user provided details to slot SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) ## if user wants to search restaurants by location name if(locationEntity): locationEntities=zomatoApi.getLocationDetailsbyName(locationEntity) if(locationEntities["restaurants_available"]=="no"): dispatcher.utter_message("Sorry I couldn't find any restaurants 😓") return [] entity_id=locationEntities["entity_id"] entity_type=locationEntities["entity_type"] city_id=locationEntities["city_id"] SlotSet("location", locationEntities["title"]) ##get the cuisine id for the cuisine name user provided cuisine_id=zomatoApi.getCuisineId(cuisine,city_id) print("Entities: ",entity_id," ",entity_type," ",cuisine_id," ",location," ",cuisine) print() ## if we didn't find the restaurant for which user has provided the cuisine name if(cuisine_id==None): dispatcher.utter_message("Sorry we couldn't find any restaurants that serves {} cuisine in {}".format(cuisine,location)) return [UserUtteranceReverted()] else: ## search the restaurts by calling zomatoApi api restaurants=zomatoApi.searchRestaurants(entity_id,entity_type, cuisine_id,"") ## check if restaurants found if(len(restaurants)>0): if(tracker.get_latest_input_channel()=="slack"): more_restaurants=[] if(len(restaurants)>5): restData=getResto_Slack(restaurants[:5],show_more_results=True) more_restaurants=restaurants[5:] else: restData=getResto_Slack(restaurants,show_more_results=False) dispatcher.utter_message(text="Here are the few restaurants that matches your preferences 😋",json_message=restData) return [SlotSet("more_restaurants", more_restaurants)] else: if(len(restaurants)>5): dispatcher.utter_message(text="Here are the few restaurants that matches your preferences 😋",json_message={"payload":"cardsCarousel","data":restaurants[:5]}) return [SlotSet("more_restaurants", restaurants[5:])] else: dispatcher.utter_message(text="Here are the few restaurants that matches your preferences 😋",json_message={"payload":"cardsCarousel","data":restaurants}) return [SlotSet("more_restaurants", None)] else: dispatcher.utter_message("Sorry we couldn't find any restaurants that serves {} cuisine in {} 😞".format(cuisine,location)) return [UserUtteranceReverted()]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: return [SlotSet("cust_cmnd", tracker.get_slot('cmnd'))]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # dispatcher.utter_message(text="Hello World!") print(tracker.get_slot('num')) # dispatcher.utter_template('utter_your_num', tracker, number=details[str(tracker.get_slot('NAME')).lower()]) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: balance = CheckBalance(tracker.get_slot("cust_name"),tracker.get_slot("cust_cmnd"),tracker.get_slot("cust_account_number")) loan_max = balance + balance * 0.6 dispatcher.utter_message(text=f'khoản vay tối đa của quý khách là {loan_max}') return[]
def required_slots(tracker: Tracker) -> List[Text]: """A list of required slots that the form has to fill""" if tracker.get_slot("email_affirm") == "no": return ["email_affirm"] else: return ["email_affirm", "email_id"]