def welcomeIntent(request):
    isUserVerified = False
    idToken = None
    dialogflow_response = pf.DialogflowResponse()
    originalDetectIntentRequest = request.get('originalDetectIntentRequest',
                                              None)
    if originalDetectIntentRequest:
        payload = originalDetectIntentRequest.get('payload', None)
        if payload:
            user = payload.get('user', None)
            if user:
                userVerificationStatus = user.get('userVerificationStatus',
                                                  "NO")
                if userVerificationStatus == "VERIFIED":
                    isUserVerified = True
                    idToken = user['idToken']
    if isUserVerified is False:
        data = "Hi! I can show you examples of helper intents. We recommend trying this sample on a phone so you can see all helper intents."
        dialogflow_response.add(pf.SimpleResponse(data, data))
    else:

        print("\nuser_details\n")
        decode_jwt_token(idToken)
        data = "Hello! welcome to CareBot. Ask your queries."
        dialogflow_response.add(pf.SimpleResponse(data, data))
    return dialogflow_response.get_final_response()
Пример #2
0
def welcomeIntent(request):
    isUserVerified = False
    idToken = None
    dialogflow_response = pf.DialogflowResponse()
    originalDetectIntentRequest = request.get('originalDetectIntentRequest',
                                              None)
    if originalDetectIntentRequest is not None:
        payload = originalDetectIntentRequest.get('payload', None)
        if payload is not None:
            user = payload.get('user', None)
            if user is not None:
                userVerificationStatus = user.get('idToken', None)
                if userVerificationStatus is not None:
                    isUserVerified = True
                    idToken = userVerificationStatus
    if isUserVerified is False:
        data = "Hi! Welcome to CareBot. To serve you better, we need access to some of your information. Do you want to proceed?"
        dialogflow_response.add(pf.SimpleResponse(data, data))
    else:

        print("\nuser_details\n")

        data = "Hello! welcome to CareBot. Ask your queries."
        dialogflow_response.add(pf.SimpleResponse(data, data))
    return dialogflow_response.get_final_response()
Пример #3
0
    def handle_intent(self, token):
        print("Handling change_appointment_to_date intent")
        parsed_query = pf.DialogflowRequest(self.query)
        to_date = parsed_query.get_parameter('to_date')[0]
        to_date = datetime.strptime(to_date.split('+')[0], "%Y-%m-%dT%H:%M:%S")
        preferred_time = parsed_query.get_parameter('preferred_time')
        preferred_time = datetime.strptime(
            preferred_time.split('+')[0], "%Y-%m-%dT%H:%M:%S")

        output_context = parsed_query.get_single_ouputcontext(
            'change_appointment')
        output_parameters = output_context.get('parameters', None)
        from_date = output_parameters['from_date'][0]
        from_date = datetime.strptime(
            from_date.split('+')[0], '%Y-%m-%dT%H:%M:%S')
        phone_number = output_parameters['phone_number']

        proc = Process(target=rpa_process,
                       args=(
                           to_date,
                           preferred_time,
                           from_date,
                           phone_number,
                           token,
                       ))
        proc.start()

        aog = pf.dialogflow_response.DialogflowResponse()
        aog.add(
            pf.SimpleResponse(
                "Your appointments will be modified successfully",
                "Your appointments will be modified successfully"))
        return aog.get_final_response()
Пример #4
0
    def handle_intent(self):
        print("Handling book_appointment intent")
        parsed_query = pf.DialogflowRequest(self.query)
        lmp_date = parsed_query.get_parameter('lmp_date')
        lmp_date = datetime.strptime(
            lmp_date.split('+')[0], '%Y-%m-%dT%H:%M:%S')

        #Generate checkup dates
        checkup_dates = []
        day_list = [
            45, 75, 105, 135, 165, 195, 210, 225, 240, 255, 262, 269, 275, 280
        ]
        for day in day_list:
            checkup = lmp_date + timedelta(days=day)
            checkup = str(checkup.day) + "/" + str(checkup.month) + "/" + str(
                checkup.year)
            checkup_dates.append(checkup)
        doctor_names = [
            'Chitra Mattar', 'Joe Stephie', 'Padmini Ramesh', 'Helen Cho'
        ]

        dates_string = '\n'.join(checkup_dates)
        dates_string = 'Checkup Dates \n' + dates_string + '\n Please choose your preferred Doctor.'

        aog = pf.dialogflow_response.DialogflowResponse()
        aog.add(
            pf.SimpleResponse(
                dates_string,
                "These are your checkup dates. Please choose your preferred Doctor."
            ))
        aog.add(pf.Suggestions(doctor_names))
        return aog.get_final_response()
