Building an Intelligent Slack Chatbot with Dialogflow and GPT
Introduction
Over the past few years, conversational AI chatbots have become increasingly sophisticated and powerful tools for automating interactions and assisting users. By leveraging natural language processing (NLP) and machine learning (ML) techniques, today‘s chatbots can engage in lifelike conversations, understand user intents, and provide helpful information or perform actions.
Chatbots are especially valuable in the context of team collaboration software like Slack. Slack has become ubiquitous as a communication hub where work happens – it‘s where people chat, share files, manage tasks and projects. Enhancing Slack with an intelligent chatbot allows teams to be more productive by providing conversational interfaces to quickly access information, get assistance, and perform common tasks without leaving the chat interface.
In this post, we‘ll walk through how to build an intelligent chatbot for Slack using two powerhouse tools: Google‘s Dialogflow for natural language understanding, and OpenAI‘s GPT-3 for generating human-like responses. We‘ll create a bot that can engage in freeform conversations, understand intents and entities, respond dynamically using GPT, and provide a rich, interactive experience using Slack‘s Block Kit framework.
While Dialogflow provides an impressively easy way to create chatbots without any code, we‘ll go beyond that and build a custom integration using the Dialogflow and Slack APIs. This allows our bot to leverage the full power and flexibility of GPT to generate novel responses. And for an extra level of polish, we‘ll create a React app served by the bot to display information in rich, interactive formats.
Architecture Overview
At a high level, our intelligent Slack chatbot will consist of these key components:
- A Slack app with a bot user that can participate in conversations.
- A Dialogflow agent that defines the chatbot‘s conversational model, including intents, entities, and training phrases.
- Fulfillment for the Dialogflow agent using a custom integration powered by a Node.js server. This allows the bot to use the Dialogflow API to process incoming messages and identify intents and entities.
- Integration with the GPT-3 API (using the newly released gpt-3.5-turbo model) to generate intelligent, contextual responses based on the user‘s message and identified intents/entities.
- A React app served by the bot that can be displayed in Slack to provide visual, interactive elements using Slack‘s Block Kit.
Here‘s an architecture diagram showing how these pieces fit together:
[Architecture diagram showing Slack, Dialogflow, Node server, GPT-3, and React app]Now let‘s dive into building our bot step-by-step!
Step 1: Set Up a Slack App and Bot
First we need to create a new Slack app and bot user that will serve as the face of our chatbot in Slack.
-
Go to https://api.slack.com/apps and click "Create New App". Give your app a name and select the workspace where you want to install it.
-
On the left sidebar, go to "OAuth & Permissions" and add a new Bot Token Scope for "chat:write" to allow the bot to send messages.
-
On the "Bot Users" page, add a username and display name for your bot. This is how it will appear in Slack.
-
On the "Install App" page, install the app to your workspace. This will add the bot user to your workspace. Make note of the "Bot User OAuth Access Token", as you‘ll need this later to authenticate your bot with the Slack API.
Step 2: Create a Dialogflow Agent
Next, we‘ll create a new agent in Dialogflow that will define our chatbot‘s conversational model, including intents, entities, and training phrases.
-
Go to https://dialogflow.cloud.google.com/ and create a new agent. Give it a name that matches your Slack bot.
-
Create a new intent (eg. "Default Welcome Intent") and add some training phrases that your users might say to initiate a conversation with the bot, like "Hello", "Hi there", etc.
-
Add a response that you want your bot to reply with, e.g. "Hi there! I‘m an intelligent assistant powered by Dialogflow and GPT. How can I help you today?"
-
Create some additional custom intents to handle the key functions you want your bot to perform. For each intent, define the training phrases, any necessary parameters/entities, and sample responses. Some examples:
- Schedule meeting intent: "Set up a meeting with John tomorrow at 3pm"
- Team poll intent: "Create a poll asking where we should go for team lunch today"
- Project status intent: "What‘s the latest update on the Q2 budget project?"
-
Enable the "Small Talk" feature in the Dialogflow console and customize the responses to add some personality to your bot.
-
In the "Fulfillment" section, enable the Webhook option. We‘ll provide the URL for this later once we set up our Node.js server.
Step 3: Set Up a Node.js Server for Fulfillment
To enable our bot to respond intelligently using GPT-3, we need to set up a custom fulfillment server. We‘ll create a Node.js server using Express that will receive webhook requests from Dialogflow, call the GPT-3 API to generate a response, and send it back.
- Initialize a new Node project and install the necessary dependencies:
npm init
npm install express body-parser dialogflow openai
- Create a new file
server.jsand set up an Express server:
const express = require(‘express‘);
const bodyParser = require(‘body-parser‘);
const dialogflow = require(‘@google-cloud/dialogflow‘);
const openai = require(‘openai‘);
const app = express();
app.use(bodyParser.json());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Create a new POST route to handle webhook requests from Dialogflow:
app.post(‘/webhook‘, async (req, res) => {
const agent = new WebhookClient({ request: req, response: res });
let intentMap = new Map();
intentMap.set(‘Default Welcome Intent‘, welcome);
// Add mappings for other intents
agent.handleRequest(intentMap);
});
- Implement handler functions for each intent in the map above. Here‘s an example for the welcome intent that uses GPT-3 to generate a response:
async function welcome(agent) {
// Get the user‘s message from the Dialogflow request
const userMessage = agent.query;
// Call the GPT-3 API with the user‘s message as a prompt
const gptResponse = await openai.complete({
engine: ‘text-davinci-003‘,
prompt: `User: ${userMessage}\nAI:`,
maxTokens: 100,
n: 1,
stop: ‘\n‘,
});
// Extract the generated response from the GPT-3 API result
const responseText = gptResponse.data.choices[0].text.trim();
// Send the response back to Dialogflow
agent.add(responseText);
}
-
Don‘t forget to set your OpenAI API key using the environment variable
OPENAI_API_KEY. -
Run the server and make note of the public URL (you can use a tool like ngrok for local testing).
-
Go back to the Dialogflow console, and in the "Fulfillment" section, paste in the URL for the
/webhookroute on your server.
Step 4: Add Interactive Elements with Slack Block Kit
To make our chatbot more visually appealing and interactive, we can use Slack‘s Block Kit UI framework to display rich components like buttons, drop-down menus, datepickers, etc.
- In
server.js, add a new POST route to handle interactive payloads from Slack:
app.post(‘/interactive‘, async (req, res) => {
const payload = JSON.parse(req.body.payload);
// Handle button clicks, menu selections, etc.
if (payload.type === ‘block_actions‘) {
// Respond with an updated message
res.send({
"replace_original": "true",
"blocks": [
// Updated block with a confirmation of their selection
]
});
}
});
- Update the handler functions for your intents to include Block Kit components in the response, e.g.:
agent.add({
"blocks": [
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Which project do you want an update on?",
},
"accessory": {
"type": "static_select",
"placeholder": {
"type": "plain_text",
"text": "Select a project",
},
"options": [
{
"text": {
"type": "plain_text",
"text": "Q1 Budget",
},
"value": "q1-budget"
},
{
"text": {
"type": "plain_text",
"text": "Q2 Roadmap",
},
"value": "q2-roadmap"
}
]
}
}
]
});
Step 5: Building a React App for Rich Interactions
For even more interactive and dynamic Slack bot responses, we can build custom React apps that are served from our bot server.
- Create a new React app in your project:
npx create-react-app client
- In
server.js, serve the React app‘s static files:
const path = require(‘path‘);
app.use(express.static(path.join(__dirname, ‘client/build‘)));
app.get(‘*‘, (req, res) => {
res.sendFile(path.join(__dirname + ‘/client/build/index.html‘));
});
- Add a build script to your
package.jsonto build the React app:
"scripts": {
"build": "cd client && npm run build",
},
- Create a new React component that receives props from Slack (passed via URL params) and renders an interactive view, e.g.:
import React from ‘react‘;
function ProjectStatusView({ projectId }) {
// Fetch project status from API using projectId prop
// Render a pretty view with progress bars, stats, buttons, etc.
return (
<div>
{/* Project stats and interactive elements */}
</div>
);
}
- In your intent handlers in
server.js, generate a public URL to the React view and include it in the Slack response:
async function projectStatusIntent(agent) {
// Get selected project ID from Dialogflow parameters
const projectId = agent.parameters.projectId;
// Generate URL to React view
const viewUrl = `https://my-bot-server.com/project-status?projectId=${projectId}`;
agent.add({
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `Here‘s the latest status for project *${projectId}*:`
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View Project Status",
},
"value": "view_project",
"url": viewUrl
}
}
]
});
}
- Now when a user asks for a project status, they‘ll see a button that opens the pretty React view served by your bot!
Putting It All Together
With all the pieces in place, our intelligent Slack chatbot powered by Dialogflow and GPT-3 should now be able to:
- Engage in freeform conversations with users using Dialogflow‘s NLP to identify intents
- Generate contextual, human-like responses using the GPT-3 language model
- Display rich, interactive interfaces using Slack‘s Block Kit components
- Serve custom React apps for even more dynamic, interactive bot responses
Some potential enhancements and use cases to explore:
- Use Dialogflow slot filling to gather multiple parameters from the user (e.g. meeting title, date, time, attendees)
- Integrate with external APIs or databases to personalize responses (e.g. query a user‘s calendar to suggest meeting times)
- Generate reports, summaries, or even creative writing on demand using GPT-3
- Allow users to provide feedback to improve the model over time
- Implement access control and authorization flows to protect sensitive information or commands
The combination of Dialogflow‘s robust NLU, GPT-3‘s powerful language generation, and Slack‘s rich interactivity opens up near endless possibilities for building intelligent assistant bots for you and your team. I hope this guide gives you a solid foundation to start experimenting and building your own!