def validate(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                 domain: Dict[Text, Any]) -> List[Dict]:

        slot_values = self.extract_other_slots(dispatcher, tracker, domain)
        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)

        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))

        else:
            temp = tracker.get_latest_entity_values('PER')
            aux = None
            for i in temp:
                if i.lower() != "hola":
                    aux = i
            aux2 = next(tracker.get_latest_entity_values('persona'), None)
            loc = next(tracker.get_latest_entity_values('LOC'), None)
            misc = next(tracker.get_latest_entity_values('MISC'), None)
            if aux is None and aux2 is not None:
                return [SlotSet('persona', aux2.title())]
            elif aux is not None and aux is not "Hola":
                return [SlotSet('persona', aux.title())]
            elif loc is not None:
                return [SlotSet('persona', loc)]
            elif misc is not None:
                return [SlotSet('persona', misc)]
            else:
                dispatcher.utter_message("Dime cómo te llamas")
                return []

        return [SlotSet(slot, value) for slot, value in slot_values.items()]
Exemple #2
0
 def _utter_event_overview(self, dispatcher: CollectingDispatcher) -> None:
     events = self._get_events()
     event_items = ["- {} in {}".format(e.name, e.location) for e in events]
     locations = "\n".join(event_items)
     dispatcher.utter_message("Here are the next Rasa events:\n"
                              "" + locations +
                              "\nWe hope to see you at them!")
Exemple #3
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        user_ignore_count = 2
        count = 0
        tracker_list = []

        while user_ignore_count > 0:
            event = tracker.events[count].get('event')
            if event == 'user':
                user_ignore_count = user_ignore_count - 1
            if event == 'bot':
                tracker_list.append(tracker.events[count])
            count = count - 1

        i = len(tracker_list) - 1
        while i >= 0:
            data = tracker_list[i].get('data')
            if data:
                if "buttons" in data:
                    dispatcher.utter_message(text=tracker_list[i].get('text'),
                                             buttons=data["buttons"])
                else:
                    dispatcher.utter_message(text=tracker_list[i].get('text'))
            i -= 1

        return []
Exemple #4
0
    def submit(self,
               dispatcher: CollectingDispatcher,
               tracker: Tracker,
               domain: Dict[Text, Any]) -> List[Dict]:
        location_name = tracker.get_slot('location')
        cuisine = tracker.get_slot('cuisine')
        budget = tracker.get_slot('budget')

        top_5_restaurants = []
        if self.lat is not None and self.lon is not None and self.cuisine_id is not None and self.budget_type is not None:
            top_5_restaurants = zomato_utils.get_top_restaurants_by_user_ratings(self.lat, self.lon, self.cuisine_id, self.budget_type)

        response = "No restaurants found in {} serving {} cuisine in {} budget".format(location_name, cuisine, budget)
        response_array = []

        if len(top_5_restaurants) > 0:
            index = 1
            response = "Following are top 5 restaurants matching your preference in order of average user rating on zomato:\n\n"
            for restaurant in top_5_restaurants:
                response = response + "{}. {} in {} has been rated {}\n".format(index, restaurant['name'], restaurant['address'], restaurant['user_rating'])
                index += 1
            response_array = [SlotSet("lat", self.lat), SlotSet("lon", self.lon), SlotSet("cuisine_id", self.cuisine_id), SlotSet("budget_type", self.budget_type)]

        dispatcher.utter_message(response)
        return response_array
Exemple #5
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        #save in the slot the information that we got
        number_of_people = int(tracker.get_slot("num_persone"))
        orario = tracker.get_slot("orario")
        data = tracker.get_slot("data")
        prenotation_time = data + "T" + orario
        global number_of_seats
        service = authentication()
        if ":" == prenotation_time[-3:-2]:
            prenotation_time = prenotation_time[:-3] + prenotation_time[
                -2:]  # formattazione orario per chiamate successive
        prenotation_time_start = datetime.strptime(prenotation_time,
                                                   '%Y-%m-%dT%H:%M:%S.%f%z')
        prenotation_time_end = prenotation_time_start + timedelta(
            hours=2)  # si assume che una prenotazione duri 2 ore

        events_result = service.events().list(
            calendarId='*****@*****.**',
            timeMin=prenotation_time_start.isoformat(),
            timeMax=prenotation_time_end.isoformat()).execute()
        events = events_result.get('items', [])
        if check_available_seats(
                events, number_of_people
        ):  # si controlla che ci siano posti disponibili
            dispatcher.utter_template("utter_confirmation", tracker)
            return [SlotSet('available_seats', True)]
        else:
            dispatcher.utter_message("Mi dispiace ma siamo al completo.")
            return [SlotSet('available_seats', False)]
