Google Dialogflow Chatbot & Realtime Database Tutorial: Read & Write Data

I published a tutorial video on how to read from and write to the Firebase Realtime Database using snapshots and transactions. This blog post contains the code examples from the video:

Here is the index.js for the first step which is just reading from the database using a snapshot:

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');

// initialise DB connection
const admin = require('firebase-admin');
admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: 'ws://saveaverageage.firebaseio.com/',
});

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

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 handleAge(agent) {
    const age = agent.parameters.age;

    agent.add(`Thank you...`);

    return admin.database().ref('ageInfo').once("value").then((snapshot) => {
      var averageAge = snapshot.child("runningAverage").val();
      agent.add(`Our recorded average age is ` + averageAge);
    });
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('AskAge', handleAge);
  agent.handleRequest(intentMap);
});

Next we have the index.js for the second step where I read from and write to the Realtime Database using a transaction:

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');

// initialise DB connection
const admin = require('firebase-admin');
admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: 'ws://saveaverageage.firebaseio.com/',
});

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

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 handleAge(agent) {
    const age = agent.parameters.age;

    agent.add(`Thank you...`);

    return admin.database().ref('ageInfo').transaction((ageInfo) => {
      if(ageInfo !== null) {
        let oldAverage = ageInfo.runningAverage;
        let oldTotalCount = ageInfo.totalCount;
        let newAverage = (oldAverage * oldTotalCount + age) / (oldTotalCount + 1);
        ageInfo.runningAverage = newAverage;
        ageInfo.totalCount+=1;
        agent.add(`Our recorded average age is ` + newAverage);
      }
      return ageInfo;
    }, function(error, isSuccess) {
      console.log('Update average age transaction success: ' + isSuccess);
    });

  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('AskAge', handleAge);
  agent.handleRequest(intentMap);
});

For completeness, here is also theĀ package.json:


{
  "name": "dialogflowFirebaseFulfillment",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "~6.0"
  },
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
  },
  "dependencies": {
    "actions-on-google": "2.0.0-alpha.4",
    "firebase-admin": "^4.2.1",
    "firebase-functions": "^0.5.7",
    "dialogflow": "^0.1.0",
    "dialogflow-fulfillment": "0.3.0-beta.3"
  }
}
  • Billy de Fretes

    love this tutorial, i hope you add more so i can learn from you

  • Weerapat Lokatekrawee

    Is it possible to do the loop for NoSql and connect to dialogflow cause I can’t retrieve answers from realtime database?
    Here is my email: earn32578@gmail.com
    Thanks