예제 #1
0
 def run(self, dispatcher, tracker, domain):
     # if we dont know the product the user is migrating from,
     # store his last message in a slot.
     return [SlotSet("unknown_product", tracker.latest_message.get("text"))]
예제 #2
0
 def run(self, dispatcher, tracker, domain):
     return [SlotSet("test", self.some_common_feature())]
예제 #3
0
 def submit(self, dispatcher, tracker, domain):
     return [SlotSet("other_slot", 42)]
예제 #4
0
    async def run(
        self, dispatcher, tracker: Tracker, domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
    
        logger.info("action_queryredisid")
        parentid = tracker.get_slot("buttonid")
        try:
            button_obj = read_obj(parentid)
        except ConnectionError:
            logger.error("Connection error to redis server Error Message{e}")
            dispatcher.utter_message("Sorry 🤔 something is wrong.Please try again later.")
        # button_obj = read_obj(parentid)  # Only None when we are in parent node
        
        if not button_obj:
            return [
                FollowupAction("action_router"),
                SlotSet("new_action", "action_queryredis_csv"),
                SlotSet("context", "School Info"),
            ]
        message_list = []

        if button_obj.get("answerTypes"):

            answer_type = ast.literal_eval(button_obj.get("answerTypes"))
            for p in answer_type:
                

                if p["type"] == "text":
                    message = p.get("text")
                    message = random.choice(message)
                    message_info = {"type": "text", "msg": message}

                    message_list.append(message_info)
                else:
                    message = p.get("uri")
                    message = random.choice(message)
                    message_info = {"type": "uri", "msg": message}
                    message_list.append(message_info)
                    
       

        backbutton_payload = {
            "buttonid": button_obj.get("parent"),
            "new_action": "action_queryredisid",
        }
        backbutton_payload = json.dumps(backbutton_payload)

        child_button_id = ast.literal_eval(button_obj.get("children"))
        if not child_button_id:
            for message in message_list:
                if message["type"] == "text":
                    text = message["msg"]
                    

                    dispatcher.utter_message(text=text)

                else:
                    attachment = message["msg"].rsplit("/", 1)[-1]
                    buttons_list = []
                    logger.info(f"attachment is {attachment} ")

                    payload = f"{message['msg']}"
                    payload = json.dumps(payload)
                    buttons_list.append(
                        {"title": attachment, "payload": f"{payload}/link",}
                    )
                    dispatcher.utter_message(
                        text="Please click the following link",
                        buttons=buttons_list,
                    )
            return [FollowupAction("action_top_menu_nlu")]
           

        buttons = []
        for childid in child_button_id:
            button_obj = read_obj(childid)
            button_label = button_obj.get("label")
            payload = {
                "buttonid": childid,
                "new_action": "action_queryredisid",
            }
            payload = json.dumps(payload)
            buttons.append(
                {"title": f"{button_label}", "payload": f"/router{payload}"}
            )
        buttons.append(
            {"title": "Back", "payload": f"/router{backbutton_payload}"}
        )
       

        for message in message_list:
            if message["type"] == "text":
                text = message["msg"]
                dispatcher.utter_message(text)
            else:
                attachment = message["msg"].rsplit("/", 1)[-1]

                logger.info(f"attachment is {attachment} ")
                buttons_list = []
                payload = f"{message['msg']}"
                payload = json.dumps(payload)

                buttons_list.append(
                    {"title": f"{attachment}", "payload": f"{payload}/link"}
                )
                dispatcher.utter_message(
                    text="Please click the following link",
                    buttons=buttons_list,
                )

        dispatcher.utter_message(text="Select from below", buttons=buttons)
        return []
예제 #5
0
 def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     if any(tracker.get_latest_entity_values("qu_hottel")):
         lc_hottel = get_latest_entity_values("qu_hottel")
         return [SlotSet("qu_hottel", num_room)]
예제 #6
0

@pytest.mark.parametrize(
    "slots,expected_slots",
    [
        (
            {
                SLOT_MENTION: None,
                SLOT_ATTRIBUTE: None,
                SLOT_OBJECT_TYPE: "restaurant",
                SLOT_LISTED_OBJECTS: None,
                SLOT_LAST_OBJECT: None,
                SLOT_LAST_OBJECT_TYPE: None,
            },
            [
                SlotSet(SLOT_MENTION, None),
                SlotSet(SLOT_ATTRIBUTE, None),
                SlotSet(SLOT_OBJECT_TYPE, "restaurant"),
                SlotSet(SLOT_LAST_OBJECT, None),
                SlotSet(SLOT_LAST_OBJECT_TYPE, "restaurant"),
                SlotSet(SLOT_LISTED_OBJECTS, [3, 2, 1]),
            ],
        ),
        (
            {
                SLOT_MENTION: None,
                SLOT_ATTRIBUTE: None,
                SLOT_OBJECT_TYPE: "restaurant",
                SLOT_LISTED_OBJECTS: None,
                SLOT_LAST_OBJECT: None,
                SLOT_LAST_OBJECT_TYPE: "restaurant",
예제 #7
0
def set_symptoms(symptoms_value: str, end_form_slot: str) -> List[EventType]:
    return [
        SlotSet(SYMPTOMS_SLOT, symptoms_value),
        SlotSet(SELF_ASSESS_DONE_SLOT, True),
        SlotSet(REQUESTED_SLOT, None),
    ] + end_form_additional_events(end_form_slot, ORDERED_FORM_SLOTS)
예제 #8
0
def _set_emp_details_slot(tracker, response):
    emp_details = tracker.get_slot("emp_details")
    if emp_details == None:
        return [SlotSet("emp_details", response)]
    else:
        return []
예제 #9
0
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:
        """Executes the action"""
        slots = {
            "AA_CONTINUE_FORM": None,
            "zz_confirm_form": None,
            "time": None,
            "time_formatted": None,
            "start_time": None,
            "end_time": None,
            "start_time_formatted": None,
            "end_time_formatted": None,
            "grain": None,
            "search_type": None,
            "vendor_name": None,
        }

        if tracker.get_slot("zz_confirm_form") == "yes":
            search_type = tracker.get_slot("search_type")
            deposit = search_type == "deposit"
            vendor = tracker.get_slot("vendor_name")
            vendor_name = f" at {vendor.title()}" if vendor else ""
            start_time = parser.isoparse(tracker.get_slot("start_time"))
            end_time = parser.isoparse(tracker.get_slot("end_time"))
            transactions = profile_db.search_transactions(
                tracker.sender_id,
                start_time=start_time,
                end_time=end_time,
                deposit=deposit,
                vendor=vendor,
            )

            aliased_transactions = transactions.subquery()
            total = profile_db.session.query(
                sa.func.sum(aliased_transactions.c.amount))[0][0]
            if not total:
                total = 0
            numtransacts = transactions.count()
            slotvars = {
                "total": f"{total:.2f}",
                "numtransacts": numtransacts,
                "start_time_formatted":
                tracker.get_slot("start_time_formatted"),
                "end_time_formatted": tracker.get_slot("end_time_formatted"),
                "vendor_name": vendor_name,
            }

            dispatcher.utter_message(
                response=f"utter_searching_{search_type}_transactions",
                **slotvars,
            )
            dispatcher.utter_message(
                response=f"utter_found_{search_type}_transactions", **slotvars)
        else:
            dispatcher.utter_message(
                response="utter_transaction_search_cancelled")

        return [SlotSet(slot, value) for slot, value in slots.items()]
예제 #10
0
 def run(self, dispatcher, tracker, domain):
     count = 0
     config = {"user_key": ""}  #Get your key from zomato api
     zomato = zomatopy.initialize_app(config)
     loc = tracker.get_slot('location')
     cuisine = tracker.get_slot('cuisine')
     price = tracker.get_slot('price')
     location_detail = zomato.get_location(loc, 1)
     d1 = json.loads(location_detail)
     lat = d1["location_suggestions"][0]["latitude"]
     lon = d1["location_suggestions"][0]["longitude"]
     cuisines_dict = {
         'chinese': 25,
         'italian': 55,
         'north indian': 50,
         'south indian': 85,
         'american': 1,
         'mexican': 73
     }
     price_dict = {'low': 1, 'medium': 2, 'high': 3}
     results = zomato.restaurant_search("", lat, lon,
                                        str(cuisines_dict.get(cuisine)),
                                        50000)
     d = json.loads(results)
     response = "Showing you top rated restaurants:" + "\n"
     if d['results_found'] == 0:
         response = "No restaurant found for your criteria"
         dispatcher.utter_message(response)
     else:
         for restaurant in sorted(d['restaurants'],
                                  key=lambda x: x['restaurant'][
                                      'user_rating']['aggregate_rating'],
                                  reverse=True):
             #Getting Top 10 restaurants for chatbot response
             if ((price_dict.get(price) == 1) and
                 (restaurant['restaurant']['average_cost_for_two'] < 300)
                     and (count < 10)):
                 response = response + str(count + 1) + ". " + restaurant[
                     'restaurant']['name'] + " in " + restaurant[
                         'restaurant']['location'][
                             'address'] + " has been rated " + restaurant[
                                 'restaurant']['user_rating'][
                                     'aggregate_rating'] + ""
                 response = response + ". And the average price for two people here is: " + str(
                     restaurant['restaurant']
                     ['average_cost_for_two']) + "Rs\n"
                 count = count + 1
             elif ((price_dict.get(price) == 2) and
                   (restaurant['restaurant']['average_cost_for_two'] >= 300)
                   and
                   (restaurant['restaurant']['average_cost_for_two'] <= 700)
                   and (count < 10)):
                 response = response + str(count + 1) + ". " + restaurant[
                     'restaurant']['name'] + " in " + restaurant[
                         'restaurant']['location'][
                             'address'] + " has been rated " + restaurant[
                                 'restaurant']['user_rating'][
                                     'aggregate_rating'] + ""
                 response = response + ". And the average price for two people here is: " + str(
                     restaurant['restaurant']
                     ['average_cost_for_two']) + "Rs\n"
                 count = count + 1
             elif ((price_dict.get(price) == 3) and
                   (restaurant['restaurant']['average_cost_for_two'] > 700)
                   and (count < 10)):
                 response = response + str(count + 1) + ". " + restaurant[
                     'restaurant']['name'] + " in " + restaurant[
                         'restaurant']['location'][
                             'address'] + " has been rated " + restaurant[
                                 'restaurant']['user_rating'][
                                     'aggregate_rating'] + ""
                 response = response + ". And the average price for two people here is: " + str(
                     restaurant['restaurant']
                     ['average_cost_for_two']) + "Rs\n"
                 count = count + 1
             if (count == 5):
                 dispatcher.utter_message(response)
     if (count < 5 and count > 0):
         dispatcher.utter_message(response)
     if (count == 0):
         response = "Sorry, No results found for your criteria. Would you like to search for some other restaurants?"
         dispatcher.utter_message(response)
     return [SlotSet('emailbody', response)]
예제 #11
0
파일: actions.py 프로젝트: tpusmb/chat_bot
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain):
        """
        Main method to tun the action
        :param dispatcher: (CollectingDispatcher) The dispatcher which is used to send messages back to the user.
            Use dipatcher.utter_message() or any other rasa_sdk.executor.CollectingDispatcher method.
        :param tracker: (Tracker) The state tracker for the current user. You can access slot values using tracker.
            get_slot(slot_name), the most recent user message is tracker.
            latest_message.text and any other rasa_sdk.Tracker property.
        :param domain: (Dict[Text, Any]) – the bot’s domain
        :return: (List[Dict[Text, Any]]) All the action that the bot need to do
        """
        current_intent, nb_call = get_current_intent(tracker, self.name())
        if current_intent is None:
            error_txt = "Error intern: current intent search for {}!".format(
                self.name())
            PYTHON_LOGGER.error(error_txt)
            dispatcher.utter_message(error_txt)
            return []

        api_call_json = get_action_json(tracker, self.name(), current_intent,
                                        nb_call)
        request_params = {}
        method = api_call_json["method"].lower()
        # Get the method
        call_function = requests.get
        if method == "post":
            call_function = requests.post
        elif method == "put":
            call_function = requests.put
        elif method == "delete":
            call_function = requests.delete

        # Change all tag with slot values
        api_call_json = dict_change_format_var_parser(api_call_json, tracker)

        if api_call_json["header"] != "json":
            request_params["headers"] = api_call_json["header"]
            request_params["data"] = api_call_json["body"]
        else:
            request_params["json"] = api_call_json["body"]

        try:
            res = call_function(api_call_json["url"], **request_params)
        except Exception as e:
            PYTHON_LOGGER.error("Error to call the url {}: {}".format(
                api_call_json["url"], e))
            dispatcher.utter_message(
                "ouch petit problem avec l'apelle du server")
            return []
        # Now get the response content
        try:
            content = res.json()
        except Exception:
            content = res.text
        # Return all get data
        try:
            json_res = {"status_code": res.status_code, "body": content}
            return [SlotSet(api_call_json["output_var_name"], json_res)]
        except Exception as e:
            PYTHON_LOGGER.error("Error to set the slot: {}".format(e))
            return []
예제 #12
0
 def required_slots(tracker: Tracker) -> List[Text]:
     SlotSet(key='state', value='return_book')
     return ["book_name", "user_name"]
예제 #13
0
    def run(self, dispatcher, tracker, domain):
        problem = tracker.latest_message.get("text")

        return [SlotSet("problem_description", problem)]
예제 #14
0
 def run(self, dispatcher, tracker, domain):
     # if we dont know the part of nlu the user wants information on,
     # store his last message in a slot.
     return [SlotSet("unknown_nlu_part", tracker.latest_message.get("text"))]
    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        print()
        print("====Inside ActionAskCuisine====")
        print()
        location=tracker.get_slot("location")
        cuisine=tracker.get_slot("cuisine")
        lat=tracker.get_slot("latitude")
        lon=tracker.get_slot("longitude")
        
        locationEntity=next(tracker.get_latest_entity_values("location"), None)
        cuisineEntity=next(tracker.get_latest_entity_values("cuisine"), None)
        user_locationEntity=next(tracker.get_latest_entity_values("user_location"), None)
        latEntity=next(tracker.get_latest_entity_values("latitude"), None)
        lonEntity=next(tracker.get_latest_entity_values("longitude"), None)

        location=tracker.get_slot("location")
        cuisine=tracker.get_slot("cuisine")
        lat=tracker.get_slot("latitude")
        lon=tracker.get_slot("longitude")
        entity_id=tracker.get_slot("location_id")
        entity_type=tracker.get_slot("location_type")
        city_id=tracker.get_slot("city_id")

       
        if(latEntity and lonEntity):
            lat=latEntity
            lon=lonEntity

        if(user_locationEntity or (latEntity and lonEntity) ):
            if(lat==None and lon==None):
                dispatcher.utter_message("Sure, please allow me to access your location 🧐")
                dispatcher.utter_custom_json({"payload":"location"})
                return []
            else:
                locationEntities=zomatoApi.getLocationDetailsbyCoordinates(lat,lon)
                location=locationEntities["title"]
                city_id=locationEntities["city_id"]
                entity_id=locationEntities["entity_id"]
                entity_type=locationEntities["entity_type"]

                SlotSet("location", locationEntities["title"])
                SlotSet("city_id", locationEntities["city_id"])
                SlotSet("location_id", locationEntities["entity_id"])
                SlotSet("location_type", locationEntities["entity_type"])


        if(locationEntity):
            locationEntities=zomatoApi.getLocationDetailsbyName(locationEntity)
            entity_id=locationEntities["entity_id"]
            entity_type=locationEntities["entity_type"]
            city_id=locationEntities["city_id"]
            SlotSet("location", locationEntities["title"])

        
        print("locationDetails: ",locationEntities)
        print()

        ## check if the restaurants are available in the user provided location
        if(locationEntities["restaurants_available"]=="no"):
            dispatcher.utter_message("Sorry, No restaurants available in the location you have  provided 🤯")
            return [UserUtteranceReverted()] 

        else:
            locationDetails=zomatoApi.getLocationDetails(locationEntities["entity_id"],locationEntities["entity_type"])

            dispatcher.utter_template("utter_ask_cuisine", tracker)
            dispatcher.utter_custom_json({"payload":"quickReplies","data":locationDetails["top_cuisines"]})
        
            return [SlotSet("city_id", locationEntities["city_id"]),SlotSet("location_id", locationEntities["entity_id"]),SlotSet("location_type", locationEntities["entity_type"])]
예제 #16
0
    async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                  domain: Dict) -> List[EventType]:
        """Executes the custom action"""
        account_type = tracker.get_slot("account_type")

        if account_type == "credit":
            # show credit card balance
            credit_card = tracker.get_slot("credit_card")
            available_cards = profile_db.list_credit_cards(tracker.sender_id)

            if credit_card and credit_card.lower() in available_cards:
                current_balance = profile_db.get_credit_card_balance(
                    tracker.sender_id, credit_card)
                dispatcher.utter_message(
                    response="utter_credit_card_balance",
                    **{
                        "credit_card": credit_card.title(),
                        "credit_card_balance": f"{current_balance:.2f}",
                    },
                )
            else:
                for credit_card in profile_db.list_credit_cards(
                        tracker.sender_id):
                    current_balance = profile_db.get_credit_card_balance(
                        tracker.sender_id, credit_card)
                    dispatcher.utter_message(
                        response="utter_credit_card_balance",
                        **{
                            "credit_card": credit_card.title(),
                            "credit_card_balance": f"{current_balance:.2f}",
                        },
                    )
        else:
            # show bank account balance
            account_balance = profile_db.get_account_balance(tracker.sender_id)
            amount = tracker.get_slot("amount_transferred")
            if amount:
                amount = float(tracker.get_slot("amount_transferred"))
                init_account_balance = account_balance + amount
                dispatcher.utter_message(
                    response="utter_changed_account_balance",
                    init_account_balance=f"{init_account_balance:.2f}",
                    account_balance=f"{account_balance:.2f}",
                )
            else:
                dispatcher.utter_message(
                    response="utter_account_balance",
                    init_account_balance=f"{account_balance:.2f}",
                )

        events = []
        active_form_name = tracker.active_form.get("name")
        if active_form_name:
            # keep the tracker clean for the predictions with form switch stories
            events.append(UserUtteranceReverted())
            # trigger utter_ask_{form}_AA_CONTINUE_FORM, by making it the requested_slot
            events.append(SlotSet("AA_CONTINUE_FORM", None))
            # avoid that bot goes in listen mode after UserUtteranceReverted
            events.append(FollowupAction(active_form_name))

        return events
    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        print()
        print("====Inside ActionSearchRestaurants====")
        print()

        ## extract the required slots
        location=tracker.get_slot("location")
        cuisine=tracker.get_slot("cuisine")
        lat=tracker.get_slot("latitude")
        lon=tracker.get_slot("longitude")
        entity_id=tracker.get_slot("location_id")
        entity_type=tracker.get_slot("location_type")
        city_id=tracker.get_slot("city_id")

        ## extract the entities
        locationEntity=next(tracker.get_latest_entity_values("location"), None)
        cuisineEntity=next(tracker.get_latest_entity_values("cuisine"), None)
        user_locationEntity=next(tracker.get_latest_entity_values("user_location"), None)
        latEntity=next(tracker.get_latest_entity_values("latitude"), None)
        lonEntity=next(tracker.get_latest_entity_values("longitude"), None)

        ## if we latitude & longitude entities are found, set it to slot
        if(latEntity and lonEntity):
            lat=latEntity
            lon=lonEntity
        
        ## if user wants to search restaurants in his current location
        if(user_locationEntity or (latEntity and lonEntity) ):
            ##check if we already have the user location coordinates stoed in slots
            if(lat==None and lon==None):
                dispatcher.utter_message("Sure, please allow me to access your location 🧐")
                dispatcher.utter_custom_json({"payload":"location"})
                return []
            else:
                locationEntities=zomatoApi.getLocationDetailsbyCoordinates(lat,lon)
                location=locationEntities["title"]
                city_id=locationEntities["city_id"]
                entity_id=locationEntities["entity_id"]
                entity_type=locationEntities["entity_type"]
                
                ## store the user provided details to slot
                SlotSet("location", locationEntities["title"])
                SlotSet("city_id", locationEntities["city_id"])
                SlotSet("location_id", locationEntities["entity_id"])
                SlotSet("location_type", locationEntities["entity_type"])

        ## if user wants to search restaurants by location name
        if(locationEntity):
            locationEntities=zomatoApi.getLocationDetailsbyName(locationEntity)
            if(locationEntities["restaurants_available"]=="no"):
                dispatcher.utter_message("Sorry I couldn't find any restaurants  😓")
                return []
            entity_id=locationEntities["entity_id"]
            entity_type=locationEntities["entity_type"]
            city_id=locationEntities["city_id"]
            SlotSet("location", locationEntities["title"])

        ##get the cuisine id for the cuisine name user provided
        cuisine_id=zomatoApi.getCuisineId(cuisine,city_id)
        
        print("Entities:  ",entity_id," ",entity_type," ",cuisine_id," ",location," ",cuisine)
        print()

        ## if we didn't find the restaurant for which user has provided the cuisine name
        if(cuisine_id==None):
            dispatcher.utter_message("Sorry we couldn't find any restaurants that serves {} cuisine in {}".format(cuisine,location))
            return [UserUtteranceReverted()] 
        else:
            ## search the restaurts by calling zomatoApi api
            restaurants=zomatoApi.searchRestaurants(entity_id,entity_type, cuisine_id,"")

            ## check if restaurants found
            if(len(restaurants)>0):
                dispatcher.utter_message("Here are the few restaurants that matches your preferences 😋")
                dispatcher.utter_custom_json({"payload":"cardsCarousel","data":restaurants})
                return []
                
            dispatcher.utter_message("Sorry we couldn't find any restaurants that serves {} cuisine in {} 😞".format(cuisine,location))
            return [UserUtteranceReverted()] 
예제 #18
0
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        username = tracker.get_slot("username")
        email = tracker.get_slot("email-address")
        phone = tracker.get_slot("phone-number")

        smtp_server = "syberzen.com"
        port = 465
        sender_email = "*****@*****.**"
        receiver_email = "*****@*****.**"
<<<<<<< HEAD
        password = "******"
=======
        password = input("Please enter password")
>>>>>>> 1ff679a1051e00974f27b6b8e66eaabee4f9147f

        message = f"this message is sent from chatbot {username}, {email}, {phone}"    

        # create secure ssl context
        context = ssl.create_default_context()

        # try to login server
        with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, message)

        dispatcher.utter_message(text="Soon we will contact you")

        return [SlotSet(username, None),
                SlotSet(email, None),
                SlotSet(phone, None)]
예제 #19
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        calendar_auth()

        task_type = tracker.get_slot("task_type")

        print(task_type)

        if (task_type == 'create'):
            summary = tracker.get_slot("summary")
            startdatetime = tracker.get_slot("time")

            #            start = startdatetime.split(',')[0]+"T"+startdatetime.split(',')[1]+":00"
            #            if(int(startdatetime.split(',')[1].split(':')[1])>30):
            #                end = startdatetime.split(',')[0]+"T"+str(int(startdatetime.split(',')[1].split(':')[0])+1)+":"+str(int(startdatetime.split(',')[1].split(':')[1])-30)+":00"
            #            elif(int(startdatetime.split(',')[1].split(':')[1])==30):
            #                end = startdatetime.split(',')[0]+"T"+str(int(startdatetime.split(',')[1].split(':')[0])+1)+":"+str(int(startdatetime.split(',')[1].split(':')[1])-30)+":00"
            #            else:
            #                end = startdatetime.split(',')[0]+"T"+startdatetime.split(',')[1].split(':')[0]+":"+str(int(startdatetime.split(',')[1].split(':')[1])+30)+":00"
            email_attendees = tracker.get_slot("email_attendees")

            start = startdatetime  # leave it as a string
            #            end = json.dumps((dateutil.parser.parse(startdatetime) + timedelta(minutes=30)),indent=4, sort_keys=True, default=str)
            #           end = convert startdatetime to datetime object, add 30 min, then convert everything back into serializable JSON
            end = (dateutil.parser.parse(startdatetime) +
                   timedelta(minutes=30)).isoformat()

            print(summary)
            print(start)
            print(end)
            L = list(map(str, email_attendees.split(', ')))
            attendees_list = []
            for attendee in L:
                attendees_list.append({'email': attendee})
            print(attendees_list)

            if (summary == 'null' or summary == 'none'):
                summary = email_attendees

            event = {
                'summary': summary,
                'start': {
                    'dateTime': start,
                    'timeZone': 'Asia/Kolkata',
                },
                'end': {
                    'dateTime': end,
                    'timeZone': 'Asia/Kolkata',
                },
                'attendees': attendees_list,
                'reminders': {
                    'useDefault':
                    False,
                    'overrides': [
                        {
                            'method': 'email',
                            'minutes': 24 * 60
                        },
                        {
                            'method': 'popup',
                            'minutes': 10
                        },
                    ],
                },
            }

            event = service.events().insert(calendarId='primary',
                                            sendUpdates='all',
                                            body=event).execute()
            print('Event created: %s' % (event.get('htmlLink')))

            # Change the rasa default time settings to 500 instead of 10 as in link https://forum.rasa.com/t/error-asyncio-task-exception-was-never-retrieve/15511/7

            dispatcher.utter_message(
                "Your Event is successfully created of summary {} at time {}".
                format(summary, startdatetime))

            return []

        if (task_type == 'delete'):
            #            mail = tracker.get_slot("mail")
            mail = tracker.get_slot("email_attendees")
            print(mail)
            print('In delete function')

            var = 0
            id_list = []
            temp = False
            id = ''
            event_deleted = None
            page_token = None
            while True:
                events = service.events().list(calendarId='primary',
                                               pageToken=page_token).execute()
                for event in events['items']:
                    if 'attendees' in event:
                        for attendee in event['attendees']:
                            # print(attendee['email'], mail)
                            if (attendee['email'] == mail):
                                temp = True
                    if (temp):
                        temp = False
                        var += 1
                        id_list.append(event['id'])
                        print(var, event['summary'])
                if var > 0:
                    event_del = int(
                        input(
                            "Enter the serial number of the Event you wish to delete : "
                        ))
                    id = id_list[event_del - 1]
                page_token = events.get('nextPageToken')
                if not page_token:
                    break

            if var > 0:
                event_deleted = service.events().get(calendarId='primary',
                                                     eventId=id).execute()
                service.events().delete(calendarId='primary',
                                        eventId=id).execute()
                dispatcher.utter_message(
                    "Your Event {} is successfully deleted".format(
                        event_deleted))
            else:
                print("No events to display.")
                dispatcher.utter_message("No events to display")

            return [SlotSet("event_deleted", event_deleted)]

        if (task_type == 'list'):
            page_token = None
            while True:
                events = service.events().list(calendarId='primary',
                                               pageToken=page_token).execute()
                if not events['items']:
                    print("No events to display")
                    dispatcher.utter_message("No events to display")
                else:
                    for event in events['items']:
                        print(event)
                page_token = events.get('nextPageToken')
                if not page_token:
                    break

            return []

        if (task_type == 'free slots'):
            start = tracker.get_slot("start")
            end = tracker.get_slot("end")

            if (start == 'none'):
                end_year = int(end.split('-')[0])
                end_month = int(end.split('-')[1])
                end_date = int(end.split('-')[2])
                if (end_date == 1):
                    if (end_month == 1):
                        start_year = end_year - 1
                        start_month = 12
                        start_date = 31
                    elif (end_month == 5 or end_month == 7 or end_month == 8
                          or end_month == 10 or end_month == 12):
                        start_year = end_year
                        start_month = end_month - 1
                        start_date = 30
                    elif (end_month == 2 or end_month == 4 or end_month == 6
                          or end_month == 9 or end_month == 11):
                        start_year = end_year
                        start_month = end_month - 1
                        start_date = 31
                    elif (end_month == 3):
                        if (end_year % 4 == 0):
                            start_year = end_year
                            start_month = 2
                            start_date = 29
                        else:
                            start_year = end_year
                            start_month = 2
                            start_date = 28
                else:
                    start_year = end_year
                    start_month = end_month
                    start_date = end_date - 1
            elif (end == 'none'):
                start_year = int(start.split('-')[0])
                start_month = int(start.split('-')[1])
                start_date = int(start.split('-')[2])
                if (start_month == 2):
                    if (start_year % 4 == 0 and start_date == 29):
                        end_year = start_year
                        end_month = 3
                        end_date = 1
                    elif (start_date == 28):
                        end_year = start_year
                        end_month = 3
                        end_date = 1
                    else:
                        end_year = start_year
                        end_month = 2
                        end_date = start_date + 1
                elif (start_date == 31):
                    if (start_month == 12):
                        end_year = start_year + 1
                        end_month = 1
                        end_date = 1
                    elif (start_month == 1 or start_month == 3
                          or start_month == 5 or start_month == 7
                          or start_month == 8 or start_month == 10):
                        end_year = start_year
                        end_month = start_month + 1
                        end_date = 1
                elif (start_date == 30):
                    if (start_month == 4 or start_month == 6
                            or start_month == 9 or start_month == 11):
                        end_year = start_year
                        end_month = start_month + 1
                        end_date = 1
                else:
                    end_year = start_year
                    end_month = start_month
                    end_date = start_date + 1
            else:
                end_year = int(end.split('-')[0])
                end_month = int(end.split('-')[1])
                end_date = int(end.split('-')[2])
                start_year = int(start.split('-')[0])
                start_month = int(start.split('-')[1])
                start_date = int(start.split('-')[2])

            startdatetime = str(start_year) + "-" + str(
                start_month) + "-" + str(start_date) + "T" + "08:00:00+05:30"
            enddatetime = str(end_year) + "-" + str(end_month) + "-" + str(
                end_date) + "T" + "20:00:00+05:30"

            print(startdatetime)
            print(enddatetime)

            freebusy = service.freebusy().query(
                body={
                    "timeMin": startdatetime,
                    "timeMax": enddatetime,
                    "timeZone": "+05:30",
                    "items": [{
                        "id": 'primary'
                    }]
                }).execute()

            # print(type(freebusy['calendars']['primary']['busy']))

            freeslots = []

            # interval = input("Please give the time of slot in hrs")

            def compareDates_1lt2(date1, date2):
                date1_year = int(date1.split("T")[0].split("-")[0])
                date1_month = int(date1.split("T")[0].split("-")[1])
                date1_date = int(date1.split("T")[0].split("-")[2])
                date2_year = int(date2.split("T")[0].split("-")[0])
                date2_month = int(date2.split("T")[0].split("-")[1])
                date2_date = int(date2.split("T")[0].split("-")[2])

                if (date1_year > date2_year):
                    return False
                elif (date1_year < date2_year):
                    return True
                else:
                    if (date1_month > date2_month):
                        return False
                    elif (date1_month < date2_month):
                        return True
                    else:
                        if (date1_date > date2_date):
                            return False
                        elif (date1_date <= date2_date):
                            return True

            def slotsFromEvents(start, end, busytimes):
                index = 0
                for time in busytimes:
                    if (index == 0
                            and compareDates_1lt2(start, time['start'])):
                        freeslots.append({
                            'start': start,
                            'end': time['start']
                        })
                    elif (index == 0):
                        start = time['end']
                    elif (compareDates_1lt2(busytimes[index - 1]['end'],
                                            time['start'])):
                        freeslots.append({
                            'start': busytimes[index - 1]['end'],
                            'end': time['start']
                        })
                    if (len(busytimes) == (index + 1)
                            and compareDates_1lt2(time['end'], end)):
                        freeslots.append({'start': time['end'], 'end': end})
                    index = index + 1

                if (len(busytimes) == 0):
                    freeslots.append({'start': start, 'end': end})

                # temp = {}
                # hourSlots = []
                # index1 = 0
                # for slot in freeslots:

            slotsFromEvents(startdatetime, enddatetime,
                            freebusy['calendars']['primary']['busy'])

            print(freebusy['calendars']['primary']['busy'])
            print(freeslots)

            dispatcher.utter_message("The free slots are {}".format(freeslots))

            return [SlotSet("freeslots", freeslots)]

        if (task_type == 'update'):
            mail = tracker.get_slot("email_attendees")
            print(mail)
            print('In update function')

            id = tracker.get_slot("id")

            event = service.events().get(calendarId='primary',
                                         eventId=id).execute()

            summary = tracker.get_slot("summary")
            startdatetime = tracker.get_slot("startdatetime")
            start = startdatetime.split(',')[0] + "T" + startdatetime.split(
                ',')[1] + ":00"
            if (int(startdatetime.split(',')[1].split(':')[1]) > 30):
                end = startdatetime.split(',')[0] + "T" + str(
                    int(startdatetime.split(',')[1].split(':')[0]) +
                    1) + ":" + str(
                        int(startdatetime.split(',')[1].split(':')[1]) -
                        30) + ":00"
            elif (int(startdatetime.split(',')[1].split(':')[1]) == 30):
                end = startdatetime.split(',')[0] + "T" + str(
                    int(startdatetime.split(',')[1].split(':')[0]) +
                    1) + ":" + str(
                        int(startdatetime.split(',')[1].split(':')[1]) -
                        30) + ":00"
            else:
                end = startdatetime.split(',')[0] + "T" + startdatetime.split(
                    ',')[1].split(':')[0] + ":" + str(
                        int(startdatetime.split(',')[1].split(':')[1]) +
                        30) + ":00"

            email_attendees = tracker.get_slot("email_attendees")

            L = list(map(str, email_attendees.split(', ')))
            attendees_list = []
            for attendee in L:
                attendees_list.append({'email': attendee})
            print(attendees_list)

            if (summary == 'null'):
                summary = email_attendees

            event['summary'] = summary
            event['start']['dateTime'] = start
            event['end']['dateTime'] = end
            event['attendees'] = attendees_list

            updated_event = service.events().update(calendarId='primary',
                                                    eventId=event['id'],
                                                    body=event).execute()

            print('Event updated: %s' % (updated_event.get('htmlLink')))

            dispatcher.utter_message(
                "Your Event is successfully updated of summary {} at time {}".
                format(summary, startdatetime))

            return []
예제 #20
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        #the function should empty every slot, so that the user can start a new search from scratch

        genre = tracker.get_slot("genre")
        starring_name = tracker.get_slot("starring_name")
        starring_surname = tracker.get_slot("starring_surname")
        if starring_name or starring_surname:
            starring = str(starring_name) + " " + str(starring_surname)
        else:
            starring = None
        print("starring: " + str(starring))
        director_name = tracker.get_slot("director_name")
        director_surname = tracker.get_slot("director_surname")
        if director_name or director_surname:
            director = str(director_name) + " " + str(director_surname)
        else:
            director = None
        print("director: " + str(director))
        offers_already_given = tracker.get_slot("offers_already_given")

        results = _find_movies(genre, starring, director).get("results")

        if len(results) == 0:  #TODO: Gotta set existing slots perhaps huh
            dispatcher.utter_message(
                "Sorry, we could not find a movie like that")
            return [
                SlotSet("genre", None),
                SlotSet("starring_name", None),
                SlotSet("starring_surname", None),
                SlotSet("director_name", None),
                SlotSet("director_surname", None),
                SlotSet("title", None)
            ]

        num = len(results)
        movies_number = str(num)
        if num > 10:
            movies_number = "a lot of"

        # based on what movies we've already seen before,
        # let us only retrieve the first movie we run into that we haven't already offered the user
        i = 0  # movie index that helps us navigate the results (page is at max 20 results)
        movie_id = results[i]["id"]
        while (movie_id in offers_already_given) and i < 20 and i < len(
                results
        ) - 1:  #first it had: "and i<len(offers_already_given)" but I don't get why
            i += 1
            movie_id = results[i]["id"]

        if i >= len(results) - 1:  #TODO: Gotta set existing slots perhaps huh
            dispatcher.utter_message(
                "Sorry, we could not find a movie like that")
            return [
                SlotSet("genre", None),
                SlotSet("starring_name", None),
                SlotSet("starring_surname", None),
                SlotSet("director_name", None),
                SlotSet("director_surname", None),
                SlotSet("title", None)
            ]

        offers_already_given.append(
            movie_id
        )  # remember in the future that the we have offered this movie
        title = results[i][
            "title"]  # get and set (in the return) the title slot for the movie

        #TODO: check if these if statements are any useful or actually detrimental
        if genre is None:
            genre = _get_genre(str(movie_id))

        if starring is None:
            starring = _get_starring(str(movie_id))

        if director is None:
            director = _get_director(str(movie_id))

        rating = str(results[i]["vote_average"]
                     )  # get the rating for the movie and make it a string

        #dispatcher.utter_message(text="I have {} options for you. What do you think about {}? Then I have {}. Then I have {}".format(movies_number, movie_titles[0], movie_titles[1], movie_titles[2]))
        dispatcher.utter_message(
            text=
            "I have {} options for you. What do you think about {}? This movie's average rating is {}."
            .format(movies_number, title, rating))

        return [
            SlotSet("info_genre", genre),
            SlotSet("info_starring", starring),
            SlotSet("info_director", director),
            SlotSet("aggregate_rating", rating),
            SlotSet("title", title),
            SlotSet("offers_already_given", offers_already_given)
        ]
예제 #21
0
    async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                  domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        try:
            site = tracker.current_state().get('sender_id')
            # dispatcher.utter_message(text="crossword")
            slots = tracker.current_state().get('slots')

            slotsets = []
            if slots.get('crossword') and len(slots.get('crossword')) > 0:
                crossword = await get_crossword(slots.get('crossword'))
                if crossword:
                    crossword_position = self.extract_entities(
                        tracker, ['crossword_position'])
                    word = self.extract_entities(tracker, [
                        'word',
                        'thing',
                        'person',
                        'place',
                    ])
                    if crossword_position:
                        just_number = None
                        clean_number = crossword_position.replace(
                            'across', '').replace('down', '')
                        parts = clean_number.split(' ')
                        clean_number = parts[0]
                        # integer from text
                        if clean_number.isdigit() > 0 and int(
                                clean_number) > 0:
                            just_number = clean_number.strip()
                        # convert number from text
                        else:
                            try:
                                just_number = w2n.word_to_num(clean_number)
                            except:
                                pass
                        # print(just_number)
                        direction = None
                        if "across" in crossword_position:
                            direction = "across"
                        elif "down" in crossword_position:
                            direction = "down"

                        if just_number:
                            if direction:
                                if word:
                                    # print(crossword.get('data',{}))
                                    answer = crossword.get('data', {}).get(
                                        direction,
                                        {}).get(str(just_number)).get(
                                            'answer',
                                            '').lower().strip().replace(
                                                ' ', '')
                                    # print([word,answer])
                                    if word.lower().strip().replace(
                                            ' ', '') == answer:
                                        dispatcher.utter_message(
                                            text="Correct")
                                        # print(['  CROSSWORD   ',answer,crossword_position,just_number,word])
                                        await publish(
                                            'hermod/' + site +
                                            '/crossword/fill', {
                                                'direction':
                                                direction,
                                                "word":
                                                word.strip().replace(' ', ''),
                                                "number":
                                                just_number
                                            })
                                        slotsets.append(
                                            SlotSet("hermod_force_continue",
                                                    None))
                                        slotsets.append(
                                            SlotSet("hermod_force_end",
                                                    "true"))

                                    else:
                                        dispatcher.utter_message(
                                            text="Nope, try again")
                                        slotsets.append(
                                            SlotSet("hermod_force_continue",
                                                    None))
                                        slotsets.append(
                                            SlotSet("hermod_force_end",
                                                    "true"))
                                        await publish(
                                            'hermod/' + site + '/display/show',
                                            {
                                                'question':
                                                just_number + ' ' + direction +
                                                ' is '
                                            })
                                else:
                                    dispatcher.utter_message(
                                        text=
                                        "I didn't hear the word you wanted to fill"
                                    )
                                    slotsets.append(
                                        SlotSet("hermod_force_continue", None))
                                    slotsets.append(
                                        SlotSet("hermod_force_end", "true"))
                                    await publish(
                                        'hermod/' + site + '/display/show', {
                                            'question':
                                            just_number + ' ' + direction +
                                            ' is '
                                        })
                            else:
                                dispatcher.utter_message(
                                    text=
                                    "I didn't hear which direction you wanted to fill"
                                )
                                slotsets.append(
                                    SlotSet("hermod_force_continue", None))
                                slotsets.append(
                                    SlotSet("hermod_force_end", "true"))
                                await publish(
                                    'hermod/' + site + '/display/show',
                                    {'question': crossword_position})
                        else:
                            dispatcher.utter_message(
                                text=
                                "I didn't hear the number you wanted to fill")
                            slotsets.append(
                                SlotSet("hermod_force_continue", None))
                            slotsets.append(SlotSet("hermod_force_end",
                                                    "true"))
                            await publish('hermod/' + site + '/display/show',
                                          {'question': crossword_position})
                    else:
                        dispatcher.utter_message(
                            text="I didn't hear the position you wanted to fill"
                        )
                        slotsets.append(SlotSet("hermod_force_continue", None))
                        slotsets.append(SlotSet("hermod_force_end", "true"))
                        await publish('hermod/' + site + '/display/show',
                                      {'question': crossword_position})

            #hermod/+/crossword/fill
        except Exception as e:
            print('ERROR')
            print(e)
        return slotsets
예제 #22
0
 def run(self, dispatcher, tracker, domain):
     return [SlotSet("filedesc", None)]
예제 #23
0
 def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
     return [SlotSet("sure", "no")]
예제 #24
0
    def run(self, dispatcher, tracker, domain):
        # Zomato API Config
        config = {"user_key": os.getenv("ZOMATO_API_KEY")}
        zomato = zomatopy.initialize_app(config)

        # Loading data from slots
        loc = tracker.get_slot("location")
        cuisine = tracker.get_slot("cuisine")
        budget = tracker.get_slot("budget")

        # Processing the data obtained
        location_detail = zomato.get_location(loc, 1)
        d1 = json.loads(location_detail)
        lat = d1["location_suggestions"][0]["latitude"]
        lon = d1["location_suggestions"][0]["longitude"]
        cuisines_dict = {
            "american": 1,
            "chinese": 25,
            "north indian": 50,
            "italian": 55,
            "mexican": 73,
            "south indian": 85,
        }

        # Querying Restaurants using Zomato API
        results = zomato.restaurant_search("",
                                           lat,
                                           lon,
                                           str(cuisines_dict.get(cuisine)),
                                           limit=30)

        d = json.loads(results)
        if d["results_found"] == 0:
            response = "No Results"
            dispatcher.utter_message("-----" + response)
            return []

        # Formatting, Sorting (by rating) and Saving the Restaurant
        # data obtained to a file for data propogation to different intent
        restaurants = restaurant_formatter_sorter(
            zomato.filter_restaurants_by_budget(budget, d["restaurants"]))

        # Save only top 10 restaurants to the file because current requirement states
        # to send top 10 restaurants to customer via email, thus improving efficiency
        file_path = "data/restaurants/restaurants-{}.json".format(
            datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
        open(file_path, "w").write(json.dumps(restaurants[:10]))

        # Printing top 5 restaurants
        response = "\nRestaurant List\n\n"
        for restaurant in restaurants[:5]:
            response += "{} in {} has been rated {} with an average cost for two being {}\n\n".format(
                restaurant["name"],
                restaurant["address"],
                restaurant["rating"],
                restaurant["cost_for_two"],
            )

        dispatcher.utter_message(response)

        # Returning back the newly added data `restaurants_file`
        return [SlotSet("restaurants_file", file_path.split("/")[2])]
예제 #25
0
    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        place = tracker.get_slot("location")
        lst = ["Library", "parking", "gym"]
        button = []

        # print(place)
        imgs = {"library": "https://www.ritindia.edu/images/library/slide1.jpg",
                "old": "https://images.static-collegedunia.com/public/college_data/images/appImage"
                       "/1589608290Annotation20200516112058.jpg",
                "new": "https://images.static-collegedunia.com/public/college_data/images/campusimage/15894830191"
                       "%20Main%20Building%20No%202.jpg",
                "electrical": "https://img.collegedekhocdn.com/media/img/institute/crawled_images/RIT_Buid_.jpg?tr=h"
                              "-400,w-650",
                "mech": "https://www.myfirstcollege.com/wp-content/uploads/2019/04/BUILDING-RAJARAM.jpg",
                "canteen": "https://www.ritindia.edu/images/library/slide13.jpg",
                "default": "https://rotse2020.com/wp-content/uploads/2019/12/P1870243-1-scaled.jpg"}

        if place == None:
            test_carousel = {
                "type": "template",
                "payload": {
                    "template_type": "generic",
                    "elements": [{
                        "title": "Library",
                        "subtitle": "",
                        "image_url": imgs["library"],
                        "buttons": [{
                            "title": "view on map",
                            "url": "https://plus.codes/7J9P377J+6V",
                            "type": "web_url"
                        }
                        ]
                    },
                        {
                            "title": "IT department",
                            "subtitle": "",
                            "image_url": imgs["old"],
                            "buttons": [{
                                "title": "view on map",
                                "url": "https://plus.codes/7J9P377M+H6",
                                "type": "web_url"
                            }
                            ]
                        },
                        {
                            "title": "CSE department",
                            "subtitle": "Subtitle",
                            "image_url": imgs["new"],
                            "buttons": [{
                                "title": "Link name",
                                "url": "https://plus.codes/7J9P377J+7W",
                                "type": "web_url"
                            }
                            ]
                        }
                    ]
                }
            }
            dispatcher.utter_message(attachment=test_carousel)

        #     for i in lst:
        #         payload = "/location_inquiry{\"location\":\"" + i + "\"}"
        #         button.append({"title": i, "payload": payload})
        #     dispatcher.utter_message(text="Select from following or Enter another", buttons=button)
        else:
            try:
                place = place.upper()
            except Exception:
                place = ""
            dict = {"IL": "7J9P377M+J7", "CIVI": "7J9P377M+H6", "IT": "7J9P377M+H6", "MECH": "7J9P377M+R6",
                    "AUTO": "7J9P377M+Q7",
                    "ELE": "7J9P377J+HW", "ETC": "7J9P377J+7W", "CSE": "7J9P377J+7W", "GYM": "7J9P377J+HQ",
                    "LIBRA": "7J9P377J+6V",
                    "OFC": "7J9P377M+F3", "PARK": ["7J9P377J+VM", "7J9P377J+5J"]}
            key = ""
            image = imgs["default"]
            if re.findall("^IL", place):
                key = "IL"
                url = "https://plus.codes/" + dict[key]
                image = imgs["old"]
            elif re.findall("^IT|INFORM", place):
                key = "IT"
                url = "https://plus.codes/" + dict[key]
                image = imgs["old"]
            elif re.findall("^CIV", place):
                key = "CIVI"
                url = "https://plus.codes/" + dict[key]
                image = imgs["old"]
            elif re.findall("^MECH", place):
                key = "MECH"
                url = "https://plus.codes/" + dict[key]
                image = imgs["mech"]
            elif re.findall("^AUTO", place):
                key = "AUTO"
                url = "https://plus.codes/" + dict[key]
                image = imgs["mech"]
            elif re.findall("^COM|CSE|CS DEPARTMENT", place):
                key = "CSE"
                url = "https://plus.codes/" + dict[key]
                image = imgs["new"]
            elif re.findall("^ELECTRI", place):
                key = "ELE"
                url = "https://plus.codes/" + dict[key]
                image = imgs["electrical"]
            elif re.findall("^ETC|E&TC|ELECRO", place):
                key = "ETC"
                url = "https://plus.codes/" + dict[key]
                image = imgs["new"]
            elif re.findall("^GYM|WORKOUT|WORK OUT", place):
                key = "GYM"
                url = "https://plus.codes/" + dict[key]
            elif re.findall("^LIBRARY", place):
                key = "LIBRA"
                url = "https://plus.codes/" + dict[key]
                image = imgs["library"]
            elif re.findall("^OFFICE|PRICI|DEAN", place):
                key = "OFC"
                url = "https://plus.codes/" + dict[key]
                image = imgs["old"]
            elif re.findall("^PARKING", place):
                key = "PARK"
                student = tracker.get_slot("student")
                if student != None:
                    student = student.upper()
                index = 0

                if student == "HOSTELER":
                    index = 0
                    # return []

                else:
                    index = 1
                url = "https://plus.codes/" + dict[key][index]

            else:
                url = None
            test_carousel = {
                "type": "template",

                "payload": {
                    "template_type": "generic",
                    "elements": [{
                        "title": place,
                        "subtitle": "this is very bewtifull and i cNT HANDLE IT ANY MORE LSJDKF ALJDHFA LNKFHKAJLMKF AHDJFAK SJDKFHKJALNFJMNLDNFFKB HKFKAHKNLFK",
                        "image_url": image,
                        "buttons": [{
                            "title": "view on map",
                            "url": url,
                            "type": "web_url"
                        }]
                    }]
                }
            }
            dispatcher.utter_message(attachment=test_carousel)
        # dispatcher.utter_message(image="https://cdn.rit.edu/images/news/2019-09/GlobalPlaza.jpg", text=url)

        return [SlotSet("student", None), SlotSet("location", None)]
예제 #26
0
 def run(self, dispatcher, tracker, domain):
     location = tracker.get_slot("location")
     location_list = open("./data/valid_cities.txt").read().split("\n")
     if location not in location_list:
         dispatcher.utter_message(template="utter_locationNotServiced")
         return [SlotSet("location", None)]
예제 #27
0
async def test_validate_if_required():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {
            "entities": [
                {"entity": "some_slot", "value": "some_value"},
                {"entity": "some_other_slot", "value": "some_other_value"},
            ]
        },
        [],
        False,
        None,
        {"name": "some_form", "validate": True, "rejected": False},
        "action_listen",
    )

    events = await form._validate_if_required(CollectingDispatcher(), tracker, {})
    # check that validation was performed
    assert events == [
        SlotSet("some_other_slot", "some_other_value"),
        SlotSet("some_slot", "some_value"),
    ] or events == [
        SlotSet("some_slot", "some_value"),
        SlotSet("some_other_slot", "some_other_value"),
    ]

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {
            "entities": [
                {"entity": "some_slot", "value": "some_value"},
                {"entity": "some_other_slot", "value": "some_other_value"},
            ]
        },
        [],
        False,
        None,
        {"name": "some_form", "validate": False, "rejected": False},
        "action_listen",
    )

    events = await form._validate_if_required(CollectingDispatcher(), tracker, {})
    # check that validation was skipped because 'validate': False
    assert events == []

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {
            "entities": [
                {"entity": "some_slot", "value": "some_value"},
                {"entity": "some_other_slot", "value": "some_other_value"},
            ]
        },
        [],
        False,
        None,
        {"name": "some_form", "validate": True, "rejected": False},
        "some_form",
    )

    events = await form._validate_if_required(CollectingDispatcher(), tracker, {})

    # check that validation was skipped
    # because previous action is not action_listen
    assert events == []
    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        print()
        print("======Inside Action Search Best Restaurants====")
        print()

        ## extract the required slots
        location=tracker.get_slot("location")
        cuisine=tracker.get_slot("cuisine")
        lat=tracker.get_slot("latitude")
        lon=tracker.get_slot("longitude")
        entity_id=tracker.get_slot("location_id")
        entity_type=tracker.get_slot("location_type")
        city_id=tracker.get_slot("city_id")

        ## extract the entities
        locationEntity=next(tracker.get_latest_entity_values("location"), None)
        cuisineEntity=next(tracker.get_latest_entity_values("cuisine"), None)
        user_locationEntity=next(tracker.get_latest_entity_values("user_location"), None)
        latEntity=next(tracker.get_latest_entity_values("latitude"), None)
        lonEntity=next(tracker.get_latest_entity_values("longitude"), None)

        ## if we latitude & longitude entities are found, set it to slot
        if(latEntity and lonEntity):
            lat=latEntity
            lon=lonEntity

        ## if user wants to search the best restaurants in his current location
        if(user_locationEntity or (latEntity and lonEntity) ):
            ##check if we already have the user location coordinates stoed in slots
            if(lat==None and lon==None):
                dispatcher.utter_message("Sure, please allow me to access your location 🧐")
                dispatcher.utter_custom_json({"payload":"location"})
                return []
            else:
                locationEntities=zomatoApi.getLocationDetailsbyCoordinates(lat,lon)
                location=locationEntities["title"]
                city_id=locationEntities["city_id"]
                entity_id=locationEntities["entity_id"]
                entity_type=locationEntities["entity_type"]
                
                ## store the user provided details to slot
                SlotSet("location", locationEntities["title"])
                SlotSet("city_id", locationEntities["city_id"])
                SlotSet("location_id", locationEntities["entity_id"])
                SlotSet("location_type", locationEntities["entity_type"])

        ## if user wants to search best restaurants by location name
        if(locationEntity):
            locationEntities=zomatoApi.getLocationDetailsbyName(locationEntity)
            entity_id=locationEntities["entity_id"]
            entity_type=locationEntities["entity_type"]
            city_id=locationEntities["city_id"]

        print("Entities: ",entity_id," ",entity_type," ",city_id," ",locationEntity)
        
        ## search the best restaurts by calling zomatoApi api
        restaurants=zomatoApi.getLocationDetails(entity_id,entity_type)
        
        ## check if restaurants details found
        if(len(restaurants)>0):
                dispatcher.utter_message("Here are few top rated restaurants that I have found 🤩")
                dispatcher.utter_custom_json({"payload":"cardsCarousel","data":restaurants["best_restaurants"]})
                return []
                
        dispatcher.utter_message("Sorry we couldn't find any best restaurants ☹️".format(cuisine,location))
        return [UserUtteranceReverted()]
