Exemplo n.º 1
0
 def run(self, dispatcher: CollectingDispatcher,
         tracker: Tracker,
         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     brands = tracker.latest_message['text']
     if brands.lower().strip() != 'no preference':
         return [SlotSet('brand', self.reformat_brands(brands)), FollowupAction('action_recommend_laptop')]
     return [SlotSet('brand', []), FollowupAction('action_recommend_laptop')]
Exemplo n.º 2
0
    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker, domain: Dict[Text, Any]
            ) -> List[Dict[Text, Any]]:
        """Check that 'size' is a valid value (small, medium, or large).

        Args:
            dispatcher: Rasa collecting dispatcher
            tracker: Rasa tracker
            domain: Rasa domain

        Return:
            List[Dict[Text, Any]]: Set slots item and size

        """
        user_cart = cart.get_user_cart(tracker.sender_id)
        item_size_result = user_cart.validate_size(tracker.get_slot('item'), tracker.get_slot('size'))
        if not item_size_result[0]:
            dispatcher.utter_message(template='utter_invalid_item')
            return [SlotSet('item', None), SlotSet('size', None), FollowupAction('action_listen')]
        elif not item_size_result[1]:
            dispatcher.utter_message(template='utter_invalid_size')
            item_match = user_cart.menu.menu_items[user_cart.menu.get_matching_menu_item(tracker.get_slot('item'))]
            dispatcher.utter_message(item_match.describe_options('size'))
            return [SlotSet('item', item_size_result[0]), SlotSet('size', None), FollowupAction('action_listen')]
        return [SlotSet('item', item_size_result[0]), SlotSet('size', item_size_result[1])]
