Building Smart Chatbots with Dialogflow

Muhammad Usman
3 min readJun 21, 2024

--

Seamless Chatbot Integration with Dialogflow: A Step-by-Step Guide

Image taken from https://www.ismartrecruit.com/

Integrating a chatbot using Dialogflow involves creating and configuring a Dialogflow agent, setting up webhooks if needed, and embedding the chatbot in your web application.

Image taken from Google

Here’s a step-by-step guide to help you achieve this:

Step 1: Create and Configure a Dialogflow Agent

  1. Create a Dialogflow Account:

2. Create a New Agent:

  • Click on “Create Agent.”
  • Provide a name for your agent.
  • Select the desired Google Project or create a new one.
  • Click “Create.”

3. Define Intents:

  • Intents represent what the user says and how the agent responds.
  • Create intents for different user queries.
  • Add training phrases to train the agent on how to recognize user inputs.

4. Add Responses:

  • Define responses for each intent to specify what the chatbot should reply with.

5. Set Up Fulfillment (Optional):

  • If you need dynamic responses or actions, enable and set up webhooks in the Fulfillment section.

Note: You can also follow the steps here with screenshot.

Step 2: Integrate Dialogflow with Your Web Application

  1. Get Dialogflow API Credentials:
  • In the Dialogflow Console, go to the settings of your agent.
  • Navigate to the “Service Account” section and click on the project ID link.
  • This will take you to the Google Cloud Console.
  • Create a new service account and download the JSON key file.

2. Install Required Libraries:

Install the Dialogflow library in your project:

npm install dialogflow

3. Create a Server to Handle Requests:

  • Set up a Node.js server to handle communication between the web client and Dialogflow.
// server.js
const express = require('express');
const bodyParser = require('body-parser');

const dialogflow = require('@google-cloud/dialogflow');
const cors = require('cors');
const uuid = require('uuid');

const app = express();
const port = 3000;

app.use(bodyParser.json());
app.use(cors());

const projectId = 'fir-app-8aeed';
const sessionId = uuid.v4();
const languageCode = 'en';

const sessionClient = new dialogflow.SessionsClient({
keyFilename: 'fir-app-8aeed-150a8660469f.json'
});

app.post('/query', async (req, res) => {
const text = req.body.text;
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);

const request = {
session: sessionPath,
queryInput: {
text: {
text,
languageCode,
},
},
};
// Example response
const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
res.json({ fulfillmentText: result.fulfillmentText });
});

app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

4. Integrate the Chatbot on the Frontend:

  • Use HTML and JavaScript to create a simple chatbot interface and communicate with the backend server.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chatbot</title>
<style>
#chat {
border: 1px solid #ccc;
padding: 10px;
width: 300px;
height: 400px;
overflow-y: auto;
}
#input {
width: calc(100% - 22px);
margin: 10px 0;
padding: 10px;
}
</style>
</head>
<body>
<div id="chat"></div>
<input type="text" id="input" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>

<script>
function sendMessage() {
const input = document.getElementById('input');
const message = input.value;
if (message.trim() === '') return;

const chat = document.getElementById('chat');
chat.innerHTML += `<div><strong>You:</strong> ${message}</div>`;
input.value = '';

fetch('http://localhost:3000/query', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: message }),
})
.then(response => response.json())
.then(data => {
chat.innerHTML += `<div><strong>Bot:</strong> ${data.fulfillmentText}</div>`;
chat.scrollTop = chat.scrollHeight;
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
</body>
</html>
User Interface with Dialogflow Integration

Summary

  1. Create and configure a Dialogflow agent with intents and responses.
  2. Set up a Node.js server to handle requests and communicate with Dialogflow.
  3. Create a simple frontend interface to interact with the chatbot.

This setup allows you to integrate a Dialogflow chatbot into your web application, enhancing user interaction with AI-driven conversational capabilities.

--

--

Muhammad Usman
Muhammad Usman

No responses yet