Build Your Own Chatbot with Dialogflow

Chatbots have become increasingly popular in recent years as they provide a convenient way to interact with users. They can be used for a variety of purposes, including customer service, sales, and information retrieval. Chatbots can also be integrated with other applications and platforms, making them a valuable asset for businesses and developers alike.

In this tutorial, we will be using Dialogflow, a natural language understanding platform developed by Google, to build a custom chatbot. Dialogflow provides a user-friendly interface for building conversational interfaces and is powered by machine learning algorithms that enable it to understand natural language.

Prerequisites

Before we can start building our chatbot, we need to ensure that we have the necessary tools and resources. Here are the prerequisites for this tutorial:

  • A Google account
  • A basic understanding of JavasScript
  • Familiarity with Node.js and npm
  • A text editor/IDE (e.g. Visual Studio Code)

Step 1: Setting up Dialogflow

The first step is to create a new Dialogflow agent. An agent is the conversational interface that you will be building. To create a new agent, follow these steps:

  1. Go to the Dialogflow Console.
  2. Click on the Create Agent button.
  3. Enter a name for your agent and select the default language and time zone.
  4. Choose the Standard edition for your agent.
  5. Click on the Create button to create your agent.

Step 2: Creating Intents

An intent represents an action that the user wants to perform or the information that they want to retrieve. For example, if the user asks for the weather, the intent would be to retrieve weather information. In Dialogflow, you can create intents that represent these actions.

To create an intent, follow these steps:

  1. Click on the Intents option from the left-hand menu.
  2. Click on the Create Intent button.
  3. Enter a name for your intent (e.g. “Weather”).
  4. Enter some sample user phrases in the Training Phrases section that represent the intent. For example, “What is the weather like today?”, “Give me the weather forecast”, etc.
  5. In the Action section, you can enter the action that should be triggered when the intent is detected. For now, leave this field blank.
  6. In the Responses section, you can enter the responses that the chatbot should provide when the intent is detected. For example, “The current temperature in New York is 80ยฐF”.
  7. Click on the Save button to save your intent.

Step 3: Enabling Small Talk

Small talk is a collection of pre-built intents that can be used to engage with users in a more conversational way. Dialogflow provides a variety of pre-built small talk intents that can be enabled with just a few clicks.

To enable small talk, follow these steps:

  1. Click on the Prebuilt Agents option from the left-hand menu.
  2. In the Small Talk section, click on the Enable button.
  3. Click on the Save button to save your changes.

Step 4: Integration with Node.js

Now that we have created our agent and defined our intents, we need to integrate our agent with Node.js to build a functioning chatbot. We will be using the dialogflow package, which is the official Dialogflow client library for Node.js.

To get started, create a new Node.js project and install the dialogflow package:

npm init
npm install dialogflow

Next, create a new file named index.js and add the following code:

const dialogflow = require('dialogflow');
const projectId = 'YOUR_PROJECT_ID_HERE';
const sessionId = '123456';
const languageCode = 'en-US';

const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

const request = {
  session: sessionPath,
  queryInput: {
    text: {
      text: 'Hello!',
      languageCode: languageCode,
    },
  },
};

sessionClient.detectIntent(request).then(responses => {
  console.log('Detected intent');
  const result = responses[0].queryResult;
  console.log(result);
}).catch(err => {
  console.error('ERROR:', err);
});

Replace YOUR_PROJECT_ID_HERE with your actual Dialogflow project ID.

This code creates a new session client that represents a conversation between the user and the chatbot. It then sends a message to Dialogflow (“Hello!”), which is processed by the agent and returns a response. The response is then logged to the console.

To run this code, use the following command:

node index.js

You should see the response from Dialogflow in the console.

Step 5: Integrating with a Messaging Platform

Now that we have successfully integrated our agent with Node.js, we can integrate it with a messaging platform to create a functioning chatbot. For the purposes of this tutorial, we will be using Facebook Messenger as our messaging platform.

