Reub
Reub

Reputation: 785

dialogflow to interact with firebase realtime database

Is it possible to get some data from firebase database by using dialogflow? I'm new to dialogflow so I'm still doing some research about.

For example, I want to ask my chatbot if a doctor is available then chatbot will access the firebase db to check if that specific doctor is available or lets say schedule me an appoint with doc X so dialogflow will do a function that allow will enter a schedule object to the database

thanks.

Upvotes: 2

Views: 7925

Answers (1)

mattcarrollcode
mattcarrollcode

Reputation: 3469

You can use Firebase function to fulfill your Dialogflow agent and the Firestore database to store data. An example of how to do so with Dialogflow's Google Assistant integration is below:

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

// Initialize Firebase Admin SDK.
firebaseAdmin.initializeApp(functions.config().firebase); 

exports.dialogflowFulfillment = functions.https.onRequest((req, res) => {
  // Log headers and body
  console.log('Request headers: ' + JSON.stringify(req.headers));
  console.log('Request body: ' + JSON.stringify(req.body));

  // Create a new Dialgoflow app request handler
  let app = new DialogflowApp({request: req, response: res});

  // welcome function handler
  function start(app) {
      // Get user ID from the Google Assistant through Action on Google
      let userId = app.getUser().userId;
      // Check if the user is in our DB
      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);
});

Upvotes: 2

Related Questions