Beispiel #1
0
def askPartySize(req):
    res = DialogflowResponse("How many people?")
    res.add(SimpleResponse("How many people?", "How many people?"))
    res.add(
        OutputContexts(req.get_project_id(), req.get_session_id(),
                       CONTEXT_ASK_PROGRAMME_YES, 5, req.get_parameters()))
    return res.get_final_response()
def webhook(request):
    response = ''
    if request.body:
        dialogflow_request = DialogflowRequest(request.body)

        intent_name = dialogflow_request.get_intent_displayName()
        print(intent_name)
        if 'Telephone' in intent_name:
            entity = dialogflow_request.get_parameter("Department")
            print(entity)

            result = models.Contact.objects.filter(department=entity)

            result_json = serializers.serialize('json', result)
            print(result_json)

            dialogflow_response = DialogflowResponse('telephone')
            dialogflow_response.add(SimpleResponse(result_json, result_json))

            # dialogflow_response = DialogflowResponse("This is a text response")
            # dialogflow_response.add(SimpleResponse("This is a simple text response","This is a simple text response"))

            response = dialogflow_response.get_final_response()

    else:
        response = {"error": "1", "message": "An error occurred."}

    # print('res : ' + json.dumps(response))

    return HttpResponse(response,
                        content_type='application/json; charset=utf-8')
Beispiel #3
0
def askLastName(req):
    res = DialogflowResponse("May I know your last name?(e.g Last Name:Lee)")
    res.add(
        SimpleResponse("May I know your last name?(e.g Last Name:Lee)",
                       "May I know your last name?(e.g Last Name:Lee)"))
    res.add(
        OutputContexts(req.get_project_id(), req.get_session_id(),
                       CONTEXT_ASK_PROGRAMME_YES, 5, req.get_parameters()))
    return res.get_final_response()
Beispiel #4
0
def askTime(req):
    res = DialogflowResponse("How about the time?(e.g Time:1730)")
    res.add(
        SimpleResponse("How about the time?(e.g Time:1730)",
                       "How about the time?(e.g Time:1730)"))
    res.add(
        OutputContexts(req.get_project_id(), req.get_session_id(),
                       CONTEXT_ASK_PROGRAMME_YES, 5, req.get_parameters()))
    return res.get_final_response()
Beispiel #5
0
def askPhone(req):
    res = DialogflowResponse(
        "May I know your mobile number?(e.g Phone:83927594)")
    res.add(
        SimpleResponse("May I know your mobile number?(e.g Phone:83927594)",
                       "May I know your mobile number?(e.g Phone:83927594)"))
    res.add(
        OutputContexts(req.get_project_id(), req.get_session_id(),
                       CONTEXT_ASK_PROGRAMME_YES, 5, req.get_parameters()))
    return res.get_final_response()
Beispiel #6
0
def askEmail(req):
    res = DialogflowResponse(
        "What is your email address?(e.g Email:[email protected])")
    res.add(
        SimpleResponse(
            "What is your email address?(e.g Email:[email protected])",
            "What is your email address?(e.g Email:[email protected])"))
    res.add(
        OutputContexts(req.get_project_id(), req.get_session_id(),
                       CONTEXT_ASK_PROGRAMME_YES, 5, req.get_parameters()))
    return res.get_final_response()
Beispiel #7
0
def askDate(req):
    res = DialogflowResponse(
        "What is the date you are looking at?(e.g Date:dd/mm/yyyy)")
    print(req.get_parameters())
    res.add(
        SimpleResponse(
            "What is the date you are looking at?(e.g Date:dd/mm/yyyy)",
            "What is the date you are looking at?(e.g Date:dd/mm/yyyy)"))
    res.add(
        OutputContexts(req.get_project_id(), req.get_session_id(),
                       CONTEXT_ASK_PROGRAMME_YES, 5, req.get_parameters()))
    return res.get_final_response()
Beispiel #8
0
def alternateResult(req):
    i = intelligence.Intel()
    if i.has_result():
        restaurant_name, image_url = i.get_result()
        res = DialogflowResponse("How about " + restaurant_name +
                                 ", do you want to make a reservation?")
        res.add(
            OutputContexts(req.get_project_id(), req.get_session_id(),
                           CONTEXT_ASK_PROGRAMME, 5, req.get_parameters()))
        res.fulfillment_messages.append({
            "card": {
                "title":
                "How about " + restaurant_name +
                ", do you want to make a reservation?",
                "imageUri":
                "{}/image?path={}".format(server_url, image_url[0]),
                "buttons": [{
                    "text": "yes",
                    "postback": "yes:" + restaurant_name
                }, {
                    "text": "no",
                    "postback": "no"
                }]
            },
            "platform": "SLACK"
        })
        res.fulfillment_messages.append({
            "text": {
                "text":
                ["or you can type \"Find a restaurant\" to start again"]
            },
            "platform": "SLACK"
        })

    else:
        res = DialogflowResponse(
            "Thanks! You may type \"Find a restaurant\" to get another recommendation."
        )
        res.fulfillment_messages.append({
            "text": {
                "text": [
                    "Thanks! You may type \"Find a restaurant\" to get another recommendation."
                ]
            },
            "platform": "SLACK"
        })
    print(res.get_final_response())
    return res.get_final_response()
Beispiel #9
0
def index_page():
    if request.method == 'POST':
        dialogflow_request = DialogflowRequest(request.data)
        if dialogflow_request.get_intent_displayName() == "welcome_intent":
            dialogflow_response = DialogflowResponse(
                "Welcome to my test dialogflow webhook")
            dialogflow_response.add(
                SimpleResponse("Welcome to my test dialogflow webhook",
                               "Welcome to my test dialogflow webhook"))
            response = jsonify(dialogflow_response.get_final_response())
        else:
            dialogflow_response = DialogflowResponse(
                "Now that you are here. What can I help you with ?")
            dialogflow_response.add(Suggestions(["About", "Sync",
                                                 "More info"]))
            response = jsonify(dialogflow_response.get_final_response())
        return response
    else:
        abort(404)
Beispiel #10
0
def index_page():
    if request.method == 'POST':
        dialogflow_request = DialogflowRequest(request.data)
        if dialogflow_request.get_intent_displayName() == "welcome_intent":
            dialogflow_response = DialogflowResponse(
                "Welcome to my test dialogflow webhook")
            dialogflow_response.add(
                SimpleResponse("Welcome to my test dialogflow webhook",
                               "Welcome to my test dialogflow webhook"))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
        else:
            dialogflow_response = DialogflowResponse()
            dialogflow_response.add(
                SimpleResponse("Welcome to my test dialogflow webhook",
                               "Welcome to my test dialogflow webhook"))
            dialogflow_response.add(Suggestions(["About", "Sync",
                                                 "More info"]))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
        return response
    else:
        abort(404)
def index_function(request):
    if request.method == "POST":
        if request.body:
            dialogflow_request = DialogflowRequest(request.body)
            if dialogflow_request.get_intent_displayName() == "welcome_intent":
                dialogflow_response = DialogflowResponse(
                    "Welcome to my test dialogflow webhook")
                dialogflow_response.add(
                    SimpleResponse("Welcome to my test dialogflow webhook",
                                   "Welcome to my test dialogflow webhook"))
                response = dialogflow_response.get_final_response()
            else:
                dialogflow_response = DialogflowResponse(
                    "Now that you are here. What can I help you with ?")
                dialogflow_response.add(
                    Suggestions(["About", "Sync", "More info"]))
                response = dialogflow_response.get_final_response()
        else:
            response = {"error": "1", "message": "An error occurred."}
        return HttpResponse(response,
                            content_type='application/json; charset=utf-8')
    else:
        raise Http404()
Beispiel #12
0
def webhook(request):
    dialogflow_response = DialogflowResponse()
    try:
        dialog_fulfillment = DialogflowRequest(request.data)
        action = dialog_fulfillment.get_action()
        if action == "welcome":
            dialogflow_response.add(
                SimpleResponse("This is a simple text response",
                               "This is a simple text response"))
        else:
            dialogflow_response.add(
                SimpleResponse("This is a fallback text response",
                               "This is a fallback text response"))
        # dialogflow_response.fulfillment_messages = dialog_fulfillment.request_data["queryResult"]["fulfillmentMessages"]

    except Exception as e:
        logging.error(e)
        dialogflow_response = DialogflowResponse()
        dialogflow_response.add(
            SimpleResponse("Something went wrong.", "Something went wrong."))
        return json.loads(dialogflow_response.get_final_response())

    return json.loads(dialogflow_response.get_final_response())