To get started, we need to create a Facebook page and an app:

  1. Go to the Facebook Developer Portal.
  2. Create a new Facebook page if you haven’t already.
  3. Create a new Facebook app by clicking on the Add a New App button.
  4. Follow the steps to create a new app (you will need to provide some basic information about your app).
  5. Once your app is created, go to the Messenger tab and click on the Setup Webhooks button.

Next, we need to configure our app to communicate with our Dialogflow agent:

  1. Set the Callback URL to https://YOUR_APP_URL/webhook` (replaceYOUR_APP_URL` with the URL for your app).
  2. Enter a Verify Token of your choice (this can be any string).
  3. Select the messages and messaging_postbacks webhook subscriptions.
  4. Click on the Verify and Save button to save your changes.

Now, we need to create a new file named app.js and add the following code:

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const {WebhookClient} = require('dialogflow-fulfillment');

const app = express();

const PORT = process.env.PORT || 3000;
const PAGE_ACCESS_TOKEN = 'YOUR_PAGE_ACCESS_TOKEN_HERE';
const VERIFY_TOKEN = 'YOUR_VERIFY_TOKEN_HERE';
const DIALOGFLOW_PROJECT_ID = 'YOUR_DIALOGFLOW_PROJECT_ID';
const DIALOGFLOW_LANGUAGE_CODE = 'en-US';
const SESSION_ID = 'myfacebookbot';

app.use(bodyParser.json({ verify: verifyRequestSignature }));

function verifyRequestSignature(req, res, buf) {
  const signature = req.headers['x-hub-signature'];

  if (!signature) {
    throw new Error('Couldn't validate the signature.');
  }

  const [hashAlgorithm, hash] = signature.split('=');

  const expectedHash = crypto.createHmac(hashAlgorithm, PAGE_ACCESS_TOKEN)
    .update(buf)
    .digest('hex');

  if (hash !== expectedHash) {
    throw new Error('Invalid signature - expected ' + expectedHash + ' but got ' + hash);
  }
}

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.get('/webhook', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === VERIFY_TOKEN) {
    console.log('Webhook verified!');
    res.status(200).send(req.query['hub.challenge']);
  } else {
    console.error('Webhook verification failed.');
    res.sendStatus(403);
  }
});

app.post('/webhook', (req, res) => {
  const webhookClient = new WebhookClient({ request: req, response: res });

  function welcome(agent) {
    agent.add(`Welcome to my messenger bot!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  function detectIntent(agent) {
    const projectId = DIALOGFLOW_PROJECT_ID;
    const languageCode = DIALOGFLOW_LANGUAGE_CODE;

    const sessionPath = webhookClient.sessionPath(projectId, SESSION_ID);
    const query = agent.query;

    const request = {
      session: sessionPath,
      queryInput: {
        text: {
          text: query,
          languageCode: languageCode,
        },
      },
    };

    return webhookClient.detectIntent(request);
  }

  function handleResponse(agent) {
    const result = agent.result;
    const fulfillmentText = result.fulfillmentText;

    agent.add(fulfillmentText);
  }

  const intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set(null, detectIntent);
  intentMap.set(null, handleResponse);

  webhookClient.handleRequest(intentMap);
});

app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
});

Replace YOUR_PAGE_ACCESS_TOKEN_HERE with your actual Facebook page access token, YOUR_VERIFY_TOKEN_HERE with your verify token, and YOUR_DIALOGFLOW_PROJECT_ID with your actual Dialogflow project ID.

This code creates an Express app that listens to incoming requests on the /webhook endpoint. It also includes handlers for the welcome and fallback intents and a detectIntent function, which sends the user’s message to Dialogflow and returns the resulting intent.

To run this code, use the following command:

node app.js

After running the server, you should see the message “App listening on port 3000” in the console.

Conclusion

In this tutorial, we have covered the basics of building a custom chatbot using Dialogflow and integrating it with Node.js and a messaging platform like Facebook Messenger. While this tutorial only scratches the surface of what is possible with Dialogflow, it should give you a good foundation to start building your own chatbots. With its powerful natural language processing capabilities and user-friendly interface, Dialogflow is an excellent choice for building conversational interfaces that can improve user engagement and ultimately drive business results.

Related Post