在 Google 上使用 Actions 保存对话数据

saving data in conversations with Actions on Google

我正在 Google 上的 Actions 上开发一个应用程序,我注意到在使用 Dialogflow Fulfillment library 时我无法在对话之间保存数据。 这是使用 WebhookClient 的代码:

const { WebhookClient, Card, Suggestion } = require('dialogflow-fulfillment');
exports.aog_app = functions.https.onRequest((request, response)=>{
  let agent = new WebhookClient({request, response});
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', (agent)=>{
    agent.add("hello there!") ;
  });
  intentMap.set('presentation', (agent)=>{
    let conv = agent.conv();
    let counter = conv.data.counter;
    console.log("counter", counter)
    if(counter){
      conv.data.counter = counter+1;
    }else{
      conv.data.counter = 1;
    }
    agent.add("counter is "+counter) ;
  });
  agent.handleRequest(intentMap)
});

counter 在每一轮都保持未定义状态。

但是在使用 Action on Google Nodejs Library 时,我可以毫无问题地保存数据:

const {
  dialogflow,
  SimpleResponse,
  BasicCard,
  Permission,
  Suggestions,
  BrowseCarousel,
  BrowseCarouselItem,
  Button,
  Carousel,
  DateTime,
  Image,
  DialogflowConversation
} = require('actions-on-google');
const app = dialogflow({debug: true});
app.intent('Default Welcome Intent', (conv)=>{
  conv.ask("hello there!");
});
app.intent('presentation', (conv)=>{
  let counter = conv.data.counter;
  console.log("counter", counter)
  if(counter){
    conv.data.counter = counter+1;
  }else{
    conv.data.counter = 1;
  }
  conv.ask("counter is "+counter)

})
exports.aog_app = functions.https.onRequest(app);

counter 每回合递增。

有没有办法使用 Dialogflow fulfillment 库在对话之间保存数据?

Google 的 Dialogflow 团队发布了一个代码示例,展示了如何通过集成 Google Cloud 的 Firebase Cloud Firestore 来实现数据持久化。

您可以在此处找到示例:https://github.com/dialogflow/fulfillment-firestore-nodejs

这(可能)是您要查找的代码:

  function writeToDb (agent) {
    // Get parameter from Dialogflow with the string to add to the database
    const databaseEntry = agent.parameters.databaseEntry;

    // Get the database collection 'dialogflow' and document 'agent' and store
    // the document  {entry: "<value of database entry>"} in the 'agent' document
    const dialogflowAgentRef = db.collection('dialogflow').doc('agent');
    return db.runTransaction(t => {
      t.set(dialogflowAgentRef, {entry: databaseEntry});
      return Promise.resolve('Write complete');
    }).then(doc => {
      agent.add(`Wrote "${databaseEntry}" to the Firestore database.`);
    }).catch(err => {
      console.log(`Error writing to Firestore: ${err}`);
      agent.add(`Failed to write "${databaseEntry}" to the Firestore database.`);
    });
  }

您需要在更新 conv.data

后将 conv 添加回代理
agent.add(conv);