Hi there! I’m Alex Bobes, a tech enthusiast and CTO, currently in my second decade of tinkering with technology, unmasking the complexities of codes, and occasionally getting my fingers burned on the searing iron of innovation. But today, I’m not here to talk about my battle scars; instead, I want to take you through a captivating journey of building a Slack chatbot that seamlessly integrates with the OpenAI API. Sounds intriguing, right? Let’s dive in.
First, let me tell you why we’re doing this. Slack is a fantastic platform that has revolutionized workplace communication. It’s a hub for your team, where conversations, ideas, and workflows organically spring and grow. Now, imagine enriching this already powerful tool with the capability of AI through OpenAI’s GPT-3 This could mean automated responses, smarter task management, personalized messages, and so much more!
Step1: Get Your Tools Ready
You’ll need a few things before we get started. Make sure you have:
- A Slack account with administrative privileges
- An OpenAI API key
- Basic knowledge of Python and JavaScript
Also, ensure you have the necessary software installed, such as Node.js and Ngrok (for local development and testing), along with Python’s slack_sdk
and openai
libraries.
Step 2: Create a Slack App
To build a chatbot, we first need to create a Slack app. It’s simple: go to the Slack API website, navigate to “Your Apps”, and click on “Create New App”. Fill in the details like App Name and the workspace where you’ll be developing the app. Once done, you’ll get your “App ID” and “Client ID“, which we’ll need later.
Step 3: Configure Interactive Components
We want our chatbot to be interactive, responsive, and dynamic – essentially to feel alive! For that, we’ll need to dip our toes into the “Interactive Components” section of our Slack app settings.
On arriving in the section, you’ll notice a switch marked “Interactivity“. Flip it on. With this, we are essentially empowering our chatbot to start reacting to user input beyond simple text-based commands.
Next, we’re faced with the field marked “Request URL“. This is where we tell our app where to send all the payload information when an interactive component is used within our app. For those of us playing at home or on a local server, you might be wondering how to set up a URL. Don’t worry, I’ve got your back.
Ngrok is an excellent tool to help us here. When you run Ngrok on your local machine, it provides a unique URL that’s routed straight back to your computer. So, install Ngrok, and run it on the same port as your local server. Grab the URL that Ngrok provides (it’ll be something like https://abc123.ngrok.io
) and paste it into the “Request URL” field.
Bear in mind that every time you restart Ngrok, you’ll get a new URL, so you might need to update this field in your app settings periodically if you’re doing a lot of testing and development.
Once that’s set up, you’re ready to add some interaction options. In the section “Action Blocks”, click on “Add New Action”. Here, you can configure various interactive components like buttons, select menus, date pickers, and more. Each interactive component will have an “Action ID” that will be included in the payload sent to your Request URL when the component is used. This allows your app to know which component was interacted with and act accordingly.
With interactive components properly configured, your bot is now equipped to have dynamic interactions with users. It’s not just a bot anymore; it’s a tool, a companion, an integral part of your team. Let’s keep moving!
Step 4: Event Subscriptions
Event subscriptions are the lifeblood of your chatbot. They enable it to spring into action when something happens in your Slack workspace. This ‘something’ could be a user mentioning the bot, a new message in a channel, a reaction added – anything that you specify.
To start off, let’s navigate to the “Event Subscriptions” section in your app settings. Here, we’ll find another switch to flip – “Enable Events“. When we do this, our chatbot gains a keen ear, ready to respond to specific triggers.
Next up is the “Request URL” field, which might look familiar. Just like with interactive components, you’ll need to provide a URL where the event payloads can be sent when they occur. If you’re working on a local server, this is another chance for Ngrok to shine. Simply use the same URL you used for configuring the interactive components.
Upon entering your Request URL, Slack will send a challenge request to confirm that your server is ready to receive events. Make sure your server is set up to accept POST requests at the specified path, and respond with the challenge parameter. Once that’s done, you should see a green “Verified” label.
Now comes the exciting part – choosing the events our bot will listen to. In the “Subscribe to Bot Events” section, you’ll find a “Add Bot User Event” button. Click it, and you’ll be presented with a smorgasbord of events that you can subscribe to.
Here’s a pro tip: subscribing to message.channels
event is a good start, as it will allow your bot to listen to messages in public channels. If you want your bot to listen to direct messages or private channels, consider adding message.im
and message.groups
respectively. To ensure that your bot springs into action when mentioned, don’t forget to add the app_mention
event.
Remember, every time you add a new event, your app needs to be reinstalled to your workspace for the changes to take effect. But, after this is done, your bot is now all ears, ready and waiting for events to respond to. Your Slack workspace is starting to feel a little smarter already, isn’t it?
Step 5: Permissions
The permissions step is a crucial one, primarily because it sets the boundaries of what our bot can and can’t do. Let’s consider it the rulebook for our bot’s behavior. With well-configured permissions, your bot can coexist harmoniously within your workspace without overstepping its bounds.
To get started, head on over to the “OAuth & Permissions” section in your app settings. Here, you’ll see the “Scopes” section, which is basically the list of permissions that your app requests.
Scopes come in two flavors: user scopes and bot scopes. User scopes outline what the app can do on behalf of users, such as read their profile information or post messages as them. Bot scopes, on the other hand, determine what the app can do as the bot user itself.
As our focus is building a chatbot, we’ll be dealing mainly with bot scopes. Click “Add an OAuth Scope” under the “Bot Token Scopes” section. Here, you’ll find a vast array of permissions that you can request.
A good starting point is to add chat:write
which allows your bot to send messages, and app_mentions:read
which allows your bot to read messages where it has been @mentioned. If you want your bot to react to messages, you can also add reactions:write
.
Keep in mind that the principle of least privilege should guide us while setting up these permissions – your bot should have just enough permissions to perform its functions, but no more. This is a good practice to ensure the security and privacy of your workspace.
Once you’ve added all the necessary scopes, scroll up to the top of the page and click “Install App to Workspace“. You’ll need to reinstall your app every time you change scopes to ensure the new permissions take effect.
Lastly, you’ll see an “OAuth Tokens & Redirect URLs” section, where you’ll find the “Bot User OAuth Access Token“. Store this token securely as you’ll need it to authenticate your bot’s interactions with the Slack API.
Well, there you have it! Your bot now knows its boundaries and is ready to respect them. With this, we’ve ensured that our bot will be a responsible member of our Slack workspace. Now, let’s move on to the next step.
Step 6: Write the Bot Code
Now, we’ll write the code for our bot. We’ll use Node.js for handling Slack events and Python for communicating with OpenAI’s API. Remember, we’ll have two parts: one to handle Slack events and another to process user messages and respond using OpenAI’s API.
A typical interaction could look like this:
const { WebClient, App } = require("@slack/bolt");
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET
});
app.event("app_mention", async ({ event, client }) => {
try {
const result = await client.chat.postMessage({
channel: event.channel,
text: `<@${event.user}>`, // this is a placeholder. We'll replace it soon.
});
console.log(result);
}
catch (error) {
console.error(error);
}
});
(async () => {
await app.start(process.env.PORT || 3000);
console.log('⚡️ Bolt app is running!');
})();
In the above code, our bot listens for app_mention
events and sends a message mentioning the user back. But instead of just mentioning the user back, let’s make it smarter using OpenAI’s API.
import os
import openai
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
slack_token = os.getenv("SLACK_API_TOKEN")
openai_key = os.getenv("OPENAI_API_KEY")
client = WebClient(token=slack_token)
openai.api_key = openai_key
def respond_to_message(event):
conversation_id = event['channel']
user_message = event['text']
# Generate a response using OpenAI
openai_response = openai.Completion.create(
engine="text-davinci-003",
prompt=user_message,
temperature=0.5,
max_tokens=150
)
# Send the OpenAI response back to Slack
try:
response = client.chat_postMessage(
channel=conversation_id,
text=openai_response.choices[0].text.strip()
)
except SlackApiError as e:
assert e.response["ok"] is False
assert e.response["error"]
print(f"Got an error: {e.response['error']}")
The respond_to_message
function takes a Slack event (which contains the user’s message), uses the OpenAI API to generate a response, and sends that response back to Slack.
Step 7: Deploy
With the bot code ready, you’re good to go. If you’ve been developing locally, now’s the time to deploy your bot to a server. You can use services like Heroku or AWS for deployment. Remember to update the Request URL in your Slack app settings.
And voila! You’ve built your own Slack chatbot that communicates with the OpenAI API. You can now enjoy engaging, contextually appropriate, and dynamic interactions within your Slack workspace.
Building a Slack chatbot that leverages OpenAI can seem daunting initially. But as we’ve just seen, it’s a manageable task, broken down into straightforward steps. It’s a fascinating experience, and the result is nothing short of extraordinary.
I’m thrilled to have shared this journey with you, and I look forward to the innovative ways you’ll use this knowledge. Until next time, happy coding!