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')
def process(req):
    params = req.get_paramters()
    try:
        for con in req.get_ouputcontext_list():
            o_params = con["parameters"]
            for x in o_params:
                params[x] = o_params[x]
    except:
        None

    print(params)
    if not has_params("graduate-programme", params):
        return askProgramme(req)
    
    if not has_params("application-group", params):
        return askApplicationGroup(req)
    application_group = "" if "application-group" not in params else params["application-group"] 
    graduate_programme = "" if "graduate-programme" not in params else params["graduate-programme"]

    result = [item["answer"] for item in data 
                    if item["graduate-programme"] == graduate_programme 
                        and item["application-group"] == application_group]

    if len(result) == 0:
        return DialogflowResponse("Unknown programme {0}".format(graduate_programme)).get_final_response()
    return DialogflowResponse("The programme fee is {0}".format(result[0])).get_final_response()
Example #3
0
def process(req):
    params = req.get_paramters()
    if params["graduate-programme"] not in data:
        return DialogflowResponse(
            "We currently do not have information for {0}. Please try again later"
            .format(params["graduate-programme"])).get_final_response()
    return DialogflowResponse(
        data[params["graduate-programme"]]).get_final_response()
Example #4
0
    def toDo(self, parameters, dialogflow_request):
        # search boletim with the date paramn from request
        date = datetime.strptime(parameters['date'].split('T')[0], "%Y-%m-%d")
        boletim = Boletim.objects.filter(data=date.date())

        # verifica se algum boletim foi encontrado
        if (boletim.exists()):
            # init of string response
            response = ''

            # inicia o serializer
            serializer = ''
            boletim_id = boletim.values_list('id')

            # getting news to recover url from "boeltim"
            querySet = Noticia.objects.filter(boletim_fk=boletim_id[0])
            noticiaSerializer = NoticiaSerializer(querySet, many=True)

            if (len(boletim) > 1):
                serializer = BoletimSerializer(data=boletim, many=True)
                response = 'encontrei, ' + serializer.data
            else:
                # build the chatbot answer based on boletim number
                serializer = BoletimSerializer(boletim, many=True)

                # create response for user
                response1 = 'encontrei o boletim de numero {}, e ele está disponivel em {} você quer ver as noticias ?'.format(
                    str(serializer.data[0]['numero']),
                    str(noticiaSerializer.data[0]['disponivel_em']))
                response = DialogflowResponse(response1)

                # setting-up the webhook response
                response.dialogflow_response['outputContexts'] = [{
                    'name':
                    '{}/contexts/boletins-followup'.format(
                        dialogflow_request.get_session()),
                    'parameters': {
                        'numero': serializer.data[0]['numero']
                    },
                    'lifespanCount':
                    5
                }]

        else:
            # if the boletim doesn't exists then the default answer is returned
            response = DialogflowResponse(
                'Desculpa mas eu não consegui encontrar nada nesta data =(')

        # set the response attribute on behavior class
        self.response = response
def process(req):
    params = req.get_paramters()
    if params["graduate-programme"] not in data:
        return DialogflowResponse(
            "We currently do not have information for {0}. Please try again later"
            .format(params["graduate-programme"])).get_final_response()

    result = data[params["graduate-programme"]]
    responseText = "\n".join([
        "{0}. {1}".format(num, ans)
        for num, ans in zip(result, range(1,
                                          len(result) + 1))
    ])

    return DialogflowResponse(responseText).get_final_response()
Example #6
0
    def toDo(self, parameters, dialogflow_request):

        time = 'future'
        es_config = ElasticConfig()
        eventQuery = es_config.getEventQuery(parameters, time)

        es = Elasticsearch()

        print(eventQuery)
        res = es.search(index=es_config.getEventoIndex(), body=eventQuery)

        events = res['hits']['hits']

        # if elasticsearch query return no events, the a new query is used to search for past events
        if not events:
            time = 'past'

            eventQuery = es_config.getEventQuery(parameters, time)
            res = es.search(index=es_config.getEventoIndex(), body=eventQuery)
            events = res['hits']['hits']

        print(events)
        response = self.formatNewsResponse(events, time)

        self.response = DialogflowResponse(response)
