Доступ к правильному запросу на исполнение с намерением - PullRequest
0 голосов
/ 17 января 2020

Я надеюсь, что кто-то может помочь мне с этим. У меня есть два отдельных намерения: новости и погода в моем агенте потока диалогов. У меня разные входные параметры для них обоих.
И я использую два отдельных 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!` });
                                    });

}

это показывает выделяет возле ответа. json и говорит, что ответ не определен.

1 Ответ

0 голосов
/ 20 января 2020

Когда я читаю ваш код, похоже, что вы публикуете 2 облачные функции, а через консоль Dialogflow вы можете установить только один URL-адрес веб-крючка или облачную функцию. Поэтому ваш подход должен заключаться в том, что URL вашего веб-крюка (указывающий на виртуальную машину, контейнер и т. Д. c ..) или облачную функцию; содержит код, который ведет себя как «маршрутизатор».

Вы создадите 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() {..}

У меня есть пример проекта Dialogflow / AOG с a (Google Cloud, Cloud Function) вы можете посмотреть на:

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

С помощью этой облачной функции: https://github.com/savelee/dialogflow-aog-tvguide/blob/master/cloudfunction/tvguide/index-old.js

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...