DEV Community

Alex Bobes
Alex Bobes

Posted on

Create an Interactive AI Chatbot in Slack using Python and OpenAI API

This Python-based project will introduce you to the Slack API, OpenAI's GPT-3 API, and the Flask web framework. We'll create a command that allows users to interact with the bot using a simple /chatgpt command in Slack. After completing this tutorial, you'll have a fully functioning Slack bot capable of understanding natural language and providing intelligent responses.

Importing Required Libraries

In the first section we import all the required libraries that will be used in the application. These libraries allow us to interact with the filesystem, manage environment variables, create a web server, interact with the Slack API, handle threading, and interact with the OpenAI API.

# Import required libraries
import os
from dotenv import load_dotenv
from flask import Flask, render_template, request, jsonify
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_bolt.context.say import Say
from threading import Thread
import openai
Enter fullscreen mode Exit fullscreen mode

Loading Environment Variables

Here we load environment variables from a .env file. This is useful for managing sensitive information such as API keys and tokens, which we don't want to hardcode into our script.

# Load environment variables from a .env file
load_dotenv()
Enter fullscreen mode Exit fullscreen mode

Creating a Flask Application

We create a new instance of a Flask application. Flask is a lightweight web server framework in Python.

# Create a new Flask web server instance
app = Flask(__name__)
Enter fullscreen mode Exit fullscreen mode

Setting API Keys and Tokens

We retrieve the OpenAI API key, Slack Bot token, and Slack App token from the environment variables and set the OpenAI API key for the openai library.

# Load environment variables
api_key = os.environ.get('OPENAI_API_KEY')
SLACK_BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')
SLACK_APP_TOKEN = os.environ.get('SLACK_APP_TOKEN')

# Set the OpenAI API key
openai.api_key = api_key
Enter fullscreen mode Exit fullscreen mode

Creating a Slack App

We create a new Slack app using the bot token. This allows us to interact with the Slack API and listen for events.

# Create a new Slack app with the bot token
slack_app = App(token=SLACK_BOT_TOKEN)
Enter fullscreen mode Exit fullscreen mode

Defining a Command Handler

Here we define a command handler for the /chatgpt command in Slack. When a user types this command followed by a message, this function will be triggered. It acknowledges the command, extracts the message, sends the message to the OpenAI API, extracts the AI's response, and posts the user's message and the AI's response back to the channel.

# Define a command handler for the /chatgpt command
@slack_app.command("/chatgpt")
def command(ack, say, command):
    # Acknowledge the command right away
    ack()

    # Extract the user's message
    text = command['text']

    # Query the OpenAI API
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": text}
        ]
    )

    # Extract the AI's response
    response_text = response['choices'][0]['message']['content']

    # Post the user's message, the response, and a dashed line back to the same channel
    say(f"*User's message:* {text}\n*AI's response:* {response_text}\n----------------")
Enter fullscreen mode Exit fullscreen mode

Starting the Flask Application

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=3333)
Enter fullscreen mode Exit fullscreen mode

Setting up your Slack Bot

You'll need to create and configure your Slack bot. Here's how to do it:

Create a Slack App

Enable Bot Token Scopes

Navigate to "OAuth & Permissions" in the sidebar, then scroll down to "Bot Token Scopes". Here you need to add the required scopes for your bot. To read and write messages, you'll need the following scopes at a minimum:

  • app_mentions:read
  • channels:history
  • channels:read
  • chat:write
  • commands

Enable Socket Mode

Go to the "Socket Mode" section and enable it. This will allow your app to use the Socket Mode, which allows your app to receive events directly via a WebSocket connection. Copy the "App Level Token" (it starts with "xapp-").

Install the App

Navigate back to "OAuth & Permissions" and click "Install App to Workspace". Follow the prompts to authorize the bot in your workspace.

Retrieve Your Tokens

After installing the app, you'll be redirected back to the "OAuth & Permissions" page. Here, you'll see a section for "Tokens for Your Workspace". Copy the "Bot User OAuth Token" (it should start with "xoxb-") and the "App Level Token" (it should start with "xapp-"). You'll need these for your Python code.

Create a Slash Command

Click on "Slash Commands" in the sidebar, then "Create New Command". Enter /chatgpt as the command. Fill out the rest of the form and click "Save".

Update Your Python Code

In your Python code, replace SLACK_BOT_TOKEN, SLACK_APP_TOKEN and OPENAI_API_KEY with your actual tokens.

Invite the Bot to a Channel

Finally, go to your Slack workspace and invite your bot to a channel by adding him from the Integrations tab. Your bot should now be ready to respond to the /chatgpt command.

Running the Script in Production with PM2

PM2 is a powerful, feature-rich process manager in Node.js. It allows you to keep your applications running forever, reloads them without downtime, helps in the administration of your application's logs, and much more.

First, you'll need to have Node.js and npm (Node Package Manager) installed on your system. Once you have Node.js and npm installed, you can install PM2 using npm:

npm install -g pm2

Enter fullscreen mode Exit fullscreen mode

Start Your Application with PM2

To start your application with PM2, navigate to your project directory in the terminal and run:

pm2 start app.py --name gpt-3-slack-bot --interpreter python3

Enter fullscreen mode Exit fullscreen mode

You're now running your Flask application in a production environment with PM2. Your application will be automatically restarted if it crashes and will also be started when your system reboots.

GitHub Repo: https://github.com/alexbobes/chatgpt-slack-bot

And that's it! You now have a fully functioning AI chatbot integrated with your Slack workspace, all powered by OpenAI's GPT-3 model (or GPT-4 you have access to it).

I hope you found this tutorial helpful. If you have any questions, comments, or suggestions, feel free to leave them below.

Thanks for reading, and happy coding!

Top comments (1)

Collapse
 
iamhectorsosa profile image
Hector Sosa

This is great stuff! I also wrote a Slack bot last year but using TypeScript! Not sure why your code blocks aren't highlighted? This helps with readability. Hopefully dev.to has syntax highlighting available for Python.

Otherwise a you could use screenshots of the code blocks, if so I've created a simple OSS tool to help with this. Check it out and let me know what you think. github.com/ekqt/screenshot if you find it helpful, I'd appreciate a star. Cheers!