【问题标题】:Accessing correct fulfilment request with intent有意访问正确的履行请求
【发布时间】:2020-01-21 17:18:09
【问题描述】:

我希望有人可以帮助我解决这个问题。 我的对话流代理中有两个独立的意图新闻和天气。 我对它们都有不同的输入参数。
我为它们中的每一个使用了两个单独的 API。 当我分别使用它们时,它工作正常。 但是当我尝试将它们结合在一个代理中时,它不会根据问题显示相关输出。即,如果我问有关天气的问题,它会向我显示新闻。 有什么办法可以修复它。现在它直接进入第二个请求。这是我的代码:

'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {dialogflow} = require('actions-on-google');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = '0cb58ac2d82f484fa75185834191912';
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('63756dc5caca424fb3d0343406295021');

process.env.DEBUG = 'dialogflow:*';

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) =>
{

    var agent = new WebhookClient({ request, response });
    // Get the city and date from the request
    let city = request.body.queryResult.parameters['geo-city'];// city is a required param
     // Get the date for the weather forecast (if present)
    let date = 'date';
    if (request.body.queryResult.parameters['date']) {
                                                    date = request.body.queryResult.parameters['date'];
                                                    console.log('Date: ' + date);
                                                    }
  //Get the search criteria from the request    
  const search = request.body.queryResult.parameters['search'];
  console.log(search);

  //Map the correct intent 
    let intentMap = new Map();
        intentMap.set('misty.weather',getweather );
        intentMap.set('misty.news', getnews);

        agent.handleRequest(intentMap);

});
//Weather reuest function 
function getweather(agent,city,date)
{
  callWeatherApi(city, date).then((output) => {
                                            response.json({ 'fulfillmentText': output }); // Return the results of the weather API to Dialogflow
                                            }).catch(() => {
                                                            response.json({ 'fulfillmentText': `I don't know the weather but I hope it's good!` });
                                                            });

}

// news request function 
function getnews(search,agent)
{
callNewsApi(search).then((output) => {
                            console.log("Indide request");

                            response.json({ 'fulfillmentText': output }); // Return the results of the news API to Dialogflow
                        }).catch((error) => {
                                        console.log(error);
                                        response.json({ 'fulfillmentText': `I don't know the news but I hope it's good!` });
                                    });

}

// API call for weather 
function callWeatherApi (city, date) {
  return new Promise((resolve, reject) => {
    // Create the path for the HTTP request to get the weather
    let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' +
      '&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date;
    console.log('API Request: ' + host + path);

    // Make the HTTP request to get the weather
    http.get({host: host, path: path}, (response) => {
      let body = ''; // var to store the response chunks
      response.on('data', (d) => { body += d; }); // store each response chunk
      response.on('end', () => {
        // After all the data has been received parse the JSON for desired data
        let response = JSON.parse(body);
        let forecast = response['data']['weather'][0];
        let location = response['data']['request'][0];
        let conditions = response['data']['current_condition'][0];
        let currentConditions = conditions['weatherDesc'][0]['value'];

        // Create response
        let output = `Current conditions in the ${location['type']} 
        ${location['query']} are ${currentConditions} with a projected high of
        ${forecast['maxtempC']}°C or ${forecast['maxtempF']}°F and a low of 
        ${forecast['mintempC']}°C or ${forecast['mintempF']}°F on 
        ${forecast['date']}.`;

        // Resolve the promise with the output text
        console.log(output);
        resolve(output);
      });
      response.on('error', (error) => {
        console.log(`Error calling the weather API: ${error}`);
        reject();
      });
    });
  });
}
//API call for news
function callNewsApi(search) 
{

                    console.log("Inside api call");
                    console.log(search);

                     return newsapi.v2.topHeadlines
                    (
                            { 
                            source:'CBC News',
                            q:search,
                            langauge: 'en',        
                            country: 'ca',

                            }
                        ).then (response => {



                                                                    // var to store the response chunks
                                                    // store each response chunk

                                                            console.log(response);

                                                            var articles = response['articles'][0];
                                                            console.log(articles);
                                                            console.log("Inside responce call");
                                                    // Create response
                                                    var output = `Current news in the '${search}' with following title is  ${articles['titile']} which says that ${articles['description']}`;
                                                    console.log(output);
                                                    return output; 
                                                                    });


}       

它在第 51 行和第 42 行给了我一个参考错误。我怀疑我缺少显示输出的参数。

function getnews(search,agent)
{
callNewsApi(search).then((output) => {
                            console.log("Indide request");

                            response.json({ 'fulfillmentText': output }); // Return the results of the news API to Dialogflow
                        }).catch((error) => {
                                        console.log(error);
                                        response.json({ 'fulfillmentText': `I don't know the news but I hope it's good!` });
                                    });

}

它在 response.json 附近显示亮点,并表示未定义响应。

【问题讨论】:

  • 你能分享更多代码吗,你将两个意图处理程序结合在一个 API 中?
  • @AbhinavKumar 为代码添加了更多细节。以及我得到的确切错误

标签: node.js dialogflow-es


【解决方案1】:

当我阅读您的代码时,您似乎发布了 2 个 Cloud Functions,而通过 Dialogflow 控制台,您只能设置一个 webhook URL 或 Cloud Functions。因此,您的方法应该是您的 webhook URL(指向 VM、容器等)或 Cloud Function;包含行为类似于“路由器”的代码。

您只需创建一次 WebhookClient。 所有参数都可以从 queryResult 对象中检索出来。

intentMap 可能如下所示:

  let intentMap = new Map();   
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('misty.weather', getWeather);
  intentMap.set('misty.news', getNews);   

  function getNews() { .. }
  function getWeather() {..}

我有一个带有(Google Cloud,Cloud Function)的示例 Dialogflow / AOG 项目,你可以看看:

https://github.com/savelee/dialogflow-aog-tvguide/

使用此云功能: https://github.com/savelee/dialogflow-aog-tvguide/blob/master/cloudfunction/tvguide/index-old.js

【讨论】:

  • 您的回答对我来说很有意义我在同一个 http 调用下进行了两次请求。我查看了您的示例并尝试更改我的代码,现在它指向正确的 api 请求函数。但它没有在我的履行文本下返回任何输出,它给了我一个错误参考错误。不知道怎么解决。
  • 我已经用更新的代码编辑了我的问题。你能建议任何更改来修复错误吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 2015-10-19
  • 1970-01-01
  • 2022-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多