Example #1
0
    def run(self, dispatcher: LineDispatcher, tracker, domain):

        # medicine_list = tracker.get_slot("doctor_records")

        message = get_flex_doctor_records()

        dispatcher.line_response(message)

        return []
Example #2
0
    def run(self, dispatcher: LineDispatcher, tracker, domain):

        medicine_list = tracker.get_slot("medicine_list")

        message = get_flex_medicine_list(medicine_list)

        dispatcher.line_response(message)

        return []
Example #3
0
    def run(self, dispatcher: LineDispatcher, tracker, domain):

        dispatcher.line_template('line_cancel_success', tracker)

        return [
            Form(None),
            SlotSet("new_medicine_name", None),
            SlotSet("new_medicine_time", None),
            SlotSet("new_medicine_meal", None),
            SlotSet(REQUESTED_SLOT, None)
        ]
Example #4
0
    def handle_reminder(self, reminder_event: LineReminderScheduled,
                        dispatcher: LineDispatcher) -> None:
        """Handle a reminder that is triggered asynchronously."""

        tracker = self._get_tracker(dispatcher.sender_id)

        if not tracker:
            logger.warning("Failed to retrieve or create tracker for sender "
                           "'{}'.".format(dispatcher.sender_id))
            return None

        if (reminder_event.kill_on_user_message
                and self._has_message_after_reminder(tracker, reminder_event)
                or not self._is_reminder_still_valid(tracker, reminder_event)):
            logger.debug("Canceled reminder because it is outdated. "
                         "(event: {} id: {})".format(
                             reminder_event.action_name, reminder_event.name))
        else:
            # necessary for proper featurization, otherwise the previous
            # unrelated message would influence featurization
            tracker.update(UserUttered.empty())
            # clear replied messages
            dispatcher.output_channel.clear_messages()
            dispatcher.reminder_data = reminder_event.data
            action = self._get_action(reminder_event.action_name)
            should_continue = self._run_action(action, tracker, dispatcher)
            if should_continue:
                user_msg = UserMessage(None, dispatcher.output_channel,
                                       dispatcher.sender_id)
                self._predict_and_execute_next_action(user_msg, tracker)
            # send push to line api
            dispatcher.output_channel.send_push()
            # save tracker state to continue conversation from this state
            self._save_tracker(tracker)
Example #5
0
    def _predict_and_execute_next_action(self, message, tracker):
        # this will actually send the response to the user

        dispatcher = LineDispatcher(message.sender_id, message.output_channel,
                                    self.nlg)
        # keep taking actions decided by the policy until it chooses to 'listen'
        should_predict_another_action = True
        num_predicted_actions = 0

        self._log_slots(tracker)

        # action loop. predicts actions until we hit action listen
        while (should_predict_another_action
               and self._should_handle_message(tracker)
               and num_predicted_actions < self.max_number_of_predictions):
            # this actually just calls the policy's method by the same name

            action, policy, confidence = self.predict_next_action(tracker)

            should_predict_another_action = self._run_action(
                action, tracker, dispatcher, policy, confidence)
            num_predicted_actions += 1

        if (num_predicted_actions == self.max_number_of_predictions
                and should_predict_another_action):
            # circuit breaker was tripped
            logger.warning("Circuit breaker tripped. Stopped predicting "
                           "more actions for sender '{}'".format(
                               tracker.sender_id))
            if self.on_circuit_break:
                # call a registered callback
                self.on_circuit_break(tracker, dispatcher)
Example #6
0
    def run(self, dispatcher: LineDispatcher, tracker, domain):
        medicine_list = tracker.get_slot("medicine_list")
        medicine_reminders = tracker.get_slot("medicine_reminders")
        time_tuple = dispatcher.reminder_data.get("time_tuple")

        if medicine_list and medicine_reminders and time_tuple:
            medicine_to_remind = []

            # Time and Meal text to send push
            time_text = medicine_reminders[time_tuple]["time_text"]
            if time_tuple[1]:
                meal_text = " " + medicine_reminders[time_tuple]["meal_text"]
            else:
                meal_text = ""

            for medicine in medicine_list:
                times = medicine["time"].split("_")
                meal = medicine["meal"]
                for time in times:
                    if (time, meal) == time_tuple:
                        medicine_to_remind.append(medicine["name"])

            number_to_remind = len(medicine_to_remind)
            if number_to_remind > 0:
                if number_to_remind == 1:  # For one medicine, send as one line text
                    text = "สวัสดีค่ะ คุณทาน{} ตอน{}{} หรือยังคะ".format(
                        medicine_to_remind[0], time_text, meal_text)
                else:  # For multiple medicines, send them as a list
                    text = "สวัสดีค่ะ คุณทาน\n"
                    for medicine in medicine_to_remind:
                        text += "❥ " + medicine + "\n"
                    text += "ตอน{}{} หรือยังคะ".format(
                        time_text, meal_text)
                dispatcher.line_template(
                    "line_medicine_reminder_push", tracker, text=text)
            medicine_reminders[time_tuple]["job_id"] = None

            return [SlotSet("medicine_reminders", medicine_reminders), FollowupAction("custom_medicine_reminder_update")]

        else:
            logger.warning("medicine_list:{}, medicine_reminders:{}, time_tuple:{}".format(
                medicine_list, medicine_reminders, time_tuple
            ))

        return []
Example #7
0
    def run(self, dispatcher: LineDispatcher, tracker, domain):

        medicine_list = tracker.get_slot("medicine_list")
        if medicine_list:
            first_medicine = medicine_list[0]
            time = first_medicine["time"].split("_")[0]
            meal = first_medicine["meal"]
        else:
            return []
        schedule_time = datetime.utcnow() + timedelta(seconds=10)
        reminder = LineReminderScheduled("custom_medicine_reminder_push",
                                         schedule_time,
                                         data={
                                             "time_tuple": (time, meal)
                                         })

        dispatcher.line_template("line_test_reminder_setup", tracker)

        return [reminder]
Example #8
0
    def submit(self, dispatcher: LineDispatcher, tracker, domain):
        """Define what the form has to do
            after all required slots are filled"""

        medicine_list = tracker.get_slot("medicine_list")

        if medicine_list is None:
            new_medicine_list = []
        else:
            new_medicine_list = medicine_list.copy()

        new_medicine_name = tracker.get_slot("new_medicine_name")
        new_medicine_time = tracker.get_slot("new_medicine_time")
        new_medicine_meal = tracker.get_slot("new_medicine_meal")

        new_medicine_list.append({
            "name": new_medicine_name,
            "time": new_medicine_time,
            "meal": new_medicine_meal,
            "uuid": uuid.uuid4()
        })

        medicine_time_text = DEFAULT_MEDICINE_TEXT.get(
            new_medicine_time, new_medicine_time)
        medicine_meal_text = DEFAULT_MEDICINE_TEXT.get(new_medicine_meal, None)
        medicine_info_text = medicine_time_text
        medicine_info_text += " " + medicine_meal_text if medicine_meal_text else ""

        # utter submit template
        dispatcher.line_template('line_add_new_medicine_success', tracker,
                                 medicine_info_text=medicine_info_text
                                 )

        events = [
            SlotSet("medicine_list", new_medicine_list),
            SlotSet("new_medicine_name", None),
            SlotSet("new_medicine_time", None),
            SlotSet("new_medicine_meal", None),
            FollowupAction("custom_medicine_reminder_update")
        ]

        return events
Example #9
0
    def run(self, dispatcher: LineDispatcher, tracker, domain):

        old_medicine_list = tracker.get_slot("medicine_list")
        new_medicine_list = []

        remove_medicine_uuid = next(tracker.get_latest_entity_values(
            "remove_medicine_uuid"), None)

        removed_medicine = None
        for medicine_dict in old_medicine_list:
            if medicine_dict.get("uuid") == uuid.UUID(remove_medicine_uuid):
                removed_medicine = medicine_dict
            else:
                new_medicine_list.append(medicine_dict)

        if removed_medicine is not None:
            dispatcher.line_template(
                'line_remove_medicine_success', tracker, medicine_name=removed_medicine["name"])
        else:
            dispatcher.line_template('line_remove_medicine_already', tracker)

        return [SlotSet("medicine_list", new_medicine_list), FollowupAction("custom_medicine_reminder_update")]