Beispiel #13
0
    def results(self, request):
        # build a request object
        dialogflow_request = DialogflowRequest(request.data)
        project_id = dialogflow_request.get_project_id()
        session_id = dialogflow_request.get_session_id()

        # fetch action from json
        intent_name = dialogflow_request.get_intent_displayName()
        intent_id = intent_name.replace(f"{self.namespace}_", '')

        if not intent_id:
            return {
                'error':
                f"Intent name '{intent_name}' must start with '{self.namespace}_'"
            }

        parameters = dialogflow_request.get_parameters()
        print("parameters", parameters)
        if not parameters:
            return {'error': "No parameters found in dialogflow request"}

        print("---------------------")
        print("parameters", parameters)
        slot_values = self.parameters_to_slot_values(parameters)
        print("slot_values", slot_values)

        response_template = request.get_json(
        )['queryResult']['fulfillmentText']
        print("response_template", response_template)

        payload = {
            'intent_id': intent_id,
            'slot_values': slot_values,
            'response_template': response_template
        }

        print('calling InDiE fulfillment: ', payload)

        indie_fulfillment_service_url = os.environ[
            'INDIE_FULFILLMENT_SERVICE_URL']
        res = requests.post(indie_fulfillment_service_url,
                            json=payload,
                            verify=False)
        if res.ok:
            res = res.json()

            if 'fulfillment_message' in res:
                fulfillment_message = res['fulfillment_message']
                print("Received fulfillment message", fulfillment_message)

                dialogflow_response = DialogflowResponse(fulfillment_message)
                if 'table' in res:
                    table_response = Table(
                        rows=[TableCell(row) for row in res['table']],
                        columns=['col'] * len(res['table'][0]))
                    dialogflow_response.rich_response['items'] = []
                    dialogflow_response.add(table_response)
                return json.loads(dialogflow_response.get_final_response())
            else:
                if 'error' in res:
                    return res

        return {
            'error':
            "Failed to receive response from InDiE fulfillment service"
        }
Beispiel #14
0
 def get_platform_response(self):
     dialogflow_response = DialogflowResponse()
     dialogflow_response.expect_user_response = False
     dialogflow_response.add(
         SimpleResponse(self.get_text_message(), self.get_ssml_message()))
     return dialogflow_response.get_final_response()
