How to create an AI-powered Slack bot
Imagine working in a large organization with thousands of employees across multiple continents. Onboarding challenges become apparent when you’re added to the company Slack workspace - hundreds of channels and thousands of users create an overwhelming environment. An AI-powered Slack bot solves this problem by serving as a dedicated company assistant, available 24/7. This guide demonstrates how to integrate ChatGPT functionality into your Slack workspace.
Setup and Preparation
Installing Heroku CLI
The Slack app will use Bolt for JavaScript and OpenAI, with deployment to Heroku. First, install the Heroku CLI.
For Mac:
brew tap heroku/brew && brew install heroku
For Ubuntu:
sudo snap install --classic heroku
Log in and create a new app:
heroku login
heroku create
Note your app ID (example: stark-brushlands-55983).
Git Repositories
Option 1: Heroku Git
cd my-project/
git init
heroku git:remote -a stark-brushlands-55983
Option 2: GitHub
Link your GitHub repository in the Heroku dashboard under Deploy section for automatic deployment synchronization.
Creating the Slack App
Visit Slack’s app creation page and create a new app from scratch.
Permissions
Navigate to Features > OAuth & Permissions and add Bot Token Scopes:
app_mentions:readchat:writechannels:history
Install the app to your workspace and set the bot token in Heroku:
heroku config:set SLACK_BOT_TOKEN=xoxb-<oauth-token> -a stark-brushlands-55983
Socket Mode
Generate an App Token in Settings > Basic Information under App-Level Tokens with connections:write scope:
heroku config:set SLACK_APP_TOKEN=xapp-<app-token> -a stark-brushlands-55983
Enable Socket Mode in Settings > Socket Mode.
Event Subscriptions
Enable Events Subscriptions and add these bot events:
app_mentionmessage.channels
App Development
Packages and Git Setup
Initialize the project and install dependencies:
npm init
npm install @slack/bolt openai
Update package.json scripts:
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
Create .gitignore:
node_modules/
package-lock.json
.env
Commit initial files:
git add -A
git commit -m "Setup project"
git push
Create Procfile (required for Socket Mode on Heroku):
worker: node index.js
Create boilerplate index.js:
const { App } = require("@slack/bolt");
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
appToken: process.env.SLACK_APP_TOKEN,
socketMode: true,
});
(async () => {
await app.start();
console.log('⚡️ Bolt app started');
})();
In Heroku Resources tab, ensure the worker dyno is activated.
Coding
Initialize OpenAI in index.js:
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
Add the OpenAI API key to Heroku:
heroku config:set OPENAI_API_KEY=sk-<api-key> -a stark-brushlands-55983
Handle app mentions with the app_mention event:
app.event('app_mention', async ({ event, context, client, say }) => {
const messages = [{ user: event.user, text: event.text }];
const response = await sendAiRequest(messages, context.botUserId);
await say({
channel: event.channel,
thread_ts: event.ts,
blocks: [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": response,
}
}
]
});
});
Create the sendAiRequest function:
const sendAiRequest = async (thread, botUserId) => {
const mentionPattern = new RegExp(`<@${botUserId}>`, 'g');
const messages = thread.map(message => {
const role = message.user === botUserId ? "assistant" : "user";
return { role, content: message.text.replace(mentionPattern, '').trim() };
});
messages.unshift({role: "system", content: "You are a Slack bot. Make sure to format your messages using mrkdwn syntax."})
const completion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: messages,
});
return completion.data.choices[0].message.content;
};
Handle thread replies with the message event:
app.event('message', async ({ event, context, say }) => {
if (event.channel_type !== 'channel' || !event.thread_ts || event.user === context.botUserId) {
return;
}
const thread = await app.client.conversations.replies({
channel: event.channel,
ts: event.thread_ts,
});
const response = await sendAiRequest(thread.messages, context.botUserId);
await say({
channel: event.channel,
thread_ts: event.thread_ts,
blocks: [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": response,
}
}
]
});
});
Commit and deploy:
git add -A
git commit -m "Add bot code"
git push
Testing
The bot now appears in the Apps section of Slack. Mention the bot and it will respond within seconds, tracking conversation threads for contextual replies.
Conclusion
This guide demonstrates setting up a Slack app with OpenAI integration and Heroku deployment. The bot leverages the vast potential of AI in streamlining day-to-day tasks while maintaining conversation context across Slack threads, providing practical workplace assistance.