Example #7
0
def makeReservation(req):
    params = req.get_parameters()
    try:
        for con in req.get_ouputcontext_list():
            o_params = con["parameters"]
            for x in o_params:
                params[x] = o_params[x]
    except:
        None

    print("print params during init " + str(params))

    if not has_params("date", params):
        print("here is not have date")
        return askDate(req)
    if not has_params("time", params):
        return askTime(req)
    if not has_params("partySize", params):
        return askPartySize(req)
    if not has_params("firstName", params):
        return askfirstName(req)
    if not has_params("lastName", params):
        return askLastName(req)
    if not has_params("email", params):
        return askEmail(req)
    if not has_params("phoneNumber", params):
        return askPhone(req)

    restaurant_name = "" if "restaurantName" not in params else params[
        "restaurantName"]
    reservation_date = "" if "date" not in params else params["date.original"]
    reservation_time = "" if "time" not in params else params["time.original"]
    party_size = "" if "partySize" not in params else params[
        "partySize.original"]
    first_name = "" if "firstName" not in params else params["firstName"]
    last_name = "" if "lastName" not in params else params["lastName"]
    email_address = "" if "email" not in params else params["email"]
    phone_number = "" if "phoneNumber" not in params else params["phoneNumber"]

    MakeReservation.make_reservation(reservation_date, reservation_time,
                                     party_size, restaurant_name, first_name,
                                     last_name, email_address, phone_number)
    res = DialogflowResponse("finish making reservation for  " +
                             restaurant_name)

    return res.get_final_response()
Example #8
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()
Example #9
0
def webhook():
    req = DialogflowRequest(request.data)
    intent_name = req.get_intent_displayName()
    print(intent_name)
    if intent_name == "GetCourseDescription":
        return make_response(GetCourseDescription.process(req))
    if intent_name == "GetCourseLearningOutcome":
        return make_response(GetCourseLearningOutcome.process(req))
    if intent_name == "GetCourseDuration":
        return make_response(GetCourseDuration.process(req))
    if intent_name == "GetApplicationDeadline":
        return make_response(GetApplicationDeadline.process(req))
    if intent_name == "GetCourseAdmissionRequirements":
        return make_response(GetCourseAdmissionRequirements.process(req))
    if intent_name == "GetCourseApplicationProcess":
        return make_response(GetCourseApplicationProcess.process(req)) 
    if intent_name == "GetCourseCareerProspects":
        return make_response(GetCourseCareerProspects.process(req))
    if intent_name == "GetCourseModules":
        return make_response(GetCourseModules.process(req))
    if intent_name=="GetGraduateProgrammeFee" or intent_name =="GetGraduateProgrammeFee-ReplyProgramme" or intent_name == "GetGraduateProgrammeFee-ReplyApplicationGroup":
        return make_response(GetGraduateProgrammeFee.process(req))
    if intent_name=="GetGraduateProgrammeFee2":
        print(str(req.get_session()))
        print(str(req.get_response_id()))
        res = DialogflowResponse("This is a new response")
        print(res.get_final_response())
        #__init__(self,project_id,session_id,context_name,context_life_span, context_parameters):
        return make_response(res.get_final_response())       
    # TODO: STEP 2
    # Write your code here..
    # write some if/else to check for the correct intent name.
    # Write code to call the getWeatherIntentHandler function with appropriate input

    if intent_name == "Weather Intent":
        respose_text = "weather"

    else:
        respose_text = "No intent matched from fullfilment code."
    # Branching ends here

    # Finally sending this response to Dialogflow.
    return make_response(jsonify({"fulfillmentText": respose_text}))
Example #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 = 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)
Example #11
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()
Example #12
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()
Example #13
0
    def toDo(self, parameters, dialogflow_request):

        # Create Conection with elasticSearch and config search parameters
        elasticSearchConfig = ElasticConfig()
        elasticSearch = Elasticsearch(hosts=elasticSearchConfig.hosts)

        candidates = elasticSearch.search(
            index=elasticSearchConfig.getResolutionIndex(),
            body=elasticSearchConfig.getResolutionQuery(parameters))
        #        print(candidates)

        if not (candidates['hits']['total']['value'] == 0):
            df = self.responseRanking(candidates)
            response = self.formatResponse(df)
            self.response = DialogflowResponse(response)

        else:
            self.response = DialogflowResponse(
                "infelizmente não encontrei nada, tenta ai uma nova combinação de palavras,"
                + " talvez eu tenha mais sorte na proxima")
Example #14
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()
Example #15
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()
Example #16
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()
Example #17
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()
Example #18
0
    def toDo(self, parameters, dialogflow_request):
        # geting  output context parameters
        boletim_numero = dialogflow_request.request_data['queryResult']['outputContexts'][0]['parameters']['numero']

        # search for any boletim that contains the id from request
        boletim_id = Boletim.objects.filter(numero=boletim_numero).values_list('id')

        # search for any news that match with boletim id
        querySet = Noticia.objects.filter(boletim_fk=boletim_id[0][0])
        serializer = NoticiaSerializer(querySet, many=True)
        print(serializer.data)
        response = self.formatNewsResponse(serializer.data)

        self.response = DialogflowResponse(response)
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()
Example #20
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)
Example #21
0
def webhook(request):
    # build a request object
    req = json.loads(request.body)
    # get action from json
    intent = req.get('queryResult').get('intent').get('displayName')

    # --------------------------#
    # INFECTION STATUS INTENT   #
    # --------------------------#
    if intent == "infection-status-covid":
        country = req.get('queryResult').get('parameters').get('country-defined').lower()
        casestatus = req.get('queryResult').get('parameters').get('CaseStatus')

        pd_table = pd.DataFrame(list(globalStatus.objects.all().values()))
        LastUpdate = list(globalLastUpdate.objects.all().values('last_update'))[0]['last_update']

        try:
            diagnose_ = pd_table[pd_table['country'] == country]['diagnosed'].iloc[0]
            death_ = pd_table[pd_table['country'] == country]['death'].iloc[0]
            discharged_ = pd_table[pd_table['country'] == country]['discharged'].iloc[0]
            active_ = pd_table[pd_table['country'] == country]['active'].iloc[0]
            critical_ = pd_table[pd_table['country'] == country]['critical'].iloc[0]
            new_case_ = pd_table[pd_table['country'] == country]['new_cases'].iloc[0]
            new_death_ = pd_table[pd_table['country'] == country]['new_death'].iloc[0]
            
        except:
            country = "Worldwide"
            diagnose_ = pd_table[pd_table['country'] == 'total:']['diagnosed'].iloc[0]
            death_ = pd_table[pd_table['country'] == 'total:']['death'].iloc[0]
            discharged_ = pd_table[pd_table['country'] == 'total:']['discharged'].iloc[0]
            active_ = pd_table[pd_table['country'] == 'total:']['active'].iloc[0]
            critical_ = pd_table[pd_table['country'] == 'total:']['critical'].iloc[0]
            new_case_ = pd_table[pd_table['country'] == 'total:']['new_cases'].iloc[0]
            new_death_ = pd_table[pd_table['country'] == 'total:']['new_death'].iloc[0]

        #More info: https://github.com/Emmarex/dialogflow-fulfillment-python
        text1 = f'Currently, {country.capitalize()} has a total of {diagnose_:.0f} confirmed cases, + {new_case_:.0f} new case(s) from yesterday. There is total of {death_:.0f} death case(s), + {new_death_:.0f} new death case(s) from yesterday. \n\n{discharged_:.0f} people recovered from it, and {critical_:.0f} people still in critical condition. \n\n{LastUpdate}.'
   
    # --------------------------#
    # HEADLINE NEWS INTENT      #
    # --------------------------#
    if intent == "latest-news-covid":
        news_list = list(MOHHeadlines.objects.order_by('-news_date').values())
        metatext = "Below are the top 3 latest news:\n"
        for news in news_list[:3]: #top3
            date_ = news['news_date'].strftime('%d %b, %Y')
            title_ = news['news_title']
            link_ = news['news_link']
            metatext = metatext + f"{date_} \n{title_} \n{link_}\n\n"
        
        text1 = metatext + "For more info: https://www.moh.gov.sg/covid-19"
            
    
    # --------------------------#
    # Distance to Hospital      #
    # --------------------------#
    if intent == "nearest-hospital-covid" or intent == "treatment-covid.yes.address":
        address_ = req.get('queryResult').get('parameters').get('address')
        
        try:
            premise_ = req.get('queryResult').get('parameters').get('healthcare')
            if premise_ == '': 
                premise_ = 'Hospital'
            else:
                premise_ = premise_.capitalize()
        except:
            premise_ = 'Hospital'

        #for testing only. Pick 5th from hospital/clinic list
        premise_query = list(hospitalList.objects.filter(Type=premise_))
        #converting user-input starting point to geo-code lat & long
        geocode_result = gmaps.geocode(str(address_) + ' Singapore')

        if geocode_result==[]:
            text1 = 'Route not found. Perhaps check your address or postal code?'
        else:
            dist_list = [] 
            slat = radians(geocode_result[0]['geometry']['location']['lat'])
            slng = radians(geocode_result[0]['geometry']['location']['lng'])
            for item in premise_query:
                elat = radians(item.lat)
                elng = radians(item.lng)
                dist_list.append(6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slng - elng))) # this is original open list, for reference
            
            open_list = dist_list.copy()
            min_index = dist_list.index(min(dist_list)) #for search, find the min distance
            distance_result = gmaps.distance_matrix(str(address_) + ' Singapore', premise_query[min_index].address, departure_time=datetime.now())
            distance_gmap = distance_result['rows'][0]['elements'][0]['distance']['value']/1000 #convert m to km, this will be true distance
            duration_gmap = distance_result['rows'][0]['elements'][0]['duration']['value']/60 #convert sec to min
            solution = min_index #index of solution
            open_list.pop(min_index)
            print('original solution', premise_query[solution].Name, 'absolute distance is ', dist_list[solution], 'google final distance is ', distance_gmap)

            #check if open list has lesser distance than current one
            counter = 0
            while min(open_list) < distance_gmap:
                print('attempt', counter+1)
                new_min_index = dist_list.index(min(open_list))
                distance_result = gmaps.distance_matrix(str(address_) + ' Singapore', premise_query[new_min_index].address, departure_time=datetime.now())
                new_distance_gmap = distance_result['rows'][0]['elements'][0]['distance']['value']/1000
                new_duration_gmap = distance_result['rows'][0]['elements'][0]['duration']['value']/60 #convert sec to min
                open_list.remove(min(open_list))
                print('new solution', premise_query[new_min_index].Name, 'absolute distance is ', dist_list[new_min_index], 'google final distance is ', new_distance_gmap)
                if new_distance_gmap < distance_gmap:
                    solution = new_min_index #index of solution
                    distance_gmap = new_distance_gmap
                    duration_gmap = new_duration_gmap
                if open_list == []:
                    break
                counter+=1
                print('current solution', premise_query[solution].Name, 'absolute distance is ', dist_list[solution], 'google final distance is ', distance_gmap)

        text1 = f"Your location is {address_}, Singapore. Nearest {premise_} to you that I found is at {premise_query[solution].Name}. You are {distance_gmap:.1f}km away from it, it will take approximately {duration_gmap:.0f}min for you to reach there if you depart by car now."


    # --------------------------#
    # SYNC  INTENT              #
    # --------------------------#
    if intent == "sync":
        try:
            ss = statusScrapper()
            ss.start()
            ns = newsScrapper()
            ns.start()
            text1 = "Sync/update completed."
        
        except:
            text1="Error occurred. Contact admin to debug."



    dialogflow_response = DialogflowResponse(text1)
    reply = dialogflow_response.get_final_response()

    db.connections.close_all()
    # return generated response
    return HttpResponse(reply, content_type='application/json; charset=utf-8')
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()
Example #24
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
Example #25
0
def process(req):
    print("session id from process" + req.get_session_id())
    i = intelligence.Intel()
    if req.get_intent_displayName() == "ImageResponse":
        queryId = int(req.get_parameters()["queryId"])
        # get req value parameter
        value = int(req.get_parameters()["value"])
        i.update_response(queryId, value, 0, 0)
    else:
        i.restart_query()

    print("session id from image response" + req.get_session_id())

    print(i.get_query_size())
    if i.get_query_size() >= 5:
        id, path, restaurant_name = i.get_query()

        res = DialogflowResponse("We are recommending " + restaurant_name +
                                 ", please rate 1 - 5?")
        res.fulfillment_messages.append({
            "text": {
                "text": [
                    "We are looking for the best restaurant for you. Please type \"Show me\" in 1 minute to show the result"
                ]
            },
            "platform": "SLACK"
        })
        print("query size >=5")
        pool = Pool()
        pool.apply_async(i.calculate_result)

        print(res.get_final_response())
        return res.get_final_response()
    else:
        id, path, restaurant_name = i.get_query()

        res = DialogflowResponse("We are recommanding " + restaurant_name +
                                 ", please rate 1 - 5?")
        res.fulfillment_messages.append({
            "card": {
                "title":
                "We are recommanding " + restaurant_name +
                ", please rate 1 - 5?",
                "imageUri":
                "{}/image?path={}".format(server_url, path),
                "buttons": [{
                    "text":
                    1,
                    "postback":
                    "ImageResponse queryId {} value {}".format(id, 1)
                }, {
                    "text":
                    2,
                    "postback":
                    "ImageResponse queryId {} value {}".format(id, 2)
                }, {
                    "text":
                    3,
                    "postback":
                    "ImageResponse queryId {} value {}".format(id, 3)
                }, {
                    "text":
                    4,
                    "postback":
                    "ImageResponse queryId {} value {}".format(id, 4)
                }, {
                    "text":
                    5,
                    "postback":
                    "ImageResponse queryId {} value {}".format(id, 5)
                }]
            },
            "platform": "SLACK"
        })

        print(res.get_final_response())
        return res.get_final_response()
Example #26
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
Example #27
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"
        }
Example #28
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)
Example #29
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()
Example #30
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())