Exemplo n.º 3
0
 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."""
     if tracker.get_slot("email"):
         return [FollowupAction("resend_email_form")]
     else:
         return [FollowupAction("reset_email_form")]
Exemplo n.º 4
0
    def run(self, dispatcher, tracker, domain):
        """this function finds the corresponding address of the suggested restaurant via index
           Step 1:it creates the lists again
           Step 2:then gives the address    
        
        Args:
            dispatcher: sends message back to user
            tracker: gets the values of the slots filled by the user
            domain (Dict): gets the right intents, actions and templates
        """
        cuisine = tracker.get_slot('cuisine')

        restaurant = tracker.get_slot('restaurant')
        #step 1
        restaurants = zomatoFetchRestaurants(dispatcher)
        addresses = zomatoFetchAddresses(dispatcher)

        #step 2
        if cuisine == None:
            dispatcher.utter_message('Sorry, something went wrong.')
            return [FollowupAction("utter_cuisine")]
        elif restaurant == None:
            dispatcher.utter_message('Sorry, something went wrong.')
            return [FollowupAction("utter_cuisine")]
        else:
            cuisine = cuisine.lower()
            pick = restaurants.index(restaurant)
            dispatcher.utter_message('The address is ' + addresses[pick] +
                                     '. Bon appetit!')
            return [
                SlotSet('cuisine', cuisine),
                SlotSet('restaurant', restaurant)
            ]
Exemplo n.º 5
0
    async def run(
        self,
        dispatcher,
        tracker,
        domain,
    ):
        logger.info("query_school")
        attribute = tracker.get_slot("attribute")

        url = "api/v2/schoolProfiles"
        logger.info("On Query School action")

        results = school_info(
            url,
            attribute,
            tracker,
        )

        if results is None:

            dispatcher.utter_message(
                "Sorry, 🤔 It seems I don't have that information about your school."
            )
            return [FollowupAction("action_bottom_top_menu")]

        text = resolve_message(
            intent="school_info",
            attribute=attribute,
            results=results,
        )
        dispatcher.utter_message(text)
        return [FollowupAction("action_bottom_top_menu")]
    def run(self, dispatcher, tracker, domain):

        country_state = next(tracker.get_latest_entity_values("country_state"),
                             None)
        print("country state is {}".format(country_state))

        decsis_api = DecsisAPI()
        stats = decsis_api.search(country_state)

        if stats['code'] == 200 and not stats['has_data']:
            return [
                SlotSet('country_region_search_successful', 'empty'),
                SlotSet('country_code', 'BR'),
                FollowupAction("utter_country_region_nodata")
            ]
        elif stats['code'] == 200 and stats['has_data']:
            return [
                SlotSet('country_region_search_successful', 'ok'),
                SlotSet('country_region', stats.get('state', "N/A")),
                SlotSet('country_region_confirmed_accum',
                        int(stats.get('confirmed', "N/A"))),
                SlotSet('country_region_confirmed_new',
                        int(stats.get('confirmed_new', "N/A"))),
                SlotSet('country_region_deaths_accum',
                        int(stats.get('deaths_accum', "N/A"))),
                SlotSet('country_region_deaths_new',
                        int(stats.get('deaths_new', "N/A"))),
                FollowupAction("utter_country_state_hasdata")
            ]
        else:
            return [
                SlotSet('country_region_search_successful', 'not-ok'),
                SlotSet('country_code', 'BR'),
                FollowupAction("utter_country_region_nodata")
            ]
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        if (tracker.get_slot('bot_location') != "br"):
            # print("     !!! not br")
            today = date.today()
            return [
                SlotSet("bot_date", today.strftime("%d/%m/%Y")),
                FollowupAction("utter_features_date")
            ]
        else:
            # print("     !!! br")
            date_output = "%d/%m/%Y"
            brazil_acre = datetime.now(timezone('Brazil/Acre'))
            brazil_fnoronha = datetime.now(timezone('Brazil/DeNoronha'))
            brazil_brasilia = datetime.now(timezone('Brazil/East'))
            brazil_amazonas = datetime.now(timezone('Brazil/West'))

            return [
                SlotSet("bot_date_acre", brazil_acre.strftime(date_output)),
                SlotSet("bot_date_fnoronha",
                        brazil_fnoronha.strftime(date_output)),
                SlotSet("bot_date_brasilia",
                        brazil_brasilia.strftime(date_output)),
                SlotSet("bot_date_amazonas",
                        brazil_amazonas.strftime(date_output)),
                FollowupAction("utter_features_date")
            ]
Exemplo n.º 8
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        message = tracker.latest_message["text"]

        if self.is_int(message):
            val = int(message)
            if val == 1:
                return [FollowupAction("show_products_form")]
            elif val == 2:
                return [FollowupAction("get_price_form")]
            elif val == 3:
                return [FollowupAction("show_history_form")]
            elif val == 4:
                return [FollowupAction("action_show_stats")]
            else:
                dispatcher.utter_message(
                    text=
                    "Didnt understand you please choose any one option from above"
                )
                return [FollowupAction("action_dispatch_task")]
        else:
            intent = re.findall

        return []
Exemplo n.º 9
0
    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker, Domain: Dict[Text, Any]
            ) -> List[Dict[Text, Any]]:
        """Create cart object and load selected menu into cart object.

        Check if there is a menu corresponding to the store slot
        if not, utter error message. If menu exists, load and store in cart.

        Args:
            dispatcher: Rasa CollectingDispatcher
            tracker: Rasa Tracker
            domain: Rasa domain

        Return:
            List[Dict[Text, Any]]: SlotSet('cart')

        """
        user_cart = cart.get_user_cart(tracker.sender_id)
        curr_store = tracker.get_slot('store')
        if curr_store is None:
            dispatcher.utter_message(template="utter_no_store_selected")
            return [FollowupAction('action_listen')]
        elif user_cart.menu is not None and curr_store == user_cart.menu.name:
            return []
        else:
            # TODO: move menus to a more permanent shared folder
            menu_match = user_cart.get_matching_menu(curr_store, MENU_PATH)
            if menu_match is not None:
                user_cart.menu = cart.Menu.load_menu(menu_match, MENU_PATH)
            if menu_match is None or user_cart.menu is None:
                dispatcher.utter_message(template="utter_menu_not_found")
                return[SlotSet('store', None), FollowupAction('action_listen')]
        return[]
Exemplo n.º 10
0
    async def run(
        self, dispatcher, tracker: Tracker, domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        
        school_id = extract_schoolid_from_tracker(tracker)
        logger.info("action_queryredis_csv") 
        if not school_id:
            dispatcher.utter_message(
                "Sorry 🤔 something is wrong.Please try again later."
            )
            return []
        context = tracker.get_slot("context")
        try:
            parent_button_list = get_parent_button(school_id)
        except ConnectionError as e:
            logger.error("Connection error to redis server Error Message{e}")
            dispatcher.utter_message(
                "Sorry 🤔 something is wrong.Please try again later."
            )
            return []
        

        parentbuttonlabel = list(parent_button_list.keys())
        parentbuttonpayload = list(parent_button_list.values())
        buttons = []
        if not parentbuttonlabel and not parentbuttonpayload:

            return [FollowupAction("action_bottom_top_menu")]

        # this loop generate button for parent i.e. button right after csv
        for button_label, button_id in zip(
            parentbuttonlabel, parentbuttonpayload
        ):
            payload = {
                "buttonid": button_id,
                "new_action": "action_queryredisid",
            }
            payload = json.dumps(payload)
            buttons.append(
                {"title": f"{button_label}", "payload": f"/router{payload}"}
            )

        # find previous context before current context "schoolinfo" from csv and take contol to action_help_menu for back button
        help_context = help_db[help_db["context"] == context]

        context = help_context.prev_context_leaf.values[0]

        backbuttonpayload = {
            "buttonid": None,
            "context": context,
            "new_action": "action_help_menu",
        }
        backbuttonpayload = json.dumps(backbuttonpayload)
        buttons.append(
            {"title": "Back", "payload": f"/router{backbuttonpayload}"}
        )
        dispatcher.utter_message(text="This is what I have", buttons=buttons)

        return [FollowupAction("action_listen")]
Exemplo n.º 11
0
    def run(self, dispatcher, tracker, domain):
        """this function...
        Step 1: first lets the user know that the bot is searching
        Step 2: then it creates the lists via the previous functions
        Step 3: then it looks whether the cuisine the user wants, is actually available
        Step 4a:if it is it gives the suggestion
        Step 4b:if not it says it could not find one
    
        Args:
            dispatcher: sends message back to user
            tracker: gets the values of the slots filled by the user
            domain (Dict): gets the right intents, actions and templates
        """
        cuisine = tracker.get_slot('cuisine')

        if cuisine == None:
            dispatcher.utter_message(
                'Sorry, this type of restaurant is not in my database. Could you be more precise?'
            )
            return [FollowupAction("utter_cuisine")]
        elif cuisine.lower == 'any':
            cuisine = cuisine.lower()
            restaurants = zomatoFetchRestaurants(dispatcher)
            cuisines = zomatoFetchCuisines(dispatcher)

            pick = random.randint(1, 21)

            dispatcher.utter_message('What do you think of ' +
                                     restaurants[pick] +
                                     ', a restaurant that serves ' +
                                     cuisines[pick] + '?')
        else:

            #step 1
            restaurants = zomatoFetchRestaurants(dispatcher)
            cuisines = zomatoFetchCuisines(dispatcher)
            cuisine = cuisine.lower()
            #step 2 (often multiple cuisines per restaurant, therefore it needs to look for substrings)
            fullcuisine = next((text for text in cuisines if cuisine in text),
                               None)

            #step 3b
            if fullcuisine == None:
                dispatcher.utter_message(
                    'Sorry, I could not find this type of restaurant near you. Please choose another cuisine or be more precise.'
                )
                return [FollowupAction("utter_cuisine")]
            #step 3a
            else:
                pick = cuisines.index(fullcuisine)
                restaurant = restaurants[pick]
                dispatcher.utter_message('What do you think of ' + restaurant +
                                         ', a restaurant that serves ' +
                                         cuisines[pick] + '?')

            return [
                SlotSet('cuisine', cuisine),
                SlotSet('restaurant', restaurant)
            ]
Exemplo n.º 12
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        logger.success("on search resources through nlu action")

        if (len(tracker.events) >= 4 and tracker.events[-4].get("name")
                == "action_ask_affirmation"):
            query = tracker.events[-5].get("text")
        else:
            query = tracker.latest_message["text"].split(" ", 1)[1]

        dispatcher.utter_message(
            text="Searching resources, please wait...😊!")
        courses = object_list("courseId", tracker)

        res = await self._get_recommendation(query, courses)
        if not res:
            dispatcher.utter_message(
                "I couldn't find any resources that maybe helpful to you.")
            return [
                SlotSet("data", None),
                FollowupAction("action_bottom_top_menu"),
            ]

        if res is None:
            dispatcher.utter_message(
                "I couldn't find any resources.Something must be wrong.🤔 Check again later, sorry."
            )

            return [
                SlotSet("data", None),
                FollowupAction("action_bottom_top_menu"),
            ]
        dispatcher.utter_message(
            "You might find the following link helpful: \n")
        for i, (title, url) in enumerate(res):
            buttons_list = []
            if url and title:
                payload = f"{url}"
                payload = json.dumps(payload)
                buttons_list.append({
                    "title": title,
                    "payload": f"{payload}/link"
                })
            if i == 3:
                break
            dispatcher.utter_message(text="", buttons=buttons_list)
        return [
            SlotSet("data", None),
            FollowupAction("action_bottom_top_menu"),
        ]

        return [
            SlotSet("data", None),
            FollowupAction("action_bottom_top_menu"),
        ]
Exemplo n.º 13
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        choice = tracker.latest_message.get('text')
        if (choice == str(1)):
            return [FollowupAction("utter_instruction")]
        elif (choice == str(2)):
            return [FollowupAction("action_meow_yum_yuck")]
Exemplo n.º 14
0
    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        if not tracker.get_slot("bot_introduced"):
            return [SlotSet("bot_introduced", True), FollowupAction("utter_pt_welcome")]
        else:
            return [FollowupAction("utter_pt_greeting_hello")]
Exemplo n.º 15
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: "DomainDict",
    ) -> List[Dict[Text, Any]]:
        """
        Executes this action.

        Args:
            dispatcher: the dispatcher
            tracker: the tracker
            domain: the domain

        Returns: list of slots

        """

        found_object_names = tracker.get_slot(SLOT_FOUND_OBJECT_NAMES)
        object_attribute = tracker.get_slot(
            get_object_info.SLOT_OBJECT_ATTRIBUTE
        )

        # If no parameters were set, then quit
        if not found_object_names or len(found_object_names) == 0:
            dispatcher.utter_message(text=f"I don't think I know any.")
            return [FollowupAction(name=ACTION_LISTEN_NAME)]

        # Find objects of the given type
        found_objects: List[Object] = []
        for object in self.objects:
            if object.name in found_object_names:
                found_objects.append(object)

        if len(found_objects) == 1:
            found_object = found_objects[0]
            dispatcher.utter_message(response=found_object.intro.name)

            if object_attribute:
                attribute_value = found_object.__getattribute__(
                    object_attribute
                )

                if attribute_value:
                    dispatcher.utter_message(response=attribute_value.name)

        elif len(found_objects) > 0:
            dispatcher.utter_message(text=f"You have a few options.")

            for object in found_objects:
                dispatcher.utter_message(response=object.intro.name)
        else:
            dispatcher.utter_message(text=f"I don't think I know any.")

        return [FollowupAction(name=ACTION_LISTEN_NAME)]
Exemplo n.º 16
0
    def submit(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:
        fromcity = tracker.get_slot('fromloc_city')
        tocity = tracker.get_slot('toloc_city')
        time = tracker.get_slot('depart_time')
        if type(time) == dict:
            time1 = time["from"].split(".")[0].replace("T", " ")
            time1 = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')

            time2 = time["to"].split(".")[0].replace("T", " ")
            time2 = datetime.datetime.strptime(time2, '%Y-%m-%d %H:%M:%S')

            # dispatcher.utter_message("between {}  and {} .".format(time1, time2))
        elif type(time) == str:
            time1 = time.split(".")[0].replace("T", " ")
            time1 = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')
            # dispatcher.utter_message("at {} ".format(time1))
            time2 = time1 + datetime.timedelta(days=2)
            time1 = time1 + datetime.timedelta(days=-1)
            # dispatcher.utter_message("at {} {} ".format(time1, time2))
        dispatcher.utter_message(
            "Ok. Search the flight tickets from {} to {} between {} and {}.".
            format(fromcity, tocity, time1, time2))
        # myFormat = "{:<10} \t{:<10} \t{:<20} \t{:<10} \t{:<10} \t{:<20} \t{:<10}"
        # list1 = [myFormat.format("From", "To", "Airlines", "Seats", "Flight No", "Date", "Price")]
        list1 = []
        with open("ticket.json") as f:
            data = json.loads(f.read())
            for item in data:
                item_date = datetime.datetime.strptime(item["Date"],
                                                       '%Y-%m-%d %H:%M:%S')
                if item['From'].upper() == fromcity.upper() and \
                        item['To'].upper() == tocity.upper() and \
                        time1 <= item_date <= time2:
                    list1.append(
                        "Flight : " + item['Flight No'] + "  \nFrom-To : " +
                        item['From'] + " - " + item['To'] + "  \nAirline : " +
                        item['Airlines'] + "  \nDate : " + item['Date'] +
                        "  \nPrice :" + item['Price']
                        # myFormat.format(item['From'], item['To'], item['Airlines'], str(item['Seats']), item['Flight No'], item['Date'],  item['Price'])
                    )
        if len(list1) > 1:
            flights_list = ""
            for i in range(len(list1)):
                flights_list += (list1[i] + "\n\n")
            dispatcher.utter_message(flights_list)
            return [FollowupAction("booking_form")]
        else:
            dispatcher.utter_message("Sorry! There are no flights available.")
            return [FollowupAction("action_research")]
Exemplo n.º 17
0
    def submit(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:
        source_post_package = tracker.get_slot('source_post_package')
        buy_vip_duration = tracker.get_slot('buy_vip_duration')
        used_vip_duration = tracker.get_slot('used_vip_duration')

        vip_type = convert_post_package(source_post_package)
        _, _, _, bought_days = convert_duration(buy_vip_duration)
        _, _, _, used_days = convert_duration(used_vip_duration)

        if vip_type is None:
            return [FollowupAction('utter_ask_source_post_package')]

        discount = 0
        for i in discounts.keys():
            if used_days >= i:
                discount = discounts[i]

        used_cost = fee_table[vip_type]['fee'][1] * used_days * (1 - discount)
        paid_cost = fee_table[vip_type]['fee'][bought_days]

        message1 = 'Bạn đã dùng gói {} được {} ngày trên tổng số {} ngày. Vậy số tiền bạn đã dùng là {}đ.'.format(
            fee_table[vip_type]['name'], used_days, bought_days,
            price_format(used_cost))

        destination_post_package = tracker.get_slot('destination_post_package')
        buy_new_vip_duration = tracker.get_slot('buy_new_vip_duration')

        vip_type_new = convert_post_package(destination_post_package)
        _, _, _, bought_days_new = convert_duration(buy_new_vip_duration)

        if vip_type_new is None:
            return [FollowupAction('utter_ask_destination_post_package')]

        paid_cost_new = fee_table[vip_type_new]['fee'][bought_days_new]

        result = int(float((paid_cost - used_cost - paid_cost_new)))

        if result > 0:
            message2 = 'Khi đổi sang gói {} với thời gian {} ngày bạn sẽ được hoàn lại {}đ vào Tài khoản khuyến mại.'.format(
                fee_table[vip_type_new]['name'], bought_days_new,
                price_format(float(result)))
        else:
            message2 = 'Khi đổi sang gói {} với thời gian {} ngày bạn sẽ cần thanh toán thêm {}đ.'.format(
                fee_table[vip_type_new]['name'], bought_days_new,
                price_format(float(result) * -1))
        dispatcher.utter_message(message1)
        dispatcher.utter_message(message2)
        return []
Exemplo n.º 18
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        global randomnum, myresult, hintlist, hintmaxx, hintcnt, finfo, count, i
        ansentity = next(tracker.get_latest_entity_values("answer"), None)
        count = count + 1
        if i == 4:
            return [FollowupAction("action_send_problem_link")]

        # dispatcher.utter_message(text="Hello World!")

        return [FollowupAction("action_quiz")]
Exemplo n.º 19
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        if (len(number) == 0):
            dispatcher.utter_message("모든 문제를 완료하였습니다. \n 점수저장을 위해 이름을 입력해주세요")

            return [SlotSet("name", "테스트"), FollowupAction("Action_name")]

        problem = quiz.Getproblem(number[0], select_quiz)
        dispatcher.utter_message(problem)

        return [FollowupAction("Action_answer")]
Exemplo n.º 20
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        logger.info("On Query announcement action")

        url = "announcements/messages/students"
        if tracker.get_slot("context") == "help_class_announcements":

            data = {
                "sortBy": "",
                "sortOrder": "",
                "batchId": [],
                "courseId": [],
                "filterBy": "Class_Announcement",
                "page": 1,
                "size": 10,
            }

        else:

            data = {
                "sortBy": "",
                "sortOrder": "",
                "batchId": [],
                "courseId": [],
                "filterBy": "General_Announcement",
                "page": 1,
                "size": 10,
            }

        text = announcement_list(
            url,
            data,
            tracker,
        )
        if not text:
            dispatcher.utter_message(
                "I couldn't find any announcements at the moment.Check again later. "
            )
            return [FollowupAction("action_bottom_top_menu")]

        if text is None:
            dispatcher.utter_message(
                "I couldn't find any announcements. Something must be wrong.🤔 Check again later, sorry. "
            )
            return [FollowupAction("action_bottom_top_menu")]

        dispatcher.utter_message(text)
        return [FollowupAction("action_bottom_top_menu")]
Exemplo n.º 21
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        logger.debug("---- [ActionCheckEquipment] ----")

        try:
            # Get slot value
            muscle = tracker.get_slot('muscle')
            facility = tracker.get_slot('facility')
            deny = tracker.get_slot('deny')
            intent = tracker.latest_message['intent'].get('name')

            logger.debug("m:{}, f:{}, d:{}, ent:{}".format(
                muscle, facility, deny, intent))

            # Need to know equipments
            if tracker.latest_message['intent'].get('name') == 'query':
                dispatcher.utter_template('utter_query_equipment', tracker)
                dispatcher.utter_message(" - {}".format(
                    equipmentMapping(muscle)))
                return []
            # Need suggestion
            elif intent == 'negative' or deny != None or tracker.get_slot(
                    'suggest') != None:
                rnd = random.choice(list(equipmentMapping(muscle)))
                respond = 'Let us use {} to do some exercise!!'.format(rnd)
                dispatcher.utter_message(respond)
                return [
                    SlotSet('facility', rnd),
                    SlotSet('suggest', None),
                    SlotSet('deny', None),
                    FollowupAction('action_search_exercise')
                ]

            # Find the equipment
            if facility != None and facility.lower() in equipmentMapping(
                    muscle):
                return [FollowupAction('action_search_exercise')]
            # Cannot find the equipment and give random one.
            else:
                rnd = random.choice(list(equipmentMapping(muscle)))
                respond = 'Sorry, there is no exercise go with this equipment. But we recommend use {} to replace.'.format(
                    rnd)
                dispatcher.utter_message(respond)
                return [
                    SlotSet('facility', rnd),
                    FollowupAction('action_search_exercise')
                ]

        except:
            dispatcher.utter_template('utter_system_wrong')
            return [AllSlotsReset(), FollowupAction('action_restart')]
Exemplo n.º 22
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        logger.debug("---- [ActionCheckBody] ----")

        # Get slot value
        body = tracker.get_slot('body')
        suggest = tracker.get_slot('suggest')
        muscle = tracker.get_slot('muscle')
        facility = tracker.get_slot('facility')

        logger.debug("b:{}, s:{}, m:{}, f:{}".format(body, suggest, muscle,
                                                     facility))

        try:
            # Need a exercise suggestion.
            if suggest != None:
                rnd = random.choice(exerciseList)
                msg = "I recommend to do some {} exercise with {}!!\nFYI {}".format(
                    rnd['Body'], rnd['equipment'], rnd['resource'])
                dispatcher.utter_message(msg)
                return [AllSlotsReset(), FollowupAction('action_restart')]
            # Body part question
            elif tracker.latest_message['intent'].get('name') == 'query':
                respond = "You can choice following body: {}".format(
                    list(bodyMap.keys())[0:])
                dispatcher.utter_message(respond)
                return [FollowupAction('action_listen')]

            # Check body is vaildated.
            if body != None and body.lower() in [
                    item.lower() for item in list(bodyMap.keys())
            ]:
                dispatcher.utter_message(template='utter_check_muscle')
                return [
                    SlotSet('muscle', None),
                    SlotSet('facility', None),
                    SlotSet('deny', None),
                    SlotSet('suggest', None)
                ]

            dispatcher.utter_message(template='utter_cannot_understand')
            respond = "Please check the spelling of body part\n"
            respond = respond + "\tFollowing is the body list: {}\n".format(
                list(bodyMap.keys())[0:])
            respond = respond + "Which part of body exercise you want to know?"
            dispatcher.utter_message(respond)
            return [AllSlotsReset(), FollowupAction('action_restart')]

        except:
            dispatcher.utter_template('utter_system_wrong')
            return [AllSlotsReset(), FollowupAction('action_restart')]
Exemplo n.º 23
0
    async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                  domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        last_intent = tracker.get_intent_of_latest_message()

        if last_intent == 'exit':
            return [FollowupAction('utter_goodbye')]
        elif last_intent == 'set_time':
            return [FollowupAction('action_set_time')]

        dispatcher.utter_message(text=f'last intent: {last_intent}')

        return []
Exemplo n.º 24
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        logger.success("on search resources action")

        data = tracker.get_slot("data")
        query = data

        dispatcher.utter_message(
            text="Searching resources, please wait...😊!")
        courses = [tracker.get_slot("course_id")]

        res = await self._get_recommendation(query, courses)
        if not res:
            dispatcher.utter_message(
                "I couldn't find any resources that maybe helpful to you.")
            return [
                SlotSet("data", None),
                FollowupAction("action_bottom_top_menu"),
            ]

        if res is None:
            dispatcher.utter_message(
                "I couldn't find any resources.Something must be wrong.🤔 Check again later, sorry."
            )

            return [
                SlotSet("data", None),
                FollowupAction("action_bottom_top_menu"),
            ]
        dispatcher.utter_message(
            "You might find the following link helpful: \n")
        for i, (title, url) in enumerate(res):
            buttons_list = []
            if url and title:
                payload = f"{url}"
                payload = json.dumps(payload)
                buttons_list.append({
                    "title": title,
                    "payload": f"{payload}/link"
                })
            if i == 3:
                break
            dispatcher.utter_message(text="", buttons=buttons_list)
        return [
            SlotSet("data", None),
            FollowupAction("action_bottom_top_menu"),
        ]
Exemplo n.º 25
0
    async def run(
        self, dispatcher, tracker: Tracker, domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        logger.info("action_elastic_redis")
        last_message = tracker.latest_message.get("text")
        school_id = extract_schoolid_from_tracker(tracker)
        
        if not school_id:
            dispatcher.utter_message(
                "Sorry 🤔 something is wrong.Please try again later."
            )
            return []
        buttonid = search_query_fallback(last_message, school_id)
        if isinstance(buttonid, str):
            return [
                SlotSet("buttonid", buttonid),
                FollowupAction("action_queryredisid"),
            ]
        elif isinstance(buttonid, zip):
            buttons = []
            for objectid, label in buttonid:
                payload = {
                    "buttonid": objectid,
                    "new_action": "action_queryredisid",
                }
                payload = json.dumps(payload)

                buttons.append(
                    {"title": label, "payload": f"/router{payload}",}
                )
            payload = {
                "context": "School Info",
                "new_action": "action_help_menu",
            }
            payload = json.dumps(payload)
            buttons.append(
                {"title": "School Info", "payload": f"/router{payload}"}
            )
            message_title = "Do you mean any of these"
            dispatcher.utter_message(text=message_title, buttons=buttons)
            return []
        else:
            dispatcher.utter_message(
                "Sorry something is wrong.Please try again later."
            )
            
            return [
                SlotSet("new_action", "action_help_menu"),
                SlotSet("context", "help"),
                FollowupAction("action_router"),
            ]
Exemplo n.º 26
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        logger.info("On Query Quiz action")

        url = "api/v2/students/quiz?"
        if tracker.get_slot("context") == "help_not_attempted_quiz":
            params = {
                "courseIds": "",
                "batchIds": "",
                "quizAttemptType": "NOT_ATTEMPTED",
                "quizType": "QUIZ",
                # "page": 1,
                # "size": 10,
            }

        elif tracker.get_slot("context") == "help_passed_quiz":

            params = {
                "courseIds": "",
                "batchIds": "",
                "quizAttemptType": "PASSED",
                "quizType": "QUIZ",
            }
        else:
            params = {
                "courseIds": "",
                "batchIds": "",
                "quizAttemptType": "FAILED",
                "quizType": "QUIZ",
            }
        text = quiz_list(url, params, tracker, tracker.get_slot("context"))

        if not text:  # for empty lists
            dispatcher.utter_message(
                "I couldn't find any quizzes at the moment.Check again later! 🤓 "
            )
            return [FollowupAction("action_bottom_top_menu")]

        if text is None:  # for exception
            dispatcher.utter_message(
                "I couldn't find any quizes. Something must be wrong.🤔 Check again later, sorry."
            )
            return [FollowupAction("action_bottom_top_menu")]

        dispatcher.utter_message(text)
        return [FollowupAction("action_bottom_top_menu")]
Exemplo n.º 27
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        movieDate = tracker.get_slot("movieDate")
        movieChoice = tracker.get_slot("movieChoice")
        noTickets = tracker.get_slot("noTickets")
        with open("data/movieSchedule.json", "r") as MS:
            movieSchedule = json.load(MS)
        with open("data/movieSeatMap.json", "r") as SM:
            movieSeatMap = json.load(SM)
        movieSeatMap = movieSeatMap[str(movieDate)][str(movieChoice)]
        message = str((tracker.latest_message)['text'])
        seats = str(message).split(",")
        newSeats = []
        flag = 0
        for i in range(len(seats)):
            for i1 in range(len(seats)):
                if i != i1:
                    if seats[i] == seats[i1]:
                        flag = 1
        if (flag == 1):
            msg = "Invalid Seat selection detected !"
            dispatcher.utter_message(msg)
            return [FollowupAction("slot_display")]
        if (str(len(seats)) != str(noTickets)):
            msg = "Please select only  ", str(noTickets), " seats..."
            dispatcher.utter_message(msg)
            return [FollowupAction("slot_display")]
        else:
            newSeats = seats
        seatCount = 0
        for seat in newSeats:
            i = seat[0]
            j = seat[1:]
            try:
                if ((movieSeatMap[str(i)][str(j)]) == "1"):
                    seatCount = seatCount + 1
                else:
                    seatCount = seatCount + 0
            except:
                msg = "Invalid Seat selection detected !"
                dispatcher.utter_message(msg)
                return [FollowupAction("slot_display")]
        if (seatCount == int(noTickets)):
            return [FollowupAction("utter_seat_confirmation")]
        else:
            dispatcher.utter_message(
                "One or More seats are booked.Please re-enter your selection!")
            return [FollowupAction("slot_display")]
Exemplo n.º 28
0
    def submit(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:

        most_recent_state = tracker.current_state()
        sender_id = most_recent_state['sender_id']
        phone_number = tracker.get_slot("phone_number")
        phone_number_converted = '+{}'.format(phone_number)
        sender_id_converted = '{}'.format(sender_id)

        #TODO: Check if user phone number exists in job DB
        phone_number = tracker.get_slot("phone_number")
        job_title = tracker.get_slot("job_title")

        # after phone number submission and previously applied for the same role, prompt this
        if has_already_applied(phone_number=int(phone_number),
                               job_title=job_title):
            dispatcher.utter_message(
                template="utter_already_applied_for_this_job")
            # data = job_openings()
            # message = {"payload": "quickReplies", "data": data}
            # dispatcher.utter_message(text="These are the job openings we have right now.👇", json_message=message)
            return [
                FollowupAction("action_show_job_openings"),
                AllSlotsReset()
            ]

        # after phone number submission and not previously applied for the same role, ask for email id
        else:
            ask_email = "Your 𝐞𝐦𝐚𝐢𝐥? <br> We'll use it to inform you in case you are selected 😊"
            dispatcher.utter_message(text=ask_email)
            return []
Exemplo n.º 29
0
 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')]
Exemplo n.º 30
0
 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')]