javascript - Dialogflow Fulfillment Webhook 调用失败

标签 javascript firebase dialogflow-es javascript-objects dialogflow-es-fulfillment

enter image description here我是对话流实现的新手,我正在尝试根据用户问题从新闻 API 中检索新闻。我遵循新闻 API 提供的文档,但无法从搜索结果中捕获任何响应,当我在控制台中运行该函数时,这不是错误。我更改了代码,看起来现在它已经到达 newsapi 端点,但没有获取任何结果。我正在利用https://newsapi.org/docs/client-libraries/node-js请求搜索有关该主题的所有内容。当我诊断该函数时,它显示“Webhook 调用失败。错误:不可用。”

'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const http = require('http');


const host = 'newsapi.org';
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('63756dc5caca424fb3d0343406295021');

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

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((req, res) =>
{
  // Get the city 
  let search = req.body.queryResult.parameters['search'];// search is a required param
  

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

function callNewsApi(search) 
{
  console.log(search);
  newsapi.v2.everything
  (
    { 
        q: 'search',
        langauge: 'en',
        sortBy: 'relevancy',
        source: 'cbc-news',
        domains: 'cbc.ca',
        from: '2019-12-31',
        to: '2020-12-12',
        page: 2
    }
  ).then (response => {console.log(response);
                       {                               

                      
     let articles = response['data']['articles'][0];
                      

        // Create response
        
let responce = `Current news in the $search with following title is  ${articles['titile']} which says that 
        ${articles['description']}`;

        // Resolve the promise with the output text
        console.log(output);
       
                       }
   });  
  

}

这里还有 RAW API 响应

{
  "responseId": "a871b8d2-16f2-4873-a5d1-b907a07adb9a-b4ef8d5f",
  "queryResult": {
    "queryText": "what is the latest news about toronto",
    "parameters": {
      "search": [
        "toronto"
      ]
    },
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "intent": {
      "name": "projects/misty-ktsarh/agent/intents/b52c5774-e5b7-494a-8f4c-f783ebae558b",
      "displayName": "misty.news"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {
      "webhook_latency_ms": 543
    },
    "languageCode": "en"
  },
  "webhookStatus": {
    "code": 14,
    "message": "Webhook call failed. Error: UNAVAILABLE."
  },
  "outputAudio": "UklGRlQqAABXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAAZGF0YTAqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... (The content is truncated. Click `COPY` for the original JSON.)",
  "outputAudioConfig": {
    "audioEncoding": "OUTPUT_AUDIO_ENCODING_LINEAR_16",
    "synthesizeSpeechConfig": {
      "speakingRate": 1,
      "voice": {}
    }
  }
} 

这是履行请求:

{
  "responseId": "a871b8d2-16f2-4873-a5d1-b907a07adb9a-b4ef8d5f",
  "queryResult": {
    "queryText": "what is the latest news about toronto",
    "parameters": {
      "search": [
        "toronto"
      ]
    },
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "intent": {
      "name": "projects/misty-ktsarh/agent/intents/b52c5774-e5b7-494a-8f4c-f783ebae558b",
      "displayName": "misty.news"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {
      "webhook_latency_ms": 543
    },
    "languageCode": "en"
  },
  "webhookStatus": {
    "code": 14,
    "message": "Webhook call failed. Error: UNAVAILABLE."
  },
  "outputAudio": "UklGRlQqAABXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAAZGF0YTAqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA... (The content is truncated. Click `COPY` for the original JSON.)",
  "outputAudioConfig": {
    "audioEncoding": "OUTPUT_AUDIO_ENCODING_LINEAR_16",
    "synthesizeSpeechConfig": {
      "speakingRate": 1,
      "voice": {}
    }
  }
}

这里还有 Firebase 控制台的屏幕截图。 enter image description here

任何人都可以指导我,我在这里缺少什么吗?

最佳答案

关键是错误信息的前三行:

Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'newsapi'

它表示无法加载 newsapi 模块,最可能的原因是您没有将其列为 package.json< 中的依赖项 文件。

如果您使用的是 Dialogflow 内联编辑器,则需要选择 package.json 选项卡并在 dependencies 部分中添加一行。

Inline Editor

更新

目前尚不清楚您何时何地收到“不可用”错误,但如果您使用 Dialogflow 的内联编辑器,一个可能的原因是它使用的是具有限制的 Firebase“Spark”定价计划在 Google 网络之外的网络调用上。

您可以upgrade to the Blaze plan ,这确实需要存档信用卡,但包含 Spark 计划的免费套餐,因此您在少量使用期间不应产生任何费用。这将允许网络调用。

更新基于TypeError:无法读取未定义的属性“0”

这表明属性(或者可能是属性的索引)正在尝试引用未定义的内容。

目前尚不清楚这可能是哪一行,但这些行都是可疑的:

    let response = JSON.parse(body);
    let source = response['data']['source'][0];
    let id = response['data']['id'][0];
    let name = response['data']['name'][0];
    let author = response['author'][0];
    let title = response['title'][0];
    let description = response['description'][0];

因为它们都引用一个属性。我会检查到底返回了什么并存储在响应中。例如,发回的内容中是否没有“数据”或“作者”字段?

查看 https://newsapi.org/docs/endpoints/everything ,看起来这些都不是字段,但有一个发送回的articles属性,其中包含一个文章数组。您可能希望对其进行索引并获取所需的属性。

更新

看起来就像这样,尽管您正在使用此行将参数加载到变量中

// Get the city and date from the request
let search = req.body.queryResult.parameters['search'];// city is a required param

您实际上并没有在任何地方使用 search 变量。相反,您似乎使用此行将文字字符串“search”传递给您的函数

callNewsApi('search').then((output) => {

我猜它会搜索“搜索”这个词。

您表示“它进入 catch 部分”,这表明调用中出现了问题。您不会在 catch 部分显示任何日志记录,并且记录引发的异常可能很有用,因此您知道为什么它会进入 catch 部分。类似的东西

}).catch((xx) => {
  console.error(xx);
  res.json({ 'fulfillmentText': `I don't know the news but I hope it's good!` });
});

这是正常的,但由于您似乎将其记录在 .on('error') 部分,因此显示该错误可能会很有用。

关于javascript - Dialogflow Fulfillment Webhook 调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582045/

相关文章:

javascript - $save 给我 TypeError : undefined is not a function when saving model that is a list in angular

php - 哪个更快?空语句或返回

android - getContactsFromFirebase() 方法返回一个空列表

javascript - Angular.js 中的 ng-repeat 未按预期工作

javascript - Dialogflow(自定义负载和启用 Webhook)

javascript - 将 JS 变量输出到我的 PHP 文件中

javascript - Ember 数据中是否有一个钩子(Hook)我可以用来知道它何时实际向服务器发送请求?

firebase - 创建文档时使用 mergeFields 设置的 Firestore 文档无法按预期工作

node.js - 在对话框流中使用对象列表作为参数设置上下文

dialogflow-es - 是否可以让我的对话流代理在互联网上搜索未解决问题的答案?