我正在使用具有webhook实现(操作和参数)的Dialog流来调用外部API并解析数据,并应返回到我的dialogflow代理。在这里,我无法将我的回复返回到dialogflow操作。
我的示例代码:
"use strict";
const express = require("express");
const bodyParser = require("body-parser");
const http = require('https');
const https = require("https");
var request = require("request")
var result;
const restService = express();
restService.use(
bodyParser.urlencoded({
extended: true
})
);
restService.use(bodyParser.json());
restService.post('/v2/webhook',(req,res)=>{
var response = "currently service is unable to process your request";
console.log(req.body)
//console.log(req.body.result.action)
if(!req.body || !req.body.queryResult|| !req.body.queryResult.action){
response = "Action is missing in request";
console.log(response)
//console.log(req.body.result.action)
}else{
var action = req.body.queryResult.action;
if(action === 'input.welcome'){
response = "Hi Welcome to my test agent helper intent!";
console.log(response)
}
else if(action === 'ask.for.sign.in'){
//Calling my test API
callAddressApi().then((output) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'fulfillmentText': output }));
}).catch(() => {
res.send(JSON.stringify({ 'fulfillmentText': 'I dont know the address...!' }));
});
}
}
var speech={
"fulfillmentText":response
,"fulfillmentMessages":[
{
"text": {
"text": [
response
]
}
}
]
,"source":"webhook-echo-sample"
}
return res.json(speech);
});
function callAddressApi () {
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the address
let path = "https://maps.googleapis.com/maps/api/geocode/json?address=london";
// Make the HTTP request to get the weather
http.get({path: path}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
let respnse = JSON.parse(body);
let address = respnse['results']['0'][0]['formatted_address'];
console.log(address);
// Create response
let output = address;
result = output;
// Resolve the promise with the output text
console.log(output);
resolve(output);
});
res.on('error', (error) => {
console.log(`Error calling the address API: ${error}`)
reject();
});
});
});
}
restService.listen(process.env.PORT || 8000, function() {
console.log("Server up and listening");
});
//代码结尾。
任何人都可以评论并告诉我我错了吗?谢谢。