Beispiel #15
0
def web_hooks(request):
    dialogflow_request = DialogflowRequest(request.data)
    session_id = dialogflow_request.get_session().split("/")[-1]

    if dialogflow_request.get_intent_displayName(
    ) == "Create Appointment - User":
        _raw_user_name = dialogflow_request.get_paramter("person")
        str_raw_user_name = str(_raw_user_name)
        str_user_name = (str_raw_user_name.strip("{").strip("}").strip(
            "[").strip("]").strip(":").strip("'"))
        temp_ref.document(session_id).set({"Patient": str_user_name})
        dialogflow_response = DialogflowResponse(
            "Hi {}! Did I get your name right?".format(str_user_name))

    elif dialogflow_request.get_intent_displayName(
    ) == "Create Appointment - Phone":
        phone_number = dialogflow_request.get_paramter("phone-number")
        temp_ref.document(session_id).update({"phone_number": phone_number})
        dialogflow_response = DialogflowResponse(
            "Your phone number is {}. Is that correct?".format(phone_number))

    elif dialogflow_request.get_intent_displayName(
    ) == "Create Appointment - Purpose":
        purpose = dialogflow_request.get_paramter("purpose")
        temp_ref.document(session_id).update({"Symptoms": purpose})
        dialogflow_response = DialogflowResponse(
            "Thank you. What date would you like to make this appointment on?")

    elif dialogflow_request.get_intent_displayName(
    ) == "Create Appointment - Date":
        intend_date = dialogflow_request.get_paramter("date")
        if isinstance(intend_date, str):
            intend_date = datetime.datetime.fromisoformat(intend_date)
            intend_date = DatetimeWithNanoseconds(
                intend_date.year,
                intend_date.month,
                intend_date.day,
                intend_date.hour,
                intend_date.minute,
            )
        temp_ref.document(session_id).update({"intend_date": intend_date})
        dialogflow_response = DialogflowResponse(
            "Ok, so the date is {}. Is that right?".format(intend_date))

    elif (dialogflow_request.get_intent_displayName() ==
          "Create Appointment - Date - yes"):
        docu_dict = temp_ref.document(session_id).get().to_dict()
        intend_date = docu_dict["intend_date"]
        if isinstance(intend_date, str):
            intend_date = datetime.datetime.fromisoformat(intend_date)
            intend_date = DatetimeWithNanoseconds(
                intend_date.year,
                intend_date.month,
                intend_date.day,
                intend_date.hour,
                intend_date.minute,
            )
        if check_date_validity(intend_date):
            dialogflow_response = DialogflowResponse(
                "The date you specified is available. Please indicate a time interval (30 minutes) to book."
            )
            dialogflow_response.expect_user_response = False
            dialogflow_response.add(
                OutputContexts("pintox-app", session_id,
                               "Create Appointment - Time", 200, {}))
            dialogflow_response.add(SystemIntent("Create Appointment - Time"))

        else:
            dialogflow_response = DialogflowResponse(
                "Sorry, the date you selected is full. Please select another date."
            )
            dialogflow_response.expect_user_response = False
            dialogflow_response.add(
                OutputContexts("pintox-app", session_id,
                               "Create Appointment - Date", 200, {}))
            dialogflow_response.add(SystemIntent("Create Appointment - Date"))

    elif dialogflow_request.get_intent_displayName(
    ) == "Create Appointment - Time":
        time_period = dialogflow_request.get_paramter("time-period")
        start_time, end_time = time_period["startTime"], time_period["endTime"]
        if isinstance(start_time, str):
            start_time = datetime.datetime.fromisoformat(start_time)
            start_time = DatetimeWithNanoseconds(
                start_time.year,
                start_time.month,
                start_time.day,
                start_time.hour,
                start_time.minute,
            )
        if isinstance(end_time, str):
            end_time = datetime.datetime.fromisoformat(end_time)
            end_time = DatetimeWithNanoseconds(
                end_time.year,
                end_time.month,
                end_time.day,
                end_time.hour,
                end_time.minute,
            )
        temp_ref.document(session_id).update({
            "startTime": start_time,
            "endTime": end_time
        })
        dialogflow_response = DialogflowResponse(
            "Your time is from {} to {}. Is that correct?".format(
                start_time, end_time))

    elif (dialogflow_request.get_intent_displayName() ==
          "Create Appointment - Time - yes"):
        docu_dict = temp_ref.document(session_id).get().to_dict()
        start_time, end_time = docu_dict["startTime"], docu_dict["endTime"]
        if isinstance(start_time, str):
            start_time = datetime.datetime.fromisoformat(start_time)
            start_time = DatetimeWithNanoseconds(
                start_time.year,
                start_time.month,
                start_time.day,
                start_time.hour,
                start_time.minute,
            )
        if isinstance(end_time, str):
            end_time = datetime.datetime.fromisoformat(end_time)
            end_time = DatetimeWithNanoseconds(
                end_time.year,
                end_time.month,
                end_time.day,
                end_time.hour,
                end_time.minute,
            )

        res, msg = check_time_validity(start_time, end_time)
        if res:
            dialogflow_response = DialogflowResponse(
                "The appointment has been booked. Would you like to book another?"
            )
            appointments_ref.document().set(docu_dict)
            patients_ref.document(docu_dict["phone_number"]).set(
                {"name": docu_dict["Patient"]})
        else:
            if msg == "invalid time":
                dialogflow_response = DialogflowResponse(
                    "The time you specified is out of the working hour. Please select another time."
                )
                dialogflow_response.expect_user_response = False
                dialogflow_response.add(
                    SystemIntent("Create Appointment - Time - hours"))
            else:
                dialogflow_response = DialogflowResponse(
                    "Sorry, the time you selected is unavailable. Please select another time."
                )
                dialogflow_response.expect_user_response = False
                dialogflow_response.add(
                    SystemIntent("Create Appointment - Time - failure"))
    else:
        dialogflow_response = DialogflowResponse(
            "This is a text response from webhook.")

    response = app.response_class(
        response=dialogflow_response.get_final_response(),
        mimetype="application/json")
    return response
def askApplicationGroup(req):
    res = DialogflowResponse("Are you Singapore/PR or Non Singaporean?")
    res.add(OutputContexts(req.get_project_id(), req.get_session_id(),CONTEXT_ASK_PROGRAMME,5,req.get_paramters()))
    return res.get_final_response()
def askProgramme(req):
    res = DialogflowResponse("What is the graduate programme you are looking at?")
    res.add(OutputContexts(req.get_project_id(), req.get_session_id(),CONTEXT_ASK_PROGRAMME,5,req.get_paramters()))
    return res.get_final_response()
Beispiel #18
0
def default_welcome():
    cursor = mysql_conn.cursor()
    if request.method == 'POST':
        dialogflow_response = DialogflowResponse(
            "Welcome to Flook.Your Smart flight reservation agent")
        dialogflow_response.add(
            SimpleResponse(
                "Welcome to Flook.Your Smart flight reservation agent",
                "Welcome to Flook.Your Smart flight reservation agent"))
        response_text = dialogflow_response.get_final_response()
        dialogflow_request = DialogflowRequest(request.data)
        req = json.loads((request.data).decode('utf-8'))
        if dialogflow_request.get_intent_displayName(
        ) == "Default Welcome Intent":
            dialogflow_response = DialogflowResponse(
                "Welcome to Flook.Your Smart flight reservation agent")
            dialogflow_response.add(
                SimpleResponse("Welcome to my test dialogflow webhook",
                               "Welcome to my test dialogflow webhook"))
            response_text = dialogflow_response.get_final_response()

        if dialogflow_request.get_intent_displayName() == "book_flight":
            params = dialogflow_request.get_paramters()
            if 'source' in params and 'destination' in params and 'dateofjourney' in params:
                if params['source'] == '':
                    src = ''
                    fulfillment_text = req['queryResult']['fulfillmentText']
                    dialogflow_response = DialogflowResponse(fulfillment_text)
                    dialogflow_response.add(
                        SimpleResponse(fulfillment_text, fulfillment_text))
                    response_text = dialogflow_response.get_final_response()
                if type(params['source']) == dict:
                    if params['source']['city'] != '':
                        src = params['source']['city']
                    if params['source']['city'] == '' and params['source'][
                            'admin-area'] == '' and params['source'][
                                'country'] != '':
                        src = params['source']['country']
                    if params['source']['city'] == '' and params['source'][
                            'admin-area'] != '' and params['source'][
                                'country'] == '':
                        src = params['source']['admin-area']
                if params['destination'] == '':
                    dstn = ''
                    fulfillment_text = req['queryResult']['fulfillmentText']
                    dialogflow_response = DialogflowResponse(fulfillment_text)
                    dialogflow_response.add(
                        SimpleResponse(fulfillment_text, fulfillment_text))
                    response_text = dialogflow_response.get_final_response()
                if type(params['destination']) == dict:
                    if params['destination']['city'] != '':
                        dstn = params['destination']['city']
                    if params['destination']['city'] == '' and params[
                            'destination']['admin-area'] == '' and params[
                                'destination']['country'] != '':
                        dstn = params['destination']['country']
                    if params['destination']['city'] == '' and params[
                            'destination']['admin-area'] != '' and params[
                                'destination']['country'] == '':
                        dstn = params['destination']['admin-area']
                    if dstn == 'Bengaluru':
                        dstn = dstn.replace('Bengaluru', 'Bangalore')
                dt = params['dateofjourney']
                dt_modified = []
                if len(dt) == 0:
                    date_of_journey = ''
                    fulfillment_text = req['queryResult']['fulfillmentText']
                    dialogflow_response = DialogflowResponse(fulfillment_text)
                    dialogflow_response.add(
                        SimpleResponse(fulfillment_text, fulfillment_text))
                    response_text = dialogflow_response.get_final_response()
                if len(dt) == 1:
                    dot = re.search(r'\d{4}-\d{2}-\d{2}', dt[0])
                    date_of_journey = dot.group() + ' ' + '00:00:00'
                if len(dt) == 2:
                    for i in dt:
                        dot = re.search(r'\d{4}-\d{2}-\d{2}', i)
                        date_of_journey = dot.group() + ' ' + '00:00:00'
                        dt_modified.append(date_of_journey)

                if src != '' and dstn != '' and len(dt) != 0:
                    print(src, dstn, date_of_journey)
                    if len(dt) == 1:
                        if params['qualifier'] == '':
                            query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel=%s'
                            cursor.execute(query, (src, dstn, date_of_journey))
                            results = cursor.fetchall()
                        if params['qualifier'] != '':
                            qualifier = params['qualifier']
                            if qualifier == 'direct':
                                query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel=%s AND connection=%s'
                                cursor.execute(
                                    query,
                                    (src, dstn, date_of_journey, 'false'))
                                results = cursor.fetchall()

                            if qualifier == 'cheapest':
                                query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel=%s AND connection=%s'
                                cursor.execute(
                                    query,
                                    (src, dstn, date_of_journey, 'true'))
                                results = cursor.fetchall()
                    if len(dt) == 2:
                        query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel between %s and %s'
                        cursor.execute(
                            query, (src, dstn, dt_modified[0], dt_modified[1]))
                        results = cursor.fetchall()
                    app.logger.info(len(results))
                    app.logger.info(results)
                    if len(results) == 0:
                        dialogflow_response = DialogflowResponse(
                            "No flights available")
                        dialogflow_response.add(
                            SimpleResponse("No flights available",
                                           "No flights available"))
                        response_text = dialogflow_response.get_final_response(
                        )
                    if len(results) == 1:
                        dialogflow_response = DialogflowResponse(
                            "Your ticket has been booked")
                        dialogflow_response.add(
                            SimpleResponse("Your ticket has been booked",
                                           "Your ticket has been booked"))
                        response_text = dialogflow_response.get_final_response(
                        )
                    if len(results) > 1:
                        fulfillment_text = str(results)
                        dialogflow_response = DialogflowResponse(
                            fulfillment_text)
                        dialogflow_response.add(
                            SimpleResponse(fulfillment_text, fulfillment_text))
                        response_text = dialogflow_response.get_final_response(
                        )
                        dialogflow_response = DialogflowResponse(
                            "Please select your flight")
                        dialogflow_response.add(
                            SimpleResponse("Please select your flight",
                                           "Please select your flight"))
                        response_text = dialogflow_response.get_final_response(
                        )
                        dialogflow_response = DialogflowResponse()
                        dialogflow_response.expect_user_response = True
        if dialogflow_request.get_intent_displayName(
        ) == "book_flight - select.number":
            params = dialogflow_request.get_single_ouputcontext(
                'book_flight-followup')['parameters']
            src = params['source.original']
            dstn = params['destination.original']
            dt = params['dateofjourney']
            dt_modified = []
            if len(dt) == 1:
                dot = re.search(r'\d{4}-\d{2}-\d{2}', dt[0])
                date_of_journey = dot.group() + ' ' + '00:00:00'
                if params['qualifier'] == '':
                    query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel=%s'
                    cursor.execute(query, (src, dstn, date_of_journey))
                    results = cursor.fetchall()
                    selection = int(params['number'][0])
                    if selection <= len(results):
                        dialogflow_response = DialogflowResponse(
                            "Your ticket has been booked")
                        dialogflow_response.add(
                            SimpleResponse("Your ticket has been booked",
                                           "Your ticket has been booked"))
                        response_text = dialogflow_response.get_final_response(
                        )
                    if selection > len(results):
                        dialogflow_response = DialogflowResponse(
                            "Invalid selection,booking cancelled")
                        dialogflow_response.add(
                            SimpleResponse(
                                "Invalid selection,booking cancelled",
                                "Invalid selection,booking cancelled"))
                        response_text = dialogflow_response.get_final_response(
                        )
                if params['qualifier'] != '':
                    qualifier = params['qualifier']
                    if qualifier == 'direct':
                        query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel=%s AND connection=%s'
                        cursor.execute(query,
                                       (src, dstn, date_of_journey, 'false'))
                        results = cursor.fetchall()
                        selection = int(params['number'][0])
                        if selection <= len(results):
                            dialogflow_response = DialogflowResponse(
                                "Your ticket has been booked")
                            dialogflow_response.add(
                                SimpleResponse("Your ticket has been booked",
                                               "Your ticket has been booked"))
                            response_text = dialogflow_response.get_final_response(
                            )
                        if selection > len(results):
                            dialogflow_response = DialogflowResponse(
                                "Invalid selection,booking cancelled")
                            dialogflow_response.add(
                                SimpleResponse(
                                    "Invalid selection,booking cancelled",
                                    "Invalid selection,booking cancelled"))
                            response_text = dialogflow_response.get_final_response(
                            )
                    if qualifier == 'cheapest':
                        query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel=%s AND connection=%s'
                        cursor.execute(query,
                                       (src, dstn, date_of_journey, 'true'))
                        results = cursor.fetchall()
                        selection = int(params['number'][0])
                        if selection <= len(results):
                            dialogflow_response = DialogflowResponse(
                                "Your ticket has been booked")
                            dialogflow_response.add(
                                SimpleResponse("Your ticket has been booked",
                                               "Your ticket has been booked"))
                            response_text = dialogflow_response.get_final_response(
                            )
                        if selection > len(results):
                            dialogflow_response = DialogflowResponse(
                                "Invalid selection,booking cancelled")
                            dialogflow_response.add(
                                SimpleResponse(
                                    "Invalid selection,booking cancelled",
                                    "Invalid selection,booking cancelled"))
                            response_text = dialogflow_response.get_final_response(
                            )
            if len(dt) == 2:
                for i in dt:
                    dot = re.search(r'\d{4}-\d{2}-\d{2}', i)
                    date_of_journey = dot.group() + ' ' + '00:00:00'
                    dt_modified.append(date_of_journey)
                    query = 'SELECT * from flights where source=%s AND destination=%s AND date_of_travel between %s and %s'
                    cursor.execute(query,
                                   (src, dstn, dt_modified[0], dt_modified[1]))
                    results = cursor.fetchall()
                    selection = int(params['number'][0])
                    if selection <= len(results):
                        dialogflow_response = DialogflowResponse(
                            "Your ticket has been booked")
                        dialogflow_response.add(
                            SimpleResponse("Your ticket has been booked",
                                           "Your ticket has been booked"))
                        response_text = dialogflow_response.get_final_response(
                        )
                    if selection > len(results):
                        dialogflow_response = DialogflowResponse(
                            "Invalid selection,booking cancelled")
                        dialogflow_response.add(
                            SimpleResponse(
                                "Invalid selection,booking cancelled",
                                "Invalid selection,booking cancelled"))
                        response_text = dialogflow_response.get_final_response(
                        )

        return response_text
    else:
        abort(404)