예제 #29
0
    async def submit(self, dispatcher, tracker, domain):
        # Not really necessary, just to emphasize this is async
        await asyncio.sleep(0)

        return [SlotSet("other_slot", 42)]
    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))
            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()))

        for slot, value in slot_values.items():
            global try_OTP_counts
            if slot == 'OTP':
                checking_otp = int(value)
                print("OTP : " + str(OTP),
                      "checking OTP : " + str(checking_otp))
                #print(self.is_int(value),"   ",len(value),"   ", len(value))
                if not self.is_int(value) or len(value) <= 0 or len(value) > 6:
                    dispatcher.utter_message(
                        'OTP is incorrect. Please try again ')
                    try_OTP_counts += 1
                    slot_values[slot] = None
                    if try_OTP_counts > 4:
                        #print("EXCEEDED 1")
                        dispatcher.utter_message(
                            'You have exceeded the number of tries. Try again later.'
                        )
                        slot_values[slot] = None
                        return []
                else:
                    print("IN ELSE")
                    if checking_otp == int(OTP):
                        print("MATCHED")
                        dispatcher.utter_message(
                            'Transaction completed successfully')
                        slot_values[slot] = value
                        return [
                            SlotSet(slot, value)
                            for slot, value in slot_values.items()
                        ]
                    else:
                        dispatcher.utter_message(
                            'OTP is incorrect. Please try again ')
                        try_OTP_counts += 1
                        print("Number of tries OTP " + str(try_OTP_counts))
                        if try_OTP_counts < 3:
                            slot_values[slot] = None
                        else:
                            dispatcher.utter_message(
                                'You have exceeded the number of tries .')
                            dispatcher.utter_message(
                                ' ...Transaction canceled...')
                            slot_values[slot] = "000000"

        # validation succeed, set the slots values to the extracted values
        return [SlotSet(slot, value) for slot, value in slot_values.items()]