Exemple #6
0
 def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     intent_name = tracker.latest_message['intent'].get('name')
     entity_name = tracker.latest_message['entities']
     print("value of intent " + str(intent_name))
     print("value of entity " + str(entity_name))
     if intent_name == "get_started":
         dispatcher.utter_template("utter_payload", tracker)
         return [UserUtteranceReverted()]
     else:
         message = "कृपया आप सही जानकारी प्रदान करें"
         dispatcher.utter_message(message)
         return [UserUtteranceReverted()]
    def validate_password(self,
                            value: Text,
                            dispatcher: CollectingDispatcher,
                            tracker: Tracker,
                            domain: Dict[Text, Any]) -> Optional[Text]:
        """Validate password value."""

        if value is not None:
            return value
        else:
            dispatcher.utter_message("Erro")
            # validation failed, set slot to None
            return None
Exemple #8
0
 def submit(
     self,
     dispatcher: CollectingDispatcher,
     tracker: Tracker,
     domain: Dict[Text, Any],
 ) -> List[Dict]:
     dispatcher.utter_message(
         "❤️❤️❤️Thank you so much for showing your intrest in traveling with us"
     )
     insert_data(tracker.get_slot("travel_date"),
                 tracker.get_slot("travel_period"),
                 tracker.get_slot("trip_type"), tracker.get_slot("adults"),
                 tracker.get_slot("child"), tracker.get_slot("budget"),
                 tracker.get_slot("email"), tracker.get_slot("phno"))
     return []
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List:

        location = tracker.get_slot('location')
        facility_type = tracker.get_slot('facility_type')

        results = _find_facilities(location, facility_type)
        button_name = _resolve_name(FACILITY_TYPES, facility_type)
        if len(results) == 0:
            dispatcher.utter_message(
                "Sorry, we could not find a {} in {}.".format(
                    button_name, location))
            return []

        buttons = []
        print("found {} facilities".format(len(results)))
        for r in results:
            if facility_type == FACILITY_TYPES["hospital"]["resource"]:
                facility_id = r.get("provider_id")
                name = r["hospital_name"]
            elif facility_type == FACILITY_TYPES["nursing_home"]["resource"]:
                facility_id = r["federal_provider_number"]
                name = r["provider_name"]
            elif facility_type == FACILITY_TYPES["doctor"]["resource"]:
                facility_id = r["ind_enrl_id"]
                name = "{} {}".format(r["frst_nm"], r["lst_nm"])
            else:
                facility_id = r["provider_number"]
                name = r["provider_name"]

            payload = "/inform{\"facility_id\":\"" + facility_id + "\"}"
            buttons.append({
                "title": "{}".format(name.title()),
                "payload": payload
            })

        # limit number of buttons to 3 here for clear presentation purpose
        if "near" in location:
            location = "you"

        dispatcher.utter_button_message(
            "Here is a list of {} {}s near {}".format(len(buttons[:3]),
                                                      button_name, location),
            buttons[:3],
            button_type="custom")
        # todo: note: button options are not working BUG in rasa_core

        return []
Exemple #10
0
    def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker,
               domain: Dict[Text, Any]) -> List[Dict]:
        """Once required slots are filled, print buttons for found facilities"""

        location = tracker.get_slot('location')
        facility_type = tracker.get_slot('facility_type')

        results = _find_facilities(location, facility_type)
        button_name = _resolve_name(FACILITY_TYPES, facility_type)
        if len(results) == 0:
            dispatcher.utter_message(
                "Sorry, we could not find a {} in {}.".format(
                    button_name, location.title()))
            return []

        buttons = []
        # limit number of results to 3 for clear presentation purposes
        for r in results[:3]:
            if facility_type == FACILITY_TYPES["hospital"]["resource"]:
                facility_id = r.get("provider_id")
                name = r["hospital_name"]
            elif facility_type == FACILITY_TYPES["nursing_home"]["resource"]:
                facility_id = r["federal_provider_number"]
                name = r["provider_name"]
            else:
                facility_id = r["provider_number"]
                name = r["provider_name"]

            payload = "/inform{\"facility_id\":\"" + facility_id + "\"}"
            buttons.append({
                "title": "{}".format(name.title()),
                "payload": payload
            })

        if len(buttons) == 1:
            message = "Here is a {} near you:".format(button_name)
        else:
            if button_name == "home health agency":
                button_name = "home health agencie"
            message = "Here are {} {}s near you:".format(
                len(buttons), button_name)

        # TODO: update rasa core version for configurable `button_type`
        dispatcher.utter_button_message(message, buttons)

        return []
Exemple #11
0
    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List["Event"]:

        last_utter = get_last_utter_action(tracker, dispatcher)
        if "action_default_fallback" == last_utter:
            dispatcher.utter_message(
                "handoff to human: implementazione notifica"
            )  # TODO implement handoff
            return [ConversationPaused()]

        # first time
        else:
            dispatcher.utter_template("utter_default", tracker)
            return [UserUtteranceReverted()]
