top of page
Search
  • Writer's pictureSenthil Pitchappan V

Creating a Chat-bot using Dialogflow

Dialogflow(formerly Api.ai, Speaktoit) is a Google-owned developer of human–computer interaction technologies based on natural language conversations. Which is used to create chatbot's and it can be embedded in your site or blog.


Dialog flow mainly works on 4 values or keywords

1. Agents

2. Intents

3. Entities

4. Fulfillments


Agents:

A Dialogflow agent is a virtual agent that handles conversations with your end-users. It is a natural language understanding module that understands the nuances of human language. Dialogflow translates end-user text or audio during a conversation to structured data that your apps and services can understand. You design and build a Dialogflow agent to handle the types of conversations required for your system.A Dialogflow agent is similar to a human call center agent. You train them both to handle expected conversation scenarios, and your training does not need to be overly explicit.


Intents:

An intent categorizes an end-user's intention for one conversation turn. For each agent, you define many intents, where your combined intents can handle a complete conversation. When an end-user writes or says something, referred to as an end-user expression, Dialogflow matches the end-user expression to the best intent in your agent. Matching an intent is also known as intent classification.


Entities:

Each intent parameter has a type, called the entity type, which dictates exactly how data from an end-user expression is extracted. Dialogflow provides predefined system entities that can match many common types of data. For example, there are system entities for matching dates, times, colors, email addresses, and so on. You can also create your own custom entities for matching custom data. For example, you could define a vegetable entity that can match the types of vegetables available for purchase with a grocery store agent.


Fulfillment:

When you enable fulfillment for an intent, Dialogflow responds to that intent by calling a service that you define. For example, if you want to schedule a bike repair to a near by shop. Fulfillment has the access to the owner's database where data can be give through the chatbot. Fulfillment is used to give extra features to your chatbot like linking data to database, firebase, google sheets, etc.

This Fulfillment can be given by 2 methods:

1. Webhooks

2. Inline Editor

Inline Editor is the best way to integrate in my case. It uses Java Script.


Here, I will guide you to create a Personal Details collector Chat bot and save the data in Firebase.

You can customize it according to your needs.


Step 1:

  • Go to Default Welcome intent

  • In Responses give -> "Hello, I am your Personal Data Collector. Good to See You! Lets Start..."


Step 2:

  • Create a new Intent SavetoDB

  • Enter you training Phrases like Sure, Hi, Save, Save to DB etc.

  • In Action and Parameters enter the following. (Make sure all the values are required only then you can create prompts which are nothing but questions

  • In Responses give as you wish, like thank you, It's a pleasure helping you! etc.

  • Most Important, make sure you have enabled "webhook call for this intent" which is under Fulfillment section.

  • And Save it.


Step 3:

  • Create another intent ReadfromDB to read data from DB

  • Enter Training Phrases like Read data, Read etc.

  • In action and parameters give a parameter called "name" which can be used to coral-ate with the database and print the data of that particular person

  • Most Important, make sure you have enabled "webhook call for this intent" which is under Fulfillment section.

  • And Save it.


As of now you Chatbot will work, but with no Database. Try how your chat bot works in the left most column.

After entering all the data, You will find the output something link this,



Step 4:

  • Go to Firebase and create and new Project and give it a name.

  • Create a Realtime database and make sure the rules are as shown

{ "rules": { ".read": true, ".write": true } }


  • Go to the data tab, you will find a link

https://yourprojectname.firebaseio.com/

  • This is a secret link for your database


Step 5:

  • In the left menu, choose Fulfillment

  • And enable Inline Editor

  • If you are unable to enable Inline Editor make sure you have a billing account for this project

  • This will be the code for "index.js"

'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); const {WebhookClient} = require('dialogflow-fulfillment'); const {Card, Suggestion} = require('dialogflow-fulfillment'); const nodemailer = require("nodemailer"); //for sending mails, its a npm package const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: ' ', //your mail ID pass: ' ' // gmail password } }); admin.initializeApp({ credential: admin.credential.applicationDefault(), databaseURL: 'ws://yourprojectname.firebaseio.com/' //make sure to add "ws" }); 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 handleSavetoDB(agent) { // this sent to obtain the value entered by the user name,email etc

const Name = agent.parameters.Name; const Email = agent.parameters.Email; const Phonenumber = agent.parameters.Phonenumber; const Address = agent.parameters.Address; const Admin_number = agent.parameters.Admin_number; const date = agent.parameters.date; const mailOptions = { //mailing options from: "ChatBot", // sender address to: Email, // list of receivers, his sent to obtain the value entered by the user name,email etc subject: "This is your Personal Data Collector Chat Bot", // Subject line html: `<h1> Hello ${Name} </h1> <p> Your name is ${Name} and your Phone Number is ${Phonenumber} and Email ID is ${Email} who lives is ${Address} with Registration number ${Admin_number}</p>` }; transporter.sendMail(mailOptions, function (err, info) { if(err) { console.log(err); } }); return admin.database().ref('data').child(Name).set ({ First_name: Name, Email: Email, Phonenumber: Phonenumber , Address: Address, Admin_number: Admin_number }); } function handlerReadFromDB(agent){ const name = agent.parameters.name; //for retriving data we use python promises return admin.database().ref('data').child(name).once('value').then((snapshot) => { const value1 = snapshot.child('First_name').val(); const value5 = snapshot.child('Email').val(); const value2 = snapshot.child('Phonenumber').val(); const value3 = snapshot.child('Address').val(); const value4 = snapshot.child('Admin_number').val(); if(value1 != null && value2!= null && value5!=null && value3!=null && value4!=null){ agent.add(`Your name is ${value1} and your Phone Number is ${value2} and Email ID is ${value5} who lives is ${value3} with Registration number ${value4}`); } });

//the above function coralates the name given by the user in DB and prints all the data. } let intentMap = new Map(); intentMap.set('Default Welcome Intent', welcome); intentMap.set('Default Fallback Intent', fallback); intentMap.set('SavetoDB', handleSavetoDB); intentMap.set('ReadfromDB', handlerReadFromDB); //intentMap.set('sendEmail', handlersendEmail); agent.handleRequest(intentMap); });


  • Most of the code will be present already.

  • Which ever intents are given by you, should be given a function like

intentMap.set('SavetoDB', handleSavetoDB); intentMap.set('ReadfromDB', handlerReadFromDB);

  • Next go to "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": "8" }, "scripts": { "start": "firebase serve --only functions:dialogflowFirebaseFulfillment", "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment" }, "dependencies": { "actions-on-google": "^2.2.0", "firebase-admin": "^5.13.1", "firebase-functions": "^2.0.2", "dialogflow": "^0.6.0", "dialogflow-fulfillment": "^0.5.0", "nodemailer":"6.3.1" //we will be adding only this line } }


  • nodemailer is a npm package which is used to send mails.



Step 6:

  • Now you can Deploy your chatbot, it will take some time depending on your internet speed.

  • Check how your bot works in the left most side.

  • As soon as you enter all the data, go to your firebase and check the data





Step 7:

  • Go to integrations in the right side menu.

  • Enable Web Demo to obtain a link your your chatbot.


If your not able to copy or understand the code...Click here



Congrats, you have completed your First Chat-Bot


You guys can ping me or call me if you face any issues...






79 views0 comments

Recent Posts

See All

Comments


bottom of page