Пример #5
0
def ask_for_calendar_permsision(req):
    ff_response = pf.dialogflow_response.DialogflowResponse()
    response = "https://iss-carebot.herokuapp.com/calendar/permission"
    ff_response.add(
        pf.SimpleResponse(response,
                          "Please allow access by signin using the link"))
    card = {
        "basicCard": {
            "title":
            "Give Permission",
            "formatted_text":
            "Please give google calendar permission for us to manage your calendar",
            "buttons": [{
                "title": "sign-in",
                "openUrlAction": {
                    "url":
                    "https://iss-carebot.herokuapp.com/calendar/permission"
                }
            }]
        }
    }
    ff_response.rich_response['items'].append(card)
    ff_response.google_payload['richResponse'] = ff_response.rich_response
    ff_response.add(pf.LinkOutSuggestion("Sign-in", response))
    return ff_response.get_final_response()
    def handle_intent(self, email):
        print("Handling get_future_appointments intent")
        parsed_query = pf.DialogflowRequest(self.query)
        #phone_number = parsed_query.get_parameter('phone_number')
        request_url = "https://sangam-test-website.herokuapp.com/get_future_appointments?email=" + str(
            email)

        future_appointments = requests.get(request_url)
        print('Future appointments', future_appointments.json())
        future_appointments_json = future_appointments.json()
        future_appointments_list = future_appointments_json['data']
        cards = []
        for appointment in future_appointments_list:
            tempdict = {}
            tempdict['date'] = appointment['appointment_datetime'].replace(
                'T', ',')
            tempdict['doctor_name'] = appointment['doctor_name']
            tempdict['remarks'] = appointment['symptoms']
            cards.append(tempdict)
        print('cards:', cards)
        print('card length', len(cards))
        aog = pf.dialogflow_response.DialogflowResponse()
        if len(cards) == 0:
            aog.add(
                pf.SimpleResponse(
                    "You don't have any upcoming appointments",
                    "Oops!! Looks like you don't have any upcoming appointments"
                ))
            return aog.get_final_response()

        response_message = "These are your upcoming appointments\n"
        if len(cards) > 3:
            cards = cards[0:3]
        for card in cards:
            response_message = response_message + "\n------------------------------- \nAppointment Date : " + str(
                card['date'])
            response_message = response_message + "\nDoctor : " + str(
                card['doctor_name'])
            response_message = response_message + "\nRemarks : " + str(
                card['remarks'])

        aog.add(
            pf.SimpleResponse(response_message,
                              "These are your upcoming appointments"))

        return aog.get_final_response()
 def handle_intent(self, attraction_db):
     print("Handling ActivateRecommendIntentHandler")
     aog = pf.dialogflow_response.DialogflowResponse(
         fulfillment_message="ActivateRecommendIntentHandler")
     aog.add(
         pf.SimpleResponse("activating recommend handler",
                           "activating recommend handler"))
     return aog.get_final_response()
Пример #8
0
    def handle_intent(self, attraction_db):
        print("Handling OneDayIntentHandler")

        parsed_query = pf.DialogflowRequest(self.query)
        ct = parsed_query.get_paramter('type')
        file_name = OneDayIntentHandler.types[ct] + ".txt"
        with open(file_name, "r") as fh:
            response_list = fh.readlines()
        response = "\n".join(response_list)
        aog = pf.dialogflow_response.DialogflowResponse(
            fulfillment_message=response)
        aog.add(pf.SimpleResponse(response, "Here is your One Day Itinerary."))
        return aog.get_final_response()
