简体   繁体   English

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

[英]Why is my webhook not sending response to my dialogflow agent

I have the below code in python through which my dialogflow agent communicated to a mongodb. 我在python中有以下代码,我的dialogflow代理通过它与mongodb通信。 I am getting the response when I test the mongodb query separately. 我分别测试mongodb查询时得到响应。 However the same doesnt work when I put it in the webhook. 但是,当我将其放入webhook中时,这是行不通的。 I keep getting a JSONDecoder Error. 我不断收到JSONDecoder错误。 Below is my code: 下面是我的代码:

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()

Specific Error Text: 特定错误文字:

raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 从None引发JSONDecodeError(“期望值”,s,err.value)json.decoder.JSONDecodeError:期望值:第1行第1列(字符0)

Please suggest changes 请提出修改建议

It looks like you're sending back a human-readable string from your webhook, rather than a JSON-formatted string containing the fields in the Dialogflow response . 看起来您是从Webhook发送回人类可读的字符串,而不是包含Dialogflow响应中字段的JSON格式的字符串。

Just like you use json.dumps() to format the body for you to read in your debugging, you should build an object with the reply, and then turn that into a valid JSON string with json.dumps() that you return. 就像您使用json.dumps()格式化主体以供您在调试中读取一样,您应该使用回复构建对象,然后使用返回的json.dumps()将其转换为有效的JSON字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从我的 python 应用程序发送.png 文件到 google dialogflow webhook - How to send .png file from my python application to google dialogflow webhook 从用python编写的自定义webhook创建卡响应以进行dialogflow - create card response from custom webhook written in python for dialogflow 为什么我的 POST Webhook 在 Django 中不起作用? - Why isn't my POST Webhook working in Django? 用于 Dialogflow 的 Python 中的 Fulfillment Webhook - Fulfillment Webhook in Python for Dialogflow 为对话流程构建Webhook的问题 - Issue with building a webhook for dialogflow 如何从 ValuesView 获取价值? 试图理解我的机器人的 Dialogflow 响应 - How do I get value from ValuesView? Trying to make sense of Dialogflow response for my bot 当响应包含baicCard时,Dialogflow Webhook在AoG Simulator中给出错误响应 - Dialogflow webhook gives error response in AoG Simulator when response contains baicCard 为什么我在Breakout v0的DQN代理商不学习? - why my DQN's agent at Breakout v0 doesnt learn? 为什么我的不和谐机器人不发送每日消息 - Why is my discord bot not sending a daily message 为什么我的 django 代码没有将 Email 发送给我的新注册用户? - Why my django code is not sending Email to my newly register user?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM