如何使用DialogFlow在线编辑器从Firebase检索数据

时间:2018-07-12 02:27:44

标签: javascript actions-on-google dialogflow

我对DialogFlow很陌生。我想知道如何通过DialogFlow的内联编辑器从Firebase检索数据。希望你能帮助我!

1 个答案:

答案 0 :(得分:0)

这就是您如何通过dialogflow与firebase进行通信

const functions = require('firebase-functions');
const firebaseAdmin = require('firebase-admin');
const DialogflowApp = require('actions-on-google').DialogflowApp;

初始化Firebase Admin SDK。

firebaseAdmin.initializeApp(functions.config().firebase); 

在实现功能中与Firebase集合users进行交互

let userId = app.getUser().userId;
admin.firestore().collection('users').where('userId', '==', userId).limit(1).get()
.then(snapshot => {
      let user = snapshot.docs[0]
        if (!user) {
          // If user is not in DB, its their first time, Welcome them!
          app.ask('Welcome to my app for the first time!');
          // Add the user to DB
          firebaseAdmin.firestore().collection('users').add({
            userId: userId
          }).then(ref => {
              console.log('Added document with ID: ', ref.id);
          });
        } else {
          // User in DB
          app.ask('Welcome back!')
        }    
      });
  }

  // Map function hanlder to Dialogflow's welcome intent action 'input.welcome'
  const actionMap = new Map('input.welcome', start)
  app.handleRequest(actionMap);