Пример #9
0
    def handle_intent(self, attraction_db):
        print("Handling FareIntent")
        aog = pf.dialogflow_response.DialogflowResponse(
            fulfillment_message="Fetching Fare Details")
        parsed_query = pf.DialogflowRequest(self.query)
        output_context = parsed_query.get_single_ouputcontext(
            'attractiondetailsintent-followup')
        place = parsed_query.request_data["queryResult"]["parameters"].get(
            "place-attraction", None)

        if place is None or place == "":
            parameters = output_context.get('parameters', None)
            if parameters is None:
                aog.dialogflow_response[
                    "fulfillmentText"] = "I'm Sorry ! cannot retrieve place information"
                return aog.get_final_response()
            place = parameters['place-attraction']
            if place == "":
                aog.dialogflow_response[
                    "fulfillmentText"] = "I'm Sorry ! cannot retrieve place information"
                return aog.get_final_response()

        print(f"Fare for place :{place}")
        desired_place = None
        max_index = 0
        for attraction in attraction_db:
            index = fuzz.token_set_ratio(attraction['name'], place)
            if index >= 95:
                desired_place = attraction
                break
            elif max_index < index:
                max_index = index
                desired_place = attraction
        adult_price = desired_place['pricing']['adult']
        child_price = desired_place['pricing']['child']
        if adult_price is not None and adult_price != "":
            response = "Adult price is " + adult_price
            if child_price is not None and child_price != "":
                response = response + " and the child price is " + child_price
        else:
            response = "Price Information of the place is not available"
        aog.add(
            pf.SimpleResponse(
                response, "These are the prices of " + desired_place['name']))
        # new_output_context = pf.OutputContexts(parsed_query.get_project_id(),self.request_data["session"].split('/')[-1],
        #                                            'attractiondetailsintent-followup', 3,
        #                                            {'place-attraction': place})
        # aog.add(new_output_context)
        return aog.get_final_response()
Пример #10
0
    def handle_intent(self,attraction_db):
        print("Handling ActivateRecommendIntentHandler")
        parsed_query = pf.DialogflowRequest(self.query)
        category = parsed_query.get_paramter('type')
        response = []
        for data in attraction_db:
            if data["type"] in ActivateRecommendIntentHandler.types[category]:
                response.append(data)
                if len(response) >=5:
                    break
        response_string = "Recommendation based on your selection:\n"
        for data in response:
            text = f"{data['name']}\n"
            response_string = response_string + text

        aog = pf.dialogflow_response.DialogflowResponse(fulfillment_message=response_string)
        aog.add(pf.SimpleResponse(response_string,"Here are some of the top attractions based on your preference."))
        return aog.get_final_response()
Пример #11
0
    def handle_intent(self,attraction_db):
        print("Handling Timing Intent")
        aog = pf.dialogflow_response.DialogflowResponse(fulfillment_message="Fetching Timing Details")
        parsed_query = pf.DialogflowRequest(self.query)
        output_context = parsed_query.get_single_ouputcontext('attractiondetailsintent-followup')

        place = parsed_query.request_data["queryResult"]["parameters"].get("place-attraction",None)
        if place is None or place == "":
            parameters = output_context.get('parameters',None)
            if parameters is None:
                aog.dialogflow_response["fulfillmentText"] = "I'm Sorry ! cannot retrieve place information"
                return aog.get_final_response()
            place = parameters['place-attraction']
            if place == "":
                aog.dialogflow_response["fulfillmentText"] = "I'm Sorry ! cannot retrieve place information"
                return aog.get_final_response()

        print(f"timing for place :{place}")
        desired_place = None
        max_index = 0
        for attraction in attraction_db:
            index = fuzz.token_set_ratio(attraction['name'],place)
            if index >= 95:
                desired_place = attraction
                break
            elif max_index < index:
                max_index = index
                desired_place = attraction

        hours = desired_place['businessHour']
        response = ""
        for hour in hours:
            if hour['daily'] is True:
                response = "Opening time: "+hour['openTime']+"\nClosing Time: "+hour['closeTime']
                break
            else:
                response = response + hour['day']+": \nOpening time: "+hour['openTime']+" Closing Time: "+hour['closeTime']+"\n"
        aog.add(pf.SimpleResponse(response,"These are the business hours of "+desired_place['name']))
        #
        # new_output_context = pf.OutputContexts(parsed_query.get_project_id(),self.request_data["session"].split('/')[-1],
        #                                            'attractiondetailsintent-followup', 3,
        #                                            {'place-attraction': place})
        #aog.add(new_output_context)
        return aog.get_final_response()
    def handle_intent(self, idToken):
        print("Handling Get_doctor_name intent")

        parsed_query = pf.DialogflowRequest(self.query)
        output_context = parsed_query.get_single_ouputcontext(
            'book_appointment')
        output_parameters = output_context.get('parameters', None)
        lmp_date = output_parameters['lmp_date']
        lmp_date = datetime.strptime(
            lmp_date.split('+')[0], '%Y-%m-%dT%H:%M:%S')

        #Generate checkup dates

        phone_number = output_parameters['phone_number']
        patient_name = output_parameters['patient_name']

        doctor_name = parsed_query.get_parameter('doctor_name')
        doctor_name = doctor_name['name']
        preferred_time = parsed_query.get_parameter('preferred_time')
        preferred_time = datetime.strptime(
            preferred_time.split('+')[0], '%Y-%m-%dT%H:%M:%S')

        symptoms = 'pregnancy checkup'

        email = decode_jwt_token(idToken)
        proc = Process(target=rpa_process,
                       args=(
                           lmp_date,
                           doctor_name,
                           preferred_time,
                           phone_number,
                           patient_name,
                           symptoms,
                           email,
                           get_sub_id(idToken),
                       ))
        proc.start()

        aog = pf.dialogflow_response.DialogflowResponse()
        aog.add(
            pf.SimpleResponse("Your appointments will be booked successfully",
                              "Your appointments will be booked successfully"))
        return aog.get_final_response()
