Search code examples
node.jschatbotdialogflow-es-fulfillmentkommunicate

How to receive data in DialogFlow sent from Kommunicate?


I am creating a chatbot for my website. So, I am using DialogFlow and Kommunicate.io for the same. I added a script given by kommunicate in my html file. For sending custom data from html page to the bot, we use chatContext variable in the "onInit" function but I am not able to get how to use that data in my dialogflow bot. This is my kommunicate script :

(function(d, m){
        var kommunicateSettings = {"appId":"7519ee060abee2b532e8565aa0527aed","popupWidget":true,"automaticChatOpenOnNavigation":true, 
                "title": "test",
                 "appSettings": {
                        "chatWidget": {
                          "popup": true,           // To enable or disable the pre-chat popup (boolean)
                          //"emojilibrary" : true
                        },
                        "chatPopupMessage": [{
                          "message": "Wanna ask something related to "+document.title+ "?", // Message to be displayed in the pre-chat popup (string)
                          "delay": 3000                    // Delay interval of pre-chat popup (number in milliseconds)
                        }],
                 },
                 "onInit" : function(){
                     var chatContext = {
                      "lat":"Latitude° N",
                      "lon":"Longitude° E"
                    }
                    Kommunicate.updateChatContext(chatContext);
                 }
        };

        var s = document.createElement("script"); s.type = "text/javascript"; s.async = true;
        s.src = "https://widget.kommunicate.io/v2/kommunicate.app";
        var h = document.getElementsByTagName("head")[0]; h.appendChild(s);
        window.kommunicate = m; m._globals = kommunicateSettings;
      })(document, window.kommunicate || {});

And this is my DialogFlow code :

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const {Payload} =require('dialogflow-fulfillment');
const i18n= require('i18n');
const express=require('express');
var router=express.Router();

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 fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  function About(agent){
    agent.add(`We are a company!`);
  }

  // // Uncomment and edit to make your own intent handler
  // // uncomment `intentMap.set('your intent name here', yourFunctionHandler);`
  // // below to get this function to be run when a Dialogflow intent is matched
  // function yourFunctionHandler(agent) {
  //   agent.add(`This message is from Dialogflow's Cloud Functions for Firebase editor!`);
  //   agent.add(new Card({
  //       title: `Title: this is a card title`,
  //       imageUrl: 'https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png',
  //       text: `This is the body text of a card.  You can even use line\n  breaks and emoji! 💁`,
  //       buttonText: 'This is a button',
  //       buttonUrl: 'https://assistant.google.com/'
  //     })
  //   );
  //   agent.add(new Suggestion(`Quick Reply`));
  //   agent.add(new Suggestion(`Suggestion`));
  //   agent.setContext({ name: 'weather', lifespan: 2, parameters: { city: 'Rome' }});
  // }

  // // Uncomment and edit to make your own Google Assistant intent handler
  // // uncomment `intentMap.set('your intent name here', googleAssistantHandler);`
  // // below to get this function to be run when a Dialogflow intent is matched
  // function googleAssistantHandler(agent) {
  //   let conv = agent.conv(); // Get Actions on Google library conv instance
  //   conv.ask('Hello from the Actions on Google client library!') // Use Actions on Google library
  //   agent.add(conv); // Add Actions on Google library responses to your agent's response
  // }
  // // See https://github.com/dialogflow/fulfillment-actions-library-nodejs
  // // for a complete Dialogflow fulfillment library Actions on Google client library v2 integration sample

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
   intentMap.set('About the company', About);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

I want to show "lat" and "lon" in my welcome message.


Solution

  • The Data you pass in chatContext object from Kommunicate chat widget can be access from your fulfillment code. This data is available in request object as part of originalDetectIntentRequest parameter.

    This is the example:

    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));
    
      console.log('Data passed as chatContext from Kommunicate is: ' +  JSON.stringify(request.body.originalDetectIntentRequest)  );
    
       .
       .
       .
       .
       .
    
    
    });