def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: facility = tracker.get_slot("facility_type") area = tracker.get_slot("location") print(tracker.sender_id) session = tracker.sender_id print(type(session)) link = 'mongodb://localhost:27017' cluster = MongoClient(link) db = cluster["rasa"] collection = db["rasa"] results = collection.find({"session": session}) user = '******' if (results.count() == 0): message = 'you are not registered, please tell me your name' print(message) # dispatcher.utter_message(text=message) return [FollowupAction("action_form_ask_name")] else: # print(results[0]['name']) user = results[0]['name'] dispatcher.utter_message( text="Hello {}, tell me how can i help you".format(user)) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message(text="• Go to https://pulse.com/ \ • Select ESS based on your organization like ESS \ • Select “Main Menu” and click on “Personal details” option \ • Raise a new request for it.") return [FollowupAction('utter_followup_response')]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message( text= "• Go to https://pulse.com/ \n• Select ESS Click on it and login with AD credentials \n• Select a menu Leave management Under that click on My leave application \n• Provide required information and click on OK" ) return [FollowupAction('utter_followup_response')]
def run(self, dispatcher, tracker, domain): return [ SlotSet("fromloc_city", None), SlotSet("toloc_city", None), SlotSet("depart_time", None), FollowupAction("flight_form") ]
def run(self, dispatcher, tracker, domain): form_name = tracker.active_form.get("name") if form_name: return [FollowupAction(form_name)] else: dispatcher.utter_template("utter_default", tracker) return [Restarted()]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: slotsets = [] dispatcher.utter_message( text="The date is {}".format(strftime("%d %B", localtime()))) slotsets.append(FollowupAction('action_end')) return slotsets
async def submit(self, dispatcher, tracker, domain): dispatcher.utter_message( text="You'll be glad you picked our delicious fruit!") return [ FollowupAction("utter_contact_soon"), ]
def run(self, dispatcher, tracker, domain): try: rq = requests.get("http://pak.hashlob.com/api/getBranches").json() #print(rq) ls = [] count = 0 for i in rq['data']: print(i['name']) if count <= 10: ls.append({ "content_type": "text", "title": i["name"], "payload": i["name"] }) count += 1 res_admin = { "text": "Select your city from the button given below", "quick_replies": ls } dispatcher.utter_custom_json(res_admin) print(res_admin) except: dispatcher.utter_message( "Pakistan Currency Chatbot Didnt recognize the text! Try Again!" ) return [FollowupAction("action_greet")]
def run(self, dispatcher, tracker, domain): try: print("printing duration of transfer") dispatcher.utter_message( "* The duration of transfer for Cash Transaction is 5 Minutes\n" "* The duration of transfer for Bank Transaction is depend on your bank" ) res_admin = { "text": "Do you want to ask more?, If yes then click on I want to ask more button given below? ", "quick_replies": [{ "content_type": "text", "title": "I want to ask more", "payload": "I want to ask more" }, { "content_type": "text", "title": "No, thankyou", "payload": "No, thankyou" }] } dispatcher.utter_custom_json(res_admin) print(res_admin) except: dispatcher.utter_message( "Pakistan Currency Chatbot Didnt recognize the text! Try Again!" ) return [FollowupAction("action_greet")]
def run( self, dispatcher, tracker: Tracker, domain: Dict[Text, Any] ) -> List[Dict[Text, Any]]: seat = tracker.get_slot('seat_number') if tracker.get_slot("air_condition") is None: ac_status = tracker.get_slot('non_aircondition') else: ac_status = tracker.get_slot('air_condition') time = tracker.get_slot('time') _, time = tracker.get_slot('time').split('T') hour = int(time[:2]) if 19 <= hour < 22: time = time.split('.')[0] dispatcher.utter_message(template="utter_book_info", seats=seat, ac_status=ac_status, booking_time = time ) return [] else: dispatcher.utter_message(text="We are not open at that time. We are only open from 7pm to 10pm \nWhen would you like to book a reservation? (We are only open from 7pm to 10pm)") UserUtteranceReverted() FollowupAction('action_reservation') return []
def run(self, dispatcher, tracker, domain): try: print( "If you have any complaint you can contact us at: [email protected]" ) dispatcher.utter_message( "If you have any complaint you can contact us at: [email protected]" ) res_admin = { "text": "Do you want to ask more?, If yes then click on I want to ask more button given below? ", "quick_replies": [{ "content_type": "text", "title": "I want to ask more", "payload": "I want to ask more" }, { "content_type": "text", "title": "No, thankyou", "payload": "No, thankyou" }] } dispatcher.utter_custom_json(res_admin) print(res_admin) except: dispatcher.utter_message( "Pakistan Currency Chatbot Didnt recognize the text! Try Again!" ) return [FollowupAction("action_greet")]
def run(self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]): book_genre_type = tracker.get_slot('book_slot_value') if book_genre_type != 'Others': if book_genre_type == "Avelene's Choice": book_details = fetch_books_avelene_choice() dispatcher.utter_message( 'These are the best books I have found:\n{}'.format( book_details)) else: book_details = fetch_books_categorywise(book_genre_type) dispatcher.utter_message( 'These are the best books I have found:\n{}'.format( book_details)) return [FollowupAction('action_listen')] elif book_genre_type == "Others": return [FollowupAction('action_listen')]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: logger.debug("---- [ActionSearchExercise] ----") # Get slot value muscle = tracker.get_slot('muscle') facility = tracker.get_slot('facility') logger.debug("m:{}, f:{}".format(muscle, facility)) response = """ You want to find the {} exercise with {}.""".format( muscle, facility) try: response = """FYI {}""".format( random.choice(searchExercise(muscle, facility))) except: response = "sorry, we cannot find the related exercise for you.\n" response = "But we recommend you to do this\n" rnd = random.choice(exerciseList) response = response + "I recommend to do some {} exercise with {}!!\nFYI {}".format( rnd['Body'], rnd['equipment'], rnd['resource']) dispatcher.utter_message(response) return [AllSlotsReset(), FollowupAction('action_restart')]
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: next_action = "move" returned = [] if tracker.get_slot("object") is not None: next_action += " to " + str(tracker.get_slot("object")) returned.append(FollowupAction("action_moveto")) elif tracker.get_slot("direction"): next_action += " " + str(tracker.get_slot("direction")) returned.append(FollowupAction("action_move")) returned.append(SlotSet("next_action", next_action)) return returned
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any] ) -> List[Dict[Text, Any]]: """Get the index from target_cart_item, remove the item at that index. Args: dispatcher: Rasa CollectingDispatcher tracker: Rasa Tracker domain: Rasa domain Return: List[Dict[Text, Any]]: updated cart """ user_cart = cart.get_user_cart(tracker.sender_id) to_remove = user_cart.get_matching_cart_item(tracker.get_slot("target_cart_item")) if to_remove: removed = user_cart.remove_item(to_remove) if removed: dispatcher.utter_message(template="utter_removed") else: dispatcher.utter_message(template="utter_cart_item_not_found") return [FollowupAction("action_clear_slots"), SlotSet("num_cart_items", len(user_cart.cart_items)), SlotSet("cart_total", user_cart.sum_cost())]
def run(self, dispatcher, tracker, domain): try: dispatcher.utter_message( "This is the following requirments for sender: ") dispatcher.utter_message( 'Original NIC With Photocopy \n Receiver name as per ID\n' 'Contact Number\n Address)\n' 'Receiver Bank Account Details (If receiver has bank account)\n' ) print("sender requirement printed") res_admin = { "text": "Do you want to ask more currency rates, If yes then click on currency rates button given below? ", "quick_replies": [{ "content_type": "text", "title": "Currency Rates", "payload": "Currency Rates" }, { "content_type": "text", "title": "No, thankyou", "payload": "No, thankyou" }] } dispatcher.utter_custom_json(res_admin) print(res_admin) except: dispatcher.utter_message( "Pakistan Currency Chatbot Didnt recognize the text! Try Again!" ) return [FollowupAction("action_greet")]
def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: """Once required slots are filled, print buttons for found facilities""" name = tracker.get_slot('name') email = tracker.get_slot('email') ## connecting to mongo db link = 'mongodb://localhost:27017' cluster = MongoClient(link) db = cluster["rasa"] collection = db["rasa"] print(tracker.sender_id, name, email) ## inserting to Mongo db post = {"session": tracker.sender_id, "name": name, "email": email} collection.insert_one(post) ## inserting to GM db with api call session = tracker.sender_id phoneNumRegex = re.compile(r'[0-9]*') mo = phoneNumRegex.search(session) phone = mo.group() print(mo.group()) response = apis.register(name, phone) # dispatcher.utter_message(text="Please confirm following information \nname: {}, \nemail: {}\n".format(name,email)) return [FollowupAction("actions_find_in_mongo")]
def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: content_name = tracker.latest_message["text"].split(" ", 1)[1] review_content_name = self.resolve_object_name(content_name) # print(content_name) if review_content_name: dispatcher.utter_message( text=f"Initializing {review_content_name} quiz! 😊") else: dispatcher.utter_message( text=f"Sorry, I could not find {content_name} quiz 😞") return [] return [ SlotSet("content_name", review_content_name), SlotSet("question_count", 0), SlotSet("points", 0), FollowupAction("action_get_question"), ]
def run(self, dispatcher, tracker, domain): global output_10 # config = {} loc = tracker.get_slot('location') cuisine = tracker.get_slot('cuisine') budget = tracker.get_slot('budget') if not loc or not cuisine or not budget: dispatcher.utter_message("Some unknown problem. Please try again") return [FollowupAction("utter_ask_location")] cuisine = tracker.get_slot('cuisine').lower() budget = tracker.get_slot('budget').strip() location_detail = xxx.get_location(loc, 1) d1 = json.loads(location_detail) lat = d1["location_suggestions"][0]["latitude"] lon = d1["location_suggestions"][0]["longitude"] cuisines_dict = {'chinese': 25, 'mexican': 73, 'italian': 55, 'american': 1, 'north indian': 50, 'south indian': 85} response_orig = "" response_orig = self.find_top_rated_restaurants(lat, lon, str(cuisines_dict.get(cuisine)), budget, xxx, find_restaurant_number=10) response_10 = "" if not response_orig or len(response_orig) == 0: response = "no results found" else: response = "\n".join(response_orig) response_10 = "\n".join(output_10) dispatcher.utter_message("-----" + response) #return [SlotSet('email_content', response_10)] return []
def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: content_name = tracker.get_slot("content_name") count = int(tracker.get_slot("question_count")) answer = db[db["quiz_title"] == content_name].iloc[count]["correct_answers"] answer = ast.literal_eval(answer)[0] user_answer = tracker.get_slot("answer") points = int(tracker.get_slot("points")) if fuzz.ratio(answer, user_answer) > 90: dispatcher.utter_message(text="Great!") points += 1 else: dispatcher.utter_message(text="Ummm...") count += 1 # print(count, answer, user_answer, sep="\n") return [ SlotSet("question_count", count), SlotSet("points", points), FollowupAction("action_get_question"), ]
def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[EventType]: breakdown_counter = 0 action_counter = 0 for events in tracker.events: if (events["event"] == "action" and events["name"] == "action_repair"): breakdown_counter += 1 if (events["event"] == "action" and events["name"] != "action_listen"): action_counter += 1 logger.debug(f"You already had {breakdown_counter} \ breakdowns in this conversation!") if breakdown_counter <= 5: return [FollowupAction("action_repair_options")] elif breakdown_counter > 5: dispatcher.utter_message(template="utter_capabilities_repair") 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""" if (tracker.get_slot('oneway') == True and tracker.get_slot('confirm_onewaytrip') == True): dispatcher.utter_message(template='utter_submit') return [] elif (tracker.get_slot('oneway') == False and tracker.get_slot('confirm_returntrip') == True): dispatcher.utter_message(template='utter_submit') return [] else: dispatcher.utter_message(text="Let's start over.") return [ SlotSet("from", None), SlotSet("to", None), SlotSet("date", None), SlotSet("meal", None), SlotSet("oneway", None), SlotSet("return", None), SlotSet("confirm_onewaytrip", None), SlotSet("confirm_returntrip", None), FollowupAction("booking_form") ]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: """ Execute this action when action triggered by utterance defined in story. Run this action to get bill detail of twd as Foreign Dollar. """ if tracker.get_slot("unbill_details"): unbill_details_frd = [ unbill for unbill in tracker.get_slot("unbill_details") if unbill["currency_type"] == "frd" ] dispatcher.utter_message(json_message=unbill_details_frd) if tracker.get_slot("recent_bill_id"): # call bill detail api to get bill detail that currency type is frd # respond data format can follow ActionBillDetail Class above bill_respond = requests.get(host + API_RASA_BILL, params={ "currency_type": "frd", "bill_id": tracker.get_slot("recent_bill_id") }) dispatcher.utter_message( json_message=bill_respond.json()["result"]) return [FollowupAction("utter_unbill_detail")]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: import sqlite3 import json state = tracker.current_state() sender_id = state["sender_id"] #"42613706c7444af4ac33a316d0dcc2a8" con = sqlite3.connect("patient_profile.db") c = con.cursor() sessions = list( c.execute( f'SELECT * FROM patient_profile WHERE patient_id="{sender_id}"' )) #returns = [] symptoms = None drugs = None if sessions: if sessions[-1][-2]: symptoms = json.loads(sessions[-1][-2]) if sessions[-1][-1]: drugs = json.loads(sessions[-1][-1]) con.close() results = [ SlotSet("old_symptoms", symptoms), SlotSet("old_drugs", drugs) ] if symptoms: results.append(FollowupAction(name='ask_symptom_develop')) return results
def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: gmaps = GMapsService() slot_value = tracker.get_slot("location") try: lat, long = list(map(float, slot_value.split(","))) except ValueError: lat, long = gmaps.get_geocode_result(slot_value) if lat is None or long is None: dispatcher.utter_message(response="utter_location_not_found") return [ SlotSet("location", None), FollowupAction(name="location_form") ] else: results = gmaps.get_places_nearby({ "latitude": lat, "longitude": long }) dispatcher.utter_message(json_message={"locations": results}) return [SlotSet("location", None)]
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict) -> List[EventType]: """Executes the custom action""" account_type = tracker.get_slot("account_type") if account_type == "credit": # show credit card balance credit_card_balance = tracker.get_slot("credit_card_balance") credit_card = tracker.get_slot("credit_card") if credit_card and credit_card.lower() in credit_card_balance: current_balance = credit_card_balance[ credit_card.lower()]["current balance"] dispatcher.utter_message( template="utter_credit_card_balance", **{ "credit_card": credit_card.title(), "amount-of-money": f"{current_balance:.2f}", }, ) else: for credit_card in credit_card_balance.keys(): current_balance = credit_card_balance[credit_card][ "current balance"] dispatcher.utter_message( template="utter_credit_card_balance", **{ "credit_card": credit_card.title(), "amount-of-money": f"{current_balance:.2f}", }, ) else: # show bank account balance account_balance = float(tracker.get_slot("account_balance")) amount = tracker.get_slot("amount_transferred") if amount: amount = float(tracker.get_slot("amount_transferred")) init_account_balance = account_balance + amount dispatcher.utter_message( template="utter_changed_account_balance", init_account_balance=f"{init_account_balance:.2f}", account_balance=f"{account_balance:.2f}", ) else: dispatcher.utter_message( template="utter_account_balance", init_account_balance=f"{account_balance:.2f}", ) events = [] active_form_name = tracker.active_form.get("name") if active_form_name: # keep the tracker clean for the predictions with form switch stories events.append(UserUtteranceReverted()) # trigger utter_ask_{form}_continue_form, by making it the requested_slot events.append(SlotSet("continue_form", None)) # avoid that bot goes in listen mode after UserUtteranceReverted events.append(FollowupAction(active_form_name)) return events
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message( text= "ESS is Employee self service.It keeps track of employees attendance and leave management" ) return [FollowupAction('utter_followup_response')]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any] ) -> List[Dict[Text, Any]]: """Check that all 'options' are valid for the requested menu item. Args: dispatcher: Rasa collecting dispatcher tracker: Rasa tracker domain: Rasa domain Return: List[Text]: A list of matching values from the menu or an empty list """ user_cart = cart.get_user_cart(tracker.sender_id) options = tracker.get_slot('options') if options == []: return [SlotSet('options', options)] else: # stop-gap solution for error when adding a single add-on ['c','r','e','a','m'] if len(options[0]) == 1: options = ["".join(options)] valid, invalid = user_cart.validate_options(tracker.get_slot('item'), tracker.get_slot('options')) if invalid: dispatcher.utter_message(f"I couldn't find a matching option for {cart.list_to_string(invalid, join='or')}") return [SlotSet('options', valid), FollowupAction('action_listen')] return [SlotSet('options', valid)]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message(text="• Go to https://pulse.company.com/ \ • Select ESS based on your organization like ESS \ • Select “Main Menu” and click on “Form 16” option" ) return [FollowupAction('utter_followup_response')]
def run(self, dispatcher, tracker, domain): print("Check appointment") most_recent_state = tracker.current_state() sender_id = most_recent_state['sender_id'] with open('appointment.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: if row[0] == sender_id: customer_name = row[1] phone_number = row[2] print(row) print("Found record") dispatcher.utter_message( text=f"Em đã tiếp nhận thông tin liên lạc của anh/chị: {customer_name} - {phone_number}. " f"Bọn em sẽ cố gắng liên lạc lại trong thời gian sớm nhất.") dispatcher.utter_message(buttons=[{ 'payload': '/lai_suat', 'title': 'Lãi suất ngân hàng' }, { 'payload': '/thi_truong', 'title': 'Tình hình thị trường' }, { 'payload': '/goodbye', 'title': 'Không quan tâm' }], text="Trong thời gian chờ đợi, anh/chị có thể tham khảo các mục sau ạ.") return [] dispatcher.utter_message( text=f"Qua kiểm tra, bên em vẫn chưa tiếp nhận thông tin liên lạc của anh/chị. Vì vậy, anh/chị có thể vui " f"lòng cung cấp những thông tin sau ạ") return [FollowupAction(name='custom_contact_form')]