Пример #13
0
 def handle_intent(self,attraction_db):
     print("Handling AttractionDetails Branch")
     print(self.query['queryText'])
     place = self.query['parameters'].get('place-attraction', None)
     desired_place = None
     max_index = 0;
     for attraction in attraction_db:
         index = fuzz.token_set_ratio(attraction['name'],place)
         if index >= 95:
             desired_place = attraction
             break
         elif max_index < index:
             max_index = index
             desired_place = attraction
     print(f'desired place is {desired_place["name"]}')
     aog = pf.dialogflow_response.DialogflowResponse()
     aog.add(pf.SimpleResponse(desired_place['description'],"Here you go!"))
     aog.add(pf.Suggestions(["Timing","Fare","Nearest MRT"]))
     return aog.get_final_response()
Пример #14
0
    def handle_intent(self, attraction_db):
        print("Handling EventFindIntentHandler")
        parsed_query = pf.DialogflowRequest(self.query)
        category = parsed_query.request_data["queryResult"]["parameters"].get(
            "type", None)

        event_data = TouristDatabase(
            url='https://tih-api.stb.gov.sg',
            key='Pptc6mXV0ZbhNihfGOpAY94pj2m8WLUm').get_search_data(
                keyword=category)
        now = datetime.now()
        response = ""
        count = 0

        for event in event_data:
            if count > 3:
                break
            start_date = datetime.strptime(event['startDate'],
                                           '%Y-%m-%dT%H:%M:%SZ')
            end_date = datetime.strptime(event['endDate'],
                                         '%Y-%m-%dT%H:%M:%SZ')
            delta = end_date - now
            print(delta.days)
            if delta.days > 1:
                count += 1
                text = f'{start_date.strftime("%d/%m")}-{end_date.strftime("%d/%m")} - {event["name"]}\n{event["description"]}\n'
                response = response + text
        if response == "":
            response = "There are no upcoming events right now!"
            ssml = response
        else:
            response = "These are some of the upcoming events.\n" + response
            ssml = "Here You Go!"

        aog = pf.dialogflow_response.DialogflowResponse(
            fulfillment_message=response)
        aog.add(pf.SimpleResponse(response, ssml))
        return aog.get_final_response()
Пример #15
0
    def handle_intent(self, token):
        print("Handling cancel_appointment intent")
        parsed_query = pf.DialogflowRequest(self.query)
        from_date = parsed_query.get_parameter('from_date')
        from_date = datetime.strptime(
            from_date.split('+')[0], '%Y-%m-%dT%H:%M:%S')
        phone_number = parsed_query.get_parameter('phone_number')

        proc = Process(target=rpa_process,
                       args=(
                           from_date,
                           phone_number,
                           token,
                       ))
        proc.start()

        aog = pf.dialogflow_response.DialogflowResponse()
        aog.add(
            pf.SimpleResponse(
                "Your appointments will be modified successfully",
                "Your appointments will be modified successfully"))

        return aog.get_final_response()
Пример #16
0
def make_default_response(response):
    ff_response = pf.dialogflow_response.DialogflowResponse()
    ff_response.add(pf.SimpleResponse(response, response))
    return ff_response.get_final_response()