Beispiel #19
0
def webhook():

    if request.method == "POST":
        req = request.get_json(silent=True, force=True)
        print(req)
        result = req.get("queryResult")
        intent = result.get("intent").get('displayName')
        if (intent == 'information'):
            res = processRequest(req)
            res = json.dumps(res, indent=4)
            r = make_response(res)
            r.headers['Content-Type'] = 'application/json'
            return r
        elif (intent == 'case'):
            res = c(req)
            dialogflow_response = DialogflowResponse(res)
            dialogflow_response.add(SimpleResponse(res, res))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
            return response

        elif (intent == 'country_case'):
            res = country(req)
            dialogflow_response = DialogflowResponse(res)
            dialogflow_response.add(SimpleResponse(res, res))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
            return response

        elif (intent == 'world'):

            res = world(req)
            dialogflow_response = DialogflowResponse(res)
            dialogflow_response.add(SimpleResponse(res, res))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
            return response

        elif (intent == 'indiaStates'):

            res = indiaSates(req)
            dialogflow_response = DialogflowResponse(res)
            dialogflow_response.add(SimpleResponse(res, res))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
            return response

        elif (intent == "news"):
            res = covid_news(req)
            dialogflow_response = DialogflowResponse(res)
            dialogflow_response.add(SimpleResponse(res, res))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
            return response

        elif (intent == "menu"):
            res = welcome(req)
            dialogflow_response = DialogflowResponse(res)
            dialogflow_response.add(SimpleResponse(res, res))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
            return response

        elif (intent == "indiaCase"):
            res = india(req)
            dialogflow_response = DialogflowResponse(res)
            dialogflow_response.add(SimpleResponse(res, res))
            response = app.response_class(
                response=dialogflow_response.get_final_response(),
                mimetype='application/json')
            return response