Dialogflow v2 使用 Firebase Cloud Function 返回 Firestore 数据库数据



我是DialogFlow的新手。 我想创建一个聊天机器人,我可以向它提问,它会用从我的 Firebase Firestore 数据库中检索到的值进行响应。

我已经创建了必要的意图(GetPopulationInCity(并选择了Enable webhook call for this intent

最好是我想将DialogFlow Fulfillment与我的其他CloudFunction应用程序一起使用。

我在以下示例中使用了代码:

'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function GetPopulationInCity(agent) {
//Search Firestore for value, if found =>
agent.add(`There are 10,000 people living in XXX`); //should it be ask or something like send or return?
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Get Population', GetPopulationInCity);
intentMap.set('Default Fallback Intent', fallback);
agent.handleRequest(intentMap);
});

但我不知道如何为我的意图创建一个处理程序并返回一个值。有没有人可以帮助我?

首先,确保您尝试为其编写处理程序的意图的名称与intentMap.set()部分中的名称匹配。 (在您的描述中,您不清楚对话流中的意图名称与函数的名称

。处理程序本身需要做几件事:

  1. 获取可能在意向中设置的任何参数的值。

    你可以从agent.parameters.

  2. 在数据库中查询值。

  3. 返回一个 Promise,以指示正在异步处理结果。
  4. 作为结果处理的一部分,调用包含结果的agent.add()

    这些操作将使用类似于您现在执行 Firebase 调用的代码来完成。 您尚未展示您是如何执行此操作的,或者您的数据库结构是什么样的,但假设您使用的是 Firebase 管理库,您的 webhook 处理程序可能如下所示:

    function GetPopulationInCity( agent ){
    var cityName = agent.parameters.cityName;
    return db.collection('cities').doc(cityName).get()
    .then( doc => {
    var value = doc.data();
    agent.add(`The population of ${cityName} is ${value.population}.`);
    });
    }
    

最后,顺便说一句,您的代码提出了使用add()ask()的问题。

  • 您正在使用 Dialogflow 履行库,该库(按照惯例(将发送到处理程序的参数命名为"代理"。向响应添加消息类型的函数是agent.add()

  • 还有另一个库,即 actions-on-google 库,它的工作方式与 dialogflow-fulfillment 库类似。a-o-g 库的约定是传递带有会话信息的"conv"参数。向代理添加响应的函数是conv.ask()conv.close()

  • 为了增加一些混淆,如果您正在使用操作(而不是 Dialogflow 使用的其他代理之一(,您可以通过调用agent.conv()从 dialogflow-实现库中获取 a-o-g "conversation" 对象。

我建议看看谷歌上的动作提供的这个动作示例:https://github.com/actions-on-google/dialogflow-updates-nodejs

按照自述文件中的步骤操作,或者只查看 functions/index.js 文件,您将看到该示例如何处理 Firestore。

最新更新