Beispiel #1
0
    async def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                     domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        try:
            # get medicine, reminder time and interval from corresponding slots
            medicine = tracker.get_slot("medicine_name")
            full_time = tracker.get_slot("time")[:19]
            interval = tracker.get_slot("interval")

            resp = "Medbot will remind you daily for your medicine!!"

            # strip the time in required format
            date_time = datetime.datetime.strptime(full_time,
                                                   "%Y-%m-%dT%H:%M:%S")
            # datetime = str(date_time)
            print(medicine, full_time, interval)

            # Schedule the reminder
            reminder = ReminderScheduled(
                "EXTERNAL_reminder",
                trigger_date_time=date_time,
                entities={
                    "medicine": medicine,
                    "time": str(date_time),
                    "interval": interval
                },
                kill_on_user_message=False,
            )
            dispatcher.utter_message(text=resp)
            return [reminder, AllSlotsReset()]
        except:
            dispatcher.utter_message(
                text="Some error unable to set reminder..")

            return []
Beispiel #2
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:

        # get medicine and requied time
        medicine, d_time, interval = get_medicine_and_time(tracker)
        # print(medicine, d_time)
        resp = "Hii it's your time to take medicine: " + str(medicine)
        # print(resp)
        dispatcher.utter_message(text=resp)

        d_time = datetime.datetime.strptime(d_time, "%Y-%m-%d %H:%M:%S")
        # new_time = datetime.datetime.utcfromtimestamp(d_time) + datetime.timedelta(seconds=interval)
        new_time = d_time + datetime.timedelta(seconds=interval)
        print(new_time)
        reminder = ReminderScheduled(
            "EXTERNAL_reminder",
            trigger_date_time=new_time,
            entities={
                "medicine": medicine,
                "time": str(new_time),
                "interval": interval
            },
            kill_on_user_message=False,
        )

        return [reminder, AllSlotsReset()]