Exemple #12
0
    def _utter_next_event(self, tracker: Tracker,
                          dispatcher: CollectingDispatcher) -> None:
        location = next(tracker.get_latest_entity_values('location'), None)
        events = self._get_events()

        if location:
            events_for_location = [e for e in events if e.location == location]
            if not events_for_location and events:
                next_event = events[0]
                dispatcher.utter_message(
                    "Sorry, there are currently no events "
                    "at your location. However, the next "
                    "event is the {} in {} on {}."
                    "".format(next_event.name_as_link(), next_event.location,
                              next_event.formatted_date()))
            elif events_for_location:
                next_event = events_for_location[0]
                dispatcher.utter_message(
                    "The next event in {} is the {} on {}."
                    " Hope to see you there!"
                    "".format(location, next_event.name_as_link(),
                              next_event.formatted_date()))
        elif events:
            next_event = events[0]
            dispatcher.utter_message("The next event is the {} in {} on {}. "
                                     "Hope to see you there!"
                                     "".format(next_event.name_as_link(),
                                               next_event.location,
                                               next_event.formatted_date()))
Exemple #13
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        # save in the slot the information that we got

        intent = tracker.latest_message['intent'].get('name')
        if (intent == "afferma"):
            number_of_people = int(tracker.get_slot("num_persone"))
            orario = tracker.get_slot("orario")
            data = tracker.get_slot("data")
            prenotation_time = data + "T" + orario
            global number_of_seats
            service = authentication()
            if ":" == prenotation_time[-3:-2]:
                prenotation_time = prenotation_time[:-3] + prenotation_time[-2:]
            prenotation_time_start = datetime.strptime(
                prenotation_time, '%Y-%m-%dT%H:%M:%S.%f%z')
            prenotation_time_end = prenotation_time_start + timedelta(
                hours=2)  # we assume that a reservation last 2 hours

            events_result = service.events().list(
                calendarId='*****@*****.**',
                timeMin=prenotation_time_start.isoformat(),
                timeMax=prenotation_time_end.isoformat()).execute()
            events = events_result.get('items', [])
            if check_available_seats(events, number_of_people):  # double check
                insert_event(service, prenotation_time_start,
                             prenotation_time_end, number_of_people,
                             dispatcher)
                dispatcher.utter_template("utter_confirmed", tracker)
                return [SlotSet('conferma_prenotazione', True)]

            else:
                dispatcher.utter_message("Mi dispiace ma siamo pieni.")
                return [
                    SlotSet('conferma_prenotazione', False),
                    SlotSet('available_seats', False)
                ]
        elif intent == "nega":
            dispatcher.utter_template('utter_not_confirmed', tracker)
            return [SlotSet('conferma_prenotazione', False)]
Exemple #14
0
    def validate(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                 domain: Dict[Text, Any]) -> List[Dict]:
        """Validate extracted requested slot
            else reject the execution of the form action
        """
        # extract other slots that were not requested
        # but set by corresponding entity
        slot_values = self.extract_other_slots(dispatcher, tracker, domain)

        # extract requested slot
        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)
        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))
            if not slot_values:
                # reject form action execution
                # if some slot was requested but nothing was extracted
                # it will allow other policies to predict another action
                raise ActionExecutionRejection(
                    self.name(), "Failed to validate slot {0} "
                    "with action {1}"
                    "".format(slot_to_fill, self.name()))

        # we'll check when validation failed in order
        # to add appropriate utterances
        for slot, value in slot_values.items():
            if slot == 'account':
                if value.lower() not in self.account_db():
                    dispatcher.utter_template('utter_wrong_account', tracker)
                    dispatcher.utter_message(
                        'Here are few Types which you can ' +
                        ", ".join(self.account_db()))
                    # validation failed, set slot to None
                    slot_values[slot] = None

            elif slot == 'accounttype':
                if value.lower() not in self.accounttype():
                    dispatcher.utter_template('utter_wrong_account_type',
                                              tracker)
                    dispatcher.utter_message(
                        'Here are few Types which you can ' +
                        ", ".join(self.accounttype()))
                    # validation failed, set slot to None
                    slot_values[slot] = None

            elif slot == 'producttype':
                if value.lower() not in self.prodtype():
                    dispatcher.utter_template('utter_wrong_product_type',
                                              tracker)
                    dispatcher.utter_message('you can enter one of these ' +
                                             ", ".join(self.prodtype()))
                    # validation failed, set slot to None
                    slot_values[slot] = None

            elif slot == 'adjustmenttype':
                if value.lower() not in self.adjtype():
                    dispatcher.utter_template('utter_wrong_adjustment_type',
                                              tracker)
                    dispatcher.utter_message('below are the few options ' +
                                             ", ".join(self.adjtype()))
                    # validation failed, set slot to None
                    slot_values[slot] = None

        # validation succeed, set the slots values to the extracted values
        return [SlotSet(slot, value) for slot, value in slot_values.items()]
Exemple #15
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        message = "I'm sorry. Please enter expected details."
        dispatcher.utter_message(message)

        return [UserUtteranceReverted()]