为什么我的Webhook无法将响应发送到我的dialogflow代理

时间:2018-10-26 06:58:31

标签: python json mongodb flask dialogflow

我在python中有以下代码,我的dialogflow代理通过该代码与mongodb通信。 我分别测试mongodb查询时得到响应。 但是,当我将其放入webhook中时,这是行不通的。 我不断收到JSONDecoder错误。 下面是我的代码:

import pymongo
from pymongo import MongoClient
from pprint import pprint
import flask
from flask import Flask, request, jsonify
#import firebase_admin
#from firebase_admin import credentials
#from firebase_admin import db
#from firebase_admin import firestore
import urllib
import os
import dialogflow_v2 as dialogflow
import requests
import json
from bson.json_util import dumps


client = MongoClient("mongodb://ds052629.mlab.com:52629/healthcare")
db = client["healthcare"]
db.authenticate("admin", "Password007")

#json_docs = dumps(db.HIS.find({"Phone Number":9876540001}).limit(1))
# for doc in json_docs:
#    json_doc = json.dumps(doc, default=json_util.default)
#    json_docs.append(json_doc)

data = 9876540001

app = Flask(__name__)


@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
    req = request.get_json(silent=True)
    print("Request::")
    print(json.dumps(req, indent=4))
    data = req['queryResult']['parameters']['Phonenumber']
    print(data)
    serverrecord = getdata(data)
    pese = serverrecord
    print(type(serverrecord))
    print(serverrecord)
    print(type(pese))
    print(pees)
    print("Discharge status is : {}".format(pese['Discharged']))
    response = """
    Name:{0}
    Date:{1}
    Last Outstanding:{2}
    Discharge Status:{3}
    """.format(pese['Name'], pese['Date'], pese['Last_Outstanding'], pese['Discharged'])
    print(response)
    print(type(response))
    reply = """fulfillmentText":{},""".format(response)

    return reply


def getdata(DATA):
    res = dumps(db.HIS.aggregate(
        [
            {
                "$match": {"Phone Number": DATA}
            },
            {
                "$sort": {"Date": -1}
            },
            {
                "$group": {"_id": "Patient ID",
                           "Discharge_Date": {"$first": "$Discharge Date"},
                           "Doctor_Visit": {"$first": "$Doctor Visit"},
                           "Total_Bill_at_the_time_of_Discharge": {"$first": "$Total Bill at the time of Discharge"},
                           "Admission_Date": {"$first": "$Admission Date"},
                           "Primary_Speciality": {"$first": "$Primary Speciality"},
                           "Estimated_Patient_outstanding": {"$first": "$Estimated Patient outstanding"},
                           "Last_Outstanding": {"$first": "$Last Outstanding"},
                           "Cloned_Data": {"$first": "$Cloned_Data"},
                           "Room_Category": {"$first": "$Room Category"},
                           "Equipment_Charges": {"$first": "$Equipment Charges"},
                           "Final_Payment_Approved_by_TPA": {"$first": "$Final Payment Approved by TPA"},
                           "Radiology": {"$first": "$Radiology"},
                           "field28": {"$first": "$field28"},
                           "Date": {"$first": "$Date"},
                           "Professional_Services": {"$first": "$Professional Services"},
                           "Bill_for_the_Day": {"$first": "$Bill for the Day"},
                           "Room_Rent": {"$first": "$Room Rent"},
                           "Medical_Consumable": {"$first": "$Medical Consumable"},
                           "Name": {"$first": "$Name"},
                           "Phone_Number": {"$first": "$Phone Number"},
                           "Length_of_Stay": {"$first": "$Length of Stay"},
                           "Copayment_Pending_by_Patient": {"$first": "$Copayment Pending by Patient"},
                           "Estimated_TPA_Outstanding": {"$first": "$Estimated TPA Outstanding"},
                           "Patient_ID": {"$first": "$Patient ID"},
                           "Payment_Due_Date": {"$first": "$Payment Due Date"},
                           "Pathology": {"$first": "$Pathology"},
                           "Pharmacy": {"$first": "$Pharmacy"},
                           "Procedure_Charges": {"$first": "$Procedure Charges"},
                           "Discharged": {"$first": "$Discharged"},
                           }
            }
        ]
    ))
    pes = json.loads(res[1:-1])
    return pes


def detect_intent_texts(project_id, session_id, texts, language_code):
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)

    for text in texts:
        text_input = dialogflow.types.TextInput(
            text=text, language_code=language_code)
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(
            session=session, query_input=query_input)
        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillmentText))

    return response.query_result.fulfillmentText


@app.route('/send_message', methods=['POST'])
def send_message():
    message = request.form['message']
    project_id = os.getenv('DIALOGFLOW_PROJECT_ID')
    fulfillment_text = detect_intent_texts(project_id, "unique", message, "en")
    response_text = {"message": fulfillment_text}

    return jsonify(response_text)


if __name__ == "__main__":
    app.run()

特定错误文本:

  

从None提高JSONDecodeError(“期望值”,s,err.value)   json.decoder.JSONDecodeError:期望值:第1行第1列(字符0)

请提出更改建议

1 个答案:

答案 0 :(得分:0)

似乎您正在从Webhook发送回人类可读的字符串,而不是包含fields in the Dialogflow response的JSON格式的字符串。

就像您使用json.dumps()来格式化主体以供您在调试中读取一样,您应该使用回复构建对象,然后使用json.dumps()将其转换为有效的JSON字符串。返回。