Beispiel #3
0
        def run(self, dispatcher: CollectingDispatcher,
                tracker: Tracker,
                domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
            # 1. In any method multiple dispatcher messages are not working. if you want to display buttons, images,
            #    text video attachments then it should be mentioned in one single message.
            # 2. In case you have more than one message and would like to display one after the other
            #    mention in domain.yml under utter or in stories where chat responses are mentioned else
            #    define different functions to send different messages.
            # 3. Remember only embedded videos can be played by bot. to embed a youtube video click on share and then
            #    select embed option and then paste the link in either domain.yml or actions.py for custom actions.

            dispatcher.utter_message(text="I will remind you in 30 seconds.Would you like to be notified by phone?",
                                     buttons=[{'title': 'Yes', 'payload': 'ask_phonenumber'},
                                              {'title': 'No', 'payload': 'deny'}])

            date = datetime.datetime.now() + datetime.timedelta(seconds=30)
            # dispatcher.utter_message("Hi {}, Welcome to the Payroll Chatbot!, How may I help you?".format(Name))
            reminder = ReminderScheduled(
                "EXTERNAL_reminder",
                trigger_date_time=date,
                name="my_reminder",
                kill_on_user_message=False,
            )

            return [reminder]
Beispiel #4
0
 def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     dispatcher.utter_template('utter_saludo', tracker)
     return [
         ReminderScheduled('action_schedule_reminder',
                           datetime.now() + timedelta(seconds=30),
                           kill_on_user_message=True)
     ]
Beispiel #5
0
 def run(self, dispatcher, tracker, domain):
     result = []
     result.append(
         ReminderScheduled(intent_name="EXTERNAL_last",
                           trigger_date_time=datetime.datetime.now() +
                           datetime.timedelta(seconds=10),
                           name="last_remind",
                           kill_on_user_message=True))
     return result
Beispiel #6
0
 def run(self, dispatcher, tracker, domain):
     slot_to_fill = tracker.get_slot("requested_slot")
     dispatcher.utter_template('utter_ask_{}'.format(slot_to_fill),tracker)
     result = []
     result.append(ReminderScheduled(intent_name="EXTERNAL_second",
                                     trigger_date_time=datetime.datetime.now()
                                     + datetime.timedelta(seconds=30),
                                     name="second_remind",
                                     kill_on_user_message=True))  
     return result
Beispiel #7
0
    def run(self, dispatcher, tracker, domain):
        dispatcher.utter_message(
            "I will remind you in 10 seconds. Please note, you will only see the next message if callbacks are enabled"
        )
        date = datetime.datetime.now() + datetime.timedelta(seconds=10)

        reminder = ReminderScheduled(
            "react_to_reminder",
            trigger_date_time=date,
            name="my_reminder",
            kill_on_user_message=False,
        )

        return [reminder]
Beispiel #8
0
 def run(self, dispatcher, tracker, domain):
     result = []
     # slot_to_fill = tracker.get_slot("requested_slot")
     # if slot_to_fill == " name1":
     #     result.append(SlotSet("name1", None))
     # else:
     #     result.append(SlotSet("user_confirm", None))
     result.append(
         ReminderScheduled(intent_name="EXTERNAL_second",
                           trigger_date_time=datetime.datetime.now() +
                           datetime.timedelta(seconds=10),
                           name="second_remind",
                           kill_on_user_message=True))
     return result
Beispiel #9
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        dispatcher.utter_message(
            text=
            "Goodbye!! Closing this chat in a 5 seconds.... (Note it will only work if callback is enabled)"
        )

        date = datetime.datetime.now() + datetime.timedelta(seconds=5)

        reminder = ReminderScheduled(
            "react_to_close_chat",
            trigger_date_time=date,
            name="close_chat",
            kill_on_user_message=False,
        )

        return [reminder]
Beispiel #10
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        mycursor.execute("select enum from prova where code='E1'")
        result = mycursor.fetchone()
        for i in result:
            enum = i
        sen = enum.replace(" ", "%20")
        dispatcher.utter_message(
            "<a href=mailto:[email protected]?subject=LMS%20Account%20Lock&body={}>Send Mail</a>"
            .format(sen))
        # class ReminderScheduled(action_name, trigger_date_time, name=None, kill_on_user_message=True, timestamp=None)

        return [
            ReminderScheduled("action_reminder",
                              datetime.now() + timedelta(seconds=20),
                              kill_on_user_message=False)
        ]
Beispiel #11
0
    def run(self, dispatcher, tracker, domain):

        # intent = tracker.events[-7].get("intent", {}).get("name")
        slot_to_fill = tracker.get_slot("requested_slot")
        dispatcher.utter_template('utter_ask_{}'.format(slot_to_fill), tracker)
        # if slot_to_fill == "name":
        #     dispatcher.utter_message(tracker.events[-7].get('text'))
        # if intent == 'chichat':
        #     dispatcher.utter_template('utter_ask_{}'.format(slot_to_fill),tracker)
        # else:
        #     dispatcher.utter_message(tracker.events[-6].get('text'))
        result = []
        result.append(
            ReminderScheduled(intent_name="EXTERNAL_second",
                              trigger_date_time=datetime.datetime.now() +
                              datetime.timedelta(seconds=30),
                              name="second_remind",
                              kill_on_user_message=True))
        return result
Beispiel #12
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:

        dispatcher.utter_message("I will remind you in 5 seconds.")

        date = datetime.datetime.now() + datetime.timedelta(seconds=5)
        entities = tracker.latest_message.get("entities")

        reminder = ReminderScheduled(
            "EXTERNAL_reminder",
            trigger_date_time=date,
            entities=entities,
            name="my_reminder",
            kill_on_user_message=False,
        )

        return [reminder]
Beispiel #13
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:

        date = datetime.datetime.now() + datetime.timedelta(
            hours=8)  # 16 hours
        entities = tracker.latest_message.get("entities")

        reminder = ReminderScheduled(
            "16h_fast_reminder",
            trigger_date_time=date,
            entities=entities,
            name="16h_fast_reminder",
            kill_on_user_message=False,
        )

        print("setting reminder")

        return [reminder]
Beispiel #14
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:

        # based on fasting time, set reminder (e.g. hours=16, if at start of fast)
        start_fast = tracker.get_slot('start_fast')

        if start_fast is None:  # if user is currently not fasting, assume he is at start of fast
            reminder_in_x_hours = 16
        else:
            start_fast_dt = datetime.strptime(str(start_fast),
                                              '%Y-%m-%d %H:%M:%S')
            hours_fasted, _ = _calc_fasting_since(start_fast_dt)
            if hours_fasted < 16:
                reminder_in_x_hours = 16
            elif hours_fasted < 20:
                reminder_in_x_hours = 4
            elif hours_fasted < 24:
                reminder_in_x_hours = 4
            elif hours_fasted < 48:
                reminder_in_x_hours = 24

        date = datetime.now() + timedelta(hours=reminder_in_x_hours)

        entities = tracker.latest_message.get("entities")
        reminder = ReminderScheduled(
            "fast_reminder",
            trigger_date_time=date,
            entities=entities,
            name="fast_reminder",
            kill_on_user_message=False,
        )
        print("setting reminder")

        return [reminder]
Beispiel #15
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        # dispatcher.utter_message("Here's a new question for you. Given two strings text1 and text2, return the length of their longest common subsequence.I am setting the timer to 5 seconds.")

        dispatcher.utter_message(
            "The quiz has started and so has the timer. We challenge you to finish it withing 20 minutest. Best of luck!"
        )
        date = datetime.datetime.now() + datetime.timedelta(seconds=7200)
        entities = tracker.latest_message.get("new")

        reminder = ReminderScheduled(
            "EXTERNAL_reminder",
            trigger_date_time=date,
            entities=entities,
            name="my_reminder",
            kill_on_user_message=False,
        )

        return [reminder]
Beispiel #16
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:

        success = tracker.get_slot("success")
        if success == "success":
            dispatcher.utter_message("I will remind you 2 hours before the event start.")

            start_time = dateutil.parser.parse(tracker.get_slot("time"))
            reminder_time = start_time + timedelta(hours=-2)

            reminder = ReminderScheduled(
                "EXTERNAL_reminder",
                trigger_date_time=reminder_time,
                name="my_reminder",
                kill_on_user_message=False,
            )
            return [reminder]
        elif success == "fail":
            return[]
Beispiel #17
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:

        dispatcher.utter_message(template="utter_cancel_leave_email_done")

        date = datetime.datetime.now() + datetime.timedelta(seconds=5)
        entities = tracker.latest_message.get("entities")

        reminder = ReminderScheduled(
            "EMAIL_reminder",
            trigger_date_time=date,
            entities=entities,
            name="my_reminder",
            kill_on_user_message=False,
        )
        # await asyncio.sleep(5)
        # dispatcher.utter_message(template="utter_email_done")

        return [reminder]
Beispiel #18
0
    def validate(self, dispatcher, tracker, domain):
        result = []
        result.append(
            ReminderScheduled(intent_name="EXTERNAL_reminder",
                              trigger_date_time=datetime.datetime.now() +
                              datetime.timedelta(seconds=30),
                              name="first_remind",
                              kill_on_user_message=True))
        slot_values = self.extract_other_slots(dispatcher, tracker, domain)
        value = tracker.latest_message.get("text")
        slot_to_fill = tracker.get_slot("requested_slot")
        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))
        if slot_to_fill == "time":
            value = tracker.latest_message["entities"]

            day = value[0]['value']
            month = value[1]['value']
            year = value[2]['value']

            time = "{} / {} / {}".format(day, month, year)
            result.append(SlotSet("time", time))
        if slot_to_fill == "call":
            if value.lower() in self.call_db():
                result.append(SlotSet("call", value))
            else:
                result.append(SlotSet("call", None))
        if slot_to_fill == "additional_support":
            if value.lower() in self.additional_support_db():
                result.append(SlotSet("additional_support", value))
            else:
                result.append(SlotSet("additional_support", None))
        for slot, value in slot_values.items():
            result.append(SlotSet(slot, value))

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

        reminder_title = tracker.get_slot("reminder_title")
        date_time = parser.parse(tracker.get_slot("time"))

        # print(tracker.latest_message.get("entities"))
        reminder = ReminderScheduled(
            "EXTERNAL_reminder",
            trigger_date_time=date_time.replace(tzinfo=None),
            timestamp=date_time.timestamp(),
            entities={"reminder_title": reminder_title},
            name=reminder_title,
            kill_on_user_message=False,
        )

        # print(reminder_title, date_time, reminder,sep='\n')

        dispatcher.utter_message("Reminder Set!")
        return [reminder]
Beispiel #20
0
    def validate(self, dispatcher, tracker, domain):
        result = []
        result.append(
            ReminderScheduled(intent_name="EXTERNAL_reminder",
                              trigger_date_time=datetime.datetime.now() +
                              datetime.timedelta(seconds=10),
                              name="first_remind",
                              kill_on_user_message=True))
        slot_values = self.extract_other_slots(dispatcher, tracker, domain)
        value = tracker.latest_message.get("text")
        slot_to_fill = tracker.get_slot("requested_slot")
        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))
        intent = tracker.latest_message.get("intent", {}).get("name")
        for slot, value in slot_values.items():
            result.append(SlotSet(slot, value))

        if slot_to_fill == "name1":
            if intent == "chitchat":
                result.append(SlotSet("name1", None))
                return result
        if slot_to_fill == "user_confirm":
            if intent == "affirm":
                result.append(SlotSet("user_confirm", value))
                return result
            if intent == "chitchat":
                result.append(SlotSet("user_confirm", None))
                return result
            if intent == "deny":
                dispatcher.utter_message("result la: {}".format(result))
                result[1] = SlotSet("name1", None)
                return result
            else:
                return [result]
        return result
Beispiel #21
0
 def validate(self, dispatcher, tracker, domain):
     result = []
     result.append(ReminderScheduled(intent_name="EXTERNAL_reminder",
                                     trigger_date_time=datetime.datetime.now()
                                     + datetime.timedelta(seconds=30),
                                     name="first_remind",
                                     kill_on_user_message=True))
     slot_values = self.extract_other_slots(dispatcher, tracker, domain)
     value = tracker.latest_message.get("text")
     slot_to_fill = tracker.get_slot("requested_slot")
     
     if slot_to_fill: 
         slot_values.update(self.extract_requested_slot(dispatcher,tracker,domain))
     for slot, value in slot_values.items():
         result.append(SlotSet(slot, value))
     if slot_to_fill == "phone":
         value = tracker.latest_message["entities"] 
         try :  
             phone = value[0]['value']
         except:
             result.append(SlotSet("phone",None))
             #dispatcher.utter_message(template='utter_ask_phone')
         else :
             phone = value[0]['value']
             if self.is_phone(phone):
                 result.append(SlotSet("phone",phone))
             else:
                 result.append(SlotSet("phone",None))      
             # phone = value[0]['value']
             # if phone:
             #     if self.is_phone(phone):
             #         result.append(SlotSet("phone",phone))
             #     else:
             #         result.append(SlotSet("phone",None))
             #         #dispatcher.utter_message(template='utter_ask_phone')
             # else:
             #     result.append(SlotSet("phone",None))
             #     #dispatcher.utter_message(template='utter_ask_phone')
     if slot_to_fill=="time":
         value = tracker.latest_message["entities"] 
         value_=[]
         for x in value:
             value_.append(x['entity'])
         if "day" in value_ and "month" in value_ and "year" in value_ and "hour" in value_:
             for x in value:
                 if x['entity'] == 'day':
                     day = x['value']
                 if x['entity'] == 'month':
                     month = x['value']
                 if x['entity'] == 'year':
                     year = x['value']
                 if x['entity'] == 'hour':
                     hour = x['value']
                     hour = self.convert_tail(hour)
             time = datetime.datetime(int(year),int(month),int(day),int(hour))
             time=time.strftime("%m/%d/%Y, %H:%M:%S")
             result.append(SlotSet("time",time))
         elif "day" in value_ and "month" in value_ and "year" in value_ :
             for x in value:
                 if x['entity'] == 'day':
                     day = x['value']
                 if x['entity'] == 'month':
                     month = x['value']
                 if x['entity'] == 'year':
                     year = x['value']
             time = datetime.datetime(int(year),int(month),int(day))
             time=time.strftime("%m/%d/%Y, %H:%M:%S")
             print(time)
             result.append(SlotSet("time",time))         
         elif "day2" in value_ and "hour" in value_  :
             for x in value:
                 if x['entity'] == 'day2':
                     day2 = x['value']
                     if day2 == "nay":
                         time= datetime.datetime.now()
                     elif day2 == "mai":
                         time= datetime.datetime.now() + datetime.timedelta(days=1)
                     elif day2 == "kia":
                         time = datetime.datetime.now() + datetime.timedelta(days=2)
                 if x['entity'] == 'hour':
                     hour = x['value']
                     hour = self.convert_tail(hour)
             time = time.replace(hour=int(hour),minute=0,second=0)
             time=time.strftime("%m/%d/%Y, %H:%M:%S")
             result.append(SlotSet("time",time))
         else:
             print(',,,,,,')
             result.append(SlotSet("time",None))
         # try:
         #     day = value[0]['value']
         #     month = value[1]['value']
         #     year = value[2]['value']
         # except :
         #     result.append(SlotSet("time",None))
         # else:
         #     day = value[0]['value']
         #     month = value[1]['value']
         #     year = value[2]['value']
         #     time = datetime.datetime(year,month,day)
         #     result.append(SlotSet("time",time))
     if slot_to_fill == "call":
         if value.lower() in self.call_db():
             result.append(SlotSet("call", value))
         else:
             result.append(SlotSet("call",None))
     if slot_to_fill == "additional_support":
         if value.lower() in self.additional_support_db():
             result.append(SlotSet("additional_support", value))
         else:
             result.append(SlotSet("additional_support",None))
     
     
     return result
Beispiel #22
0
    def run(self, dispatcher, tracker, domain):

        events = []
        payload = {
            "nlu": {
                "intent": tracker.latest_message["intent"]["name"],
                "entities": tracker.latest_message["entities"]
            }
        }

        url = "{base_url}/project/{project_id}/response".format(
            base_url=os.environ.get('BF_URL'),
            project_id=os.environ.get("BF_PROJECT_ID"))
        try:
            response_sent = False
            result = requests.post(url, json=payload)

            if result.status_code == 200:
                response = result.json()
                response_name = response["key"]
                dispatcher.utter_template(response_name, tracker)
                response_sent = True

                events.append(SlotSet('latest_response_name', response_name))
                if 'follow_up' in response and response['follow_up'].get(
                        'action'):
                    if response['follow_up']['action'].startswith('utter'):
                        action = 'action_botfront_mapping_follow_up'
                        events.append(
                            SlotSet('followup_response_name',
                                    response['follow_up']['action']))

                    # FollowUpAction produces random results, so we force a minimum delay for a reminder.
                    delay = max(2, int(response['follow_up']['delay']))
                    events.append(
                        ReminderScheduled(action,
                                          datetime.now() +
                                          timedelta(seconds=delay),
                                          kill_on_user_message=True))

            elif result.status_code == 404:
                logger.warning('Response not found for: {}'.format(
                    str(payload)))
                events.append(
                    SlotSet('latest_response_name',
                            'error_response_not_found'))
                if not response_sent:
                    dispatcher.utter_template("utter_fallback", tracker)
            else:
                logger.warning('Error {} with request: {}'.format(
                    result.status_code, str(payload)))
                events.append(
                    SlotSet('latest_response_name', 'error_unknown_error'))
                if not response_sent:
                    dispatcher.utter_template("utter_fallback", tracker)

        except StopIteration:
            logger.error('Error with request {}: {}'.format(
                str(payload), "No intent was passed as an entity"))
            events.append(SlotSet('latest_response_name', 'error_no_intent'))
            dispatcher.utter_template("utter_fallback", tracker)
        except Exception as e:
            logger.error('Error with request {}: {}'.format(str(payload), e))
            events.append(
                SlotSet('latest_response_name', 'error_unknown_error'))
            dispatcher.utter_template("utter_fallback", tracker)
        return events