Building a Simple Slack Bot backed by OpenAI to Answer Questions

Introduction:

Slack AI Bot code

Slack bots have gained significant popularity due to their ability to enhance communication and boost productivity within teams. Here are some key reasons behind their popularity:

1. Automation of Tasks: Slack bots can automate routine tasks, such as sending reminders, scheduling meetings, or fetching information from external systems. This automation saves time and reduces manual effort, allowing team members to focus on more important work.

2. Real-Time Collaboration: Bots in Slack enable real-time collaboration by facilitating quick information sharing and interaction. They can provide notifications, updates, and alerts to keep teams informed and aligned. This instant communication fosters a sense of teamwork and improves overall efficiency.

3. Streamlined Workflows: By integrating with various tools and services, Slack bots can streamline workflows and centralize information. They can gather data from different sources, perform actions, and provide consolidated updates within the Slack platform. This streamlining minimizes context switching and enables smoother collaboration.

4. Enhanced Accessibility: Bots make information readily accessible within Slack channels, making it easier for team members to find and retrieve relevant data. Bots can search through knowledge bases, provide quick answers to FAQs, or fetch specific information from databases. This accessibility empowers users to retrieve information without leaving the Slack environment.

5. Customization and Personalization: Slack bots can be customized to meet specific team needs. They can be configured to deliver personalized notifications, reminders, or tailored responses based on individual preferences. This customization helps teams optimize their workflow and adapt the bot to their unique requirements.

6. Integration with External Services: Slack bots can integrate with a wide range of external services, such as project management tools, customer support systems, or analytics platforms. This integration allows teams to access and interact with multiple systems from a single interface, reducing the need to switch between different applications.

Overall, Slack bots offer a powerful way to streamline communication, automate tasks, and improve collaboration within teams. Their versatility and ability to integrate with various tools make them valuable assets for enhancing productivity and efficiency in the workplace.

Using OpenAI, a powerful language model developed by OpenAI, in the development of a Slack bot allows for the creation of an intelligent question-answering bot. OpenAI's advanced language understanding and generation capabilities enable it to comprehend natural language queries and provide accurate and coherent responses. Integrating OpenAI into a Slack bot enhances communication and productivity by offering instant and intelligent answers to questions. The bot can retrieve information, provide explanations, and engage in conversations with users. Additionally, OpenAI can be customized and fine-tuned to match specific team requirements, and it can learn and improve over time through user interactions. By combining the capabilities of OpenAI with the collaborative nature of Slack, the bot can revolutionize team communication and knowledge sharing, leading to increased productivity.

Section 1: Setting Up the Environment

1.1 Choosing a Development Platform:

Several coding languages are available for developing a Slack bot, including Python, Node.js, and Golang. In my case, I opted for Python due to my extensive familiarity with it and the ease of quickly setting up a chat bot. However, if you decide to pursue a different language, the concepts presented in this blog post can still be applied to develop a Slack bot that seamlessly integrates with OpenAI.  

1.2 Installing Dependencies:

During the initial stages of Slack chat bot development, it is advisable to utilize existing Python packages to streamline the development process. While it is possible to build everything from scratch using the "requests" library, this approach contradicts the objective of creating a simple Slack bot. In my implementation of this bot, I relied on the following three packages to expedite development:

Installation of these dependencies is pretty straightforward, all three of them can be installed through the PIP package manager.  

pip install slackeventsapi
pip install slack_sdk
pip install --upgrade openai

Section 2: Creating a Slack App

2.1 Creating a Slack Workspace and App:

Creating a Slack app empowers you to extend the functionality of Slack, integrate external tools, automate tasks, enhance communication, and streamline workflows within your team. It offers customization options, improves productivity, and provides access to developer resources and support. By leveraging the capabilities of Slack apps, you can tailor the Slack experience to match your team's unique requirements and drive collaboration and efficiency.

To commence the creation of a Slack bot, the initial step involves the creation of a Slack App. This preliminary stage is essential for several reasons, as it sets the foundation before proceeding with the actual coding of the bot.

2.2 Obtaining Slack API Credentials:

There are quite a few steps to go through to setup your slack app, we will need to obtain the signing key, tokens and to subscribe to the events for this bot to work correctly.

To begin the app development process, login to the desired Slack workspace where you intend to integrate the Slack bot.

Access the workspace dropdown menu and select "Settings & administration" followed by "Manage apps."

Proceed to the "Build" section.

Click on "Create an App."

From the Create an app menu, choose the option "From scratch."

Specify the app name and select the corresponding workspace in the Name app & choose workspace section.

Navigate to the Basic Info menu and select "Bots."

To assign a scope to your bot token, click on "Review Scopes to Add."

Scroll down to the bot tokens section in the OAuth Tokens for Your Workspace.

Add the required scopes individually, to allow the bot the needed access to the workspace:

  • Channels:history: Grant access to view messages and other content in public channels where the bot is added.

  • Chat:write: Enable the bot to send messages as @DD Slack bot.

  • Files:read: Allow viewing of files shared in channels and conversations where the bot is present.

  • Files:write: Permit the bot to upload, edit, and delete files as Jarvis.

  • Groups:history: Provide access to view messages and content in private channels where the bot is added.

  • Im:history: Enable viewing of messages and content in direct messages where the bot is added.

  • Reactions:read: Grant access to view emoji reactions and associated content in channels and conversations where the bot is present.

Ensure that all scopes have been added correctly.

You will need to return to the basic info tab once you need to retrieve your credentials.

To customize the bot, scroll down to the Display information section and enter the relevant bot information. Additionally, you may upload an icon for the bot, ensuring it adheres to the dimensions of 512px X 512px. Save any changes made.

If desired, set the bot to show as online by accessing App Home and selecting "Always Show My Bot as Online."

Here is an example of what the new app might look like in the Slack client.

*** Important Note ***

Securely managing and storing credentials for your Slack bot is of utmost importance. Credential management plays a crucial role in maintaining the security and integrity of your bot along with the sensitive data it handles. Here's a summary of the importance of securely managing and storing these credentials:

1. Protecting Access: Properly securing credentials ensures that only authorized individuals or applications can access your Slack bot. Unauthorized access to credentials could lead to malicious activities, data breaches, or misuse of your bot's capabilities. By implementing strong access controls and safeguarding credentials, you can mitigate these risks.

2. Preventing Unauthorized Usage: Storing credentials securely helps prevent unauthorized usage of your bot. It ensures that only trusted entities can authenticate and interact with the bot, reducing the chances of malicious actors gaining control or exploiting its functionality.

3. Safeguarding Sensitive Data: Credentials often grant access to sensitive data or systems. Storing them securely prevents unauthorized individuals from obtaining these credentials and potentially accessing or manipulating sensitive information. It helps maintain the confidentiality, integrity, and privacy of your data.

4. Mitigating Impersonation Risks: If credentials are compromised, malicious actors may impersonate your bot, leading to unauthorized actions or misleading interactions with users. By securely managing credentials, you reduce the risk of impersonation, protecting the reputation and trustworthiness of your bot.

5. Compliance with Security Standards: Properly managing credentials aligns with security best practices and compliance requirements. Many regulations, such as GDPR or HIPAA, emphasize the importance of protecting sensitive information and enforcing access controls. Securely storing credentials helps you meet these standards and ensures compliance with relevant regulations.

6. Regular Credential Rotation: Securely managing credentials includes periodically rotating them to prevent prolonged exposure in case of a breach. By regularly updating and refreshing credentials, you limit the potential impact of any compromised or leaked credentials.

Securely managing and storing credentials is vital for maintaining the security, privacy, and trustworthiness of your Slack bot. It protects against unauthorized access, prevents misuse, safeguards sensitive data, and ensures compliance with security standards. By implementing robust credential management practices, you can mitigate risks, maintaining the integrity and security of your bot along with the data it interacts with.

Now let's continue building our Slack bot, go back to the App Credentials section and retrieve the keys that we need, there are two secrets you will need the Signing Secret and the Bot Token.

At this point you will Install your app and allow it permissions to access the workspace that it will be deployed to. This process will generate all the tokens to interact with the workspace.

Once you click the Install button review the content and what the bot will be able to do then click allow.

Finally to get your Bot’s User OAuth Token click on the Install App menu item.


Section 3: Integrating OpenAI with the Slack Bot

3.1 Setting Up the OpenAI API:

The OpenAI API is a powerful tool that provides access to advanced language models developed by OpenAI, such as GPT-3.5. It allows developers to integrate these models into their applications, leveraging their natural language understanding and generation capabilities. Here's an overview of the OpenAI API and its usage:

1. Access to Language Models: The OpenAI API offers access to state-of-the-art language models, allowing developers to generate human-like text responses, perform language translation, summarize documents, answer questions, and much more.

2. Simple API Calls: The API provides a straightforward interface for making requests to the language models. Developers can send a prompt or query as input and receive generated text as output. The API handles the complexity of the underlying language model, making it easy to integrate and use.

3. Customization and Fine-Tuning: The OpenAI API allows for customization and fine-tuning of the models. Developers can guide the model's behavior by providing instructions, examples, or specifying the desired output format. This customization helps tailor the model's responses to specific use cases or requirements.

4. Language Understanding and Generation: The language models offered by the OpenAI API possess impressive natural language understanding capabilities. They can comprehend context, generate coherent and contextually relevant responses, and adapt to different conversational styles.

5. Diverse Applications: The OpenAI API is used in applications in a wide range of fields, including content generation, virtual assistants, customer support, chatbots, language translation, and much more. It can be used to enhance user experiences, automate tasks, and provide intelligent responses in various industries and domains.

6. Developer Support and Resources: OpenAI provides comprehensive documentation, guides, and developer support to assist in utilizing the API effectively. This ensures that developers have the necessary tools and resources to integrate the models seamlessly into their applications.

The OpenAI API provides developers with access to advanced language models, enabling them to leverage powerful natural language understanding and generation capabilities. Its straightforward API calls, customization options, and support make it a valuable resource for building applications that require sophisticated text-based interactions and responses.

In our project we are going to be using OpenAI’s API to be the interface between our Slack bot and the AI used to answer questions.  OpenAI is used more by developers than ChatGPT but both are developed by the same organization.  There is a web interface to OpenAI just like there is with ChatGPT but we are more interested in the API that backs the chat frontend.  There are two tiers of access when using OpenAI, we will be using the free plan but there is also a plus plan.  

Here is what the two plans offer:

To access the OpenAI API, you need to authenticate your requests using an API key. Here's an overview of the authentication process and how to acquire the necessary API key:

  • OpenAI Account: Start by creating an account on the OpenAI platform if you don't already have one. Visit the OpenAI website (https://www.openai.com/) and sign up for an account.

  • Once signed up you can click on your profile on the left side of the screen

  • Now click View API keys

  • To create a new key for your bot click on Create new secret key.

  • In the Create new secret key box enter the key name and click on Create secret key

  • Now copy your new secret key and save it in a safe location you will need this key once you create your bot code.

  • Authentication in Requests: To authenticate your API requests, include the API key in the authorization header of each request. The exact method for including the API key may depend on the programming language or library you are using. Consult the OpenAI API documentation for specific instructions.

  • Keep API Key Secure: Treat your API key as a sensitive piece of information and keep it secure. Avoid sharing it publicly or committing it to version control systems. Exposing your API key can lead to unauthorized usage and potential security risks.

  • API Usage and Rate Limits: Once you have your API key and authentication set up, you can start making requests to the OpenAI API. Ensure that you follow the guidelines, usage limits, and any rate limits specified in the API documentation to avoid exceeding the allocated usage quota.

Remember to regularly check the OpenAI documentation and resources for updates and changes to the authentication process or any additional requirements.


3.2 Implementing the Slack Bot Logic:

At this stage of the process, we have successfully configured a Slack app and obtained an OpenAI key to access the API. However, to enable event reception from Slack and ensure connectivity if your system is protected by a firewall, an additional service is required to expose your Slack bot to the Slack cloud.

Several services are available for this purpose, but I recommend ngrok. Ngrok offers a free service suitable for testing and initial setup of your bot, with the option to upgrade for expanded capabilities. If you wish to enhance your bot's functionality and desire a consistent custom domain, ngrok provides various paid tiers of service to fulfill this requirement.

  1. To set up the ngrok service first we will need to signup for an account at the ngrok website

Once the account has been created we need to login to it and download the ngrok software, for my purposes I used the Linux agent but there are several other agents options available. 

Once you have the agent downloaded, unzip it to a directory

For Linux:  

unzip /path/to/ngrok.zip

Once you have the agent unzipped you will need to run the configuration command to set your API key. 

ngrok config add-authtoken <API KEY>

Now that the agent has been configured with the API key we can start it, you will need to change the port to whatever is set up within the flask app, use the below command to run the ngrok agent to forward events to the slack flask app.

Note: By default python flask runs on port 5000

ngrok http <SET PORT NUMBER>

Now that we have the agent running there will be an external url that will need to add to the Slack app so that Slack knows where to forward events to. We will now go back to our Slack app and add it to the Events subscription.

Now go back to the Slack app set up before and click on the Event Subscription menu on the left of the screen. Enable Event Subscriptions by toggling the switch to on.

You will need to copy your forwarding URL from the ngrok agent, then paste the URL into the box.  Make sure you add “/slack/events” to the end of the URL.

Slack will verify your URL is able to receive events once that is successful you can start to add the specific events to listen for. To add events click on the Subscribe to bot events then expand it.  I added the following events, this is the bare minimum needed to have your Slack bot respond to mentions.

Save the Changes and you will need to reinstall your app, you can click on the banner that pops up to do this.

Examples of how to call OpenAI with the new keys:

The OpenAI API is relatively easy to use and is capable of answering questions, writing code and even creating images.  We will keep the scope of this Slack bot to only answering questions.  

Asking a question using curl:

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{"model": "text-davinci-003",
     "prompt": "Say this is a test",
     "max_tokens": 7,
     "temperature": 0}'

In the above example we use the Authorization header to pass the OpenAI API token.  Also note the Content-Type header is set to application/json, we chose the text-davinci-003 model for our purposes.  The important part of this payload is the prompt; this is where we ask our question otherwise known as prompting.  

If we add in our API Key and run the above curl command we get the following answer.

{"id": "cmpl-7YcnRBaDDjUIGcdWOet7HRzVaBBYo",
  "object": "text_completion",
  "created": 1688486641,
  "model": "text-davinci-003",
  "choices": [{"text": "\n\nThis is indeed a test",
       "index": 0,
      "logprobs": null,
       "finish_reason": "length"}],
  "usage": {"prompt_tokens": 5,
     "completion_tokens": 7,      "total_tokens": 12} }

If you want to read more on the OpenAI API you can find it in this documentation.

Section 4: Enhancing Bot Functionality

4.1 Implementing Command Parsing:

When deciding what language we wanted to use for development of our Slack bot we chose Python as the language, the following Python libraries were used to process the incoming events.  This being a very simple program that only responds to @mentions there isn’t a lot of code needed to do the work but let's take a look at the main function of this bot.

To begin building our Slack bot we will first import two libraries to make the process easier to deal with the events.  The two libraries I am using are the slackeventsapi and the slack_sdk, these libraries make it easy to work with Slack events.

from slackeventsapi import SlackEventAdapter
from slack_sdk.web import WebClient

Once the libraries are imported we will want to create the function to support the app_mention event.

@slack_events_adapter.on("app_mention")
def handle_mentions(event_data):
    event = event_data["event"]
    if "?" in event['text']:
        response = openaiapi(question=event['text'])
        channel = event["channel"]
        message = "<@{}> {}".format(event["user"], response)
        slack_client.chat_postMessage(channel=channel, text=message)

Let’s break down what is happening in the code above.

  1. We have a decorator for the app_mention event to route the incoming request to this function.

  2. We throw the value of event_data[‘key’] into a new dictionary called event.

  3. To make this very simple we just look for a question mark within the event[‘text’] dict value. 

  4. Based on the question mark trigger we will now call the OpenAI function and pass the question to it as a variable called question.

  5. We also dump the channel from the event[‘channel’] value into a variable so that we can send the answer back to that channel.

  6. Once we have the answer back, along with the channel and user information we will build our message to send back to the user using the @user command.

  7. When the message is formatted we will use slack_client.chat_postMessage to send the message to the channel with an @mention of the requesting user.


4.2 Adding Custom Actions and Responses:

The code used in this Slack bot is very basic and is only to demonstrate how you could integrate Slack with OpenAI. You can easily extend the capabilities of the bot code by adding more commands or listening to more events such as messages, file uploads or reactions.

A full list of event types can be found in the Slack documentation that is located here.

An example of another event type that would help extend the Slack bot’s capabilities would be message event, to respond to channel messages you would add in the following decorator.

@slack_events_adapter.on("message")

Another example of how to extend the capabilities would be to look for the text “turn on” this would allow you to implement functions to turn on a device through integration with a home automation system.

Example:

if "turn on" in event['text']:

    <do stuff>

Now that we have the Slack bot set up we would move on to reacting to messages using artificial intelligence the next step would be to integrate with OpenAI.  This integration will allow us to leverage the OpenAI capabilities and give our Slack bot more capabilities. I have created a simple function below that will take a question from the Slack channel processes it using OpenAI and responds to the user. 

def openaiapi(question=None):
    response = openai.Completion.create(
    model="text-davinci-003",
    prompt=question,
    temperature=0.5,
    max_tokens=150,
    top_p=1.0,
    frequency_penalty=0.0,
    presence_penalty=0.0
    )
    for line in response['choices']:
        return line['text']

If we look at the function above we can see that it take the question from the Slack app and pass it into the prompt field sending it to OpenAI.  The function will query the OpenAI API and return an answer that is passed back to the Slack channel.

Let's take a look at what this process looks like from a user's perspective.

Conclusion:

To summarize the process of developing a Slack bot first we set up the Slack App, during this process it’s important to remember that you need to scope the OAuth permissions to allow the bot to perform certain tasks.  Along with the OAuth permission there needs to be specific Events that the Slack bot will subscribe to and since we are installing this locally we need to have a service such as ngrok to forward the events to the python code.  

A Slack bot that has the power of OpenAI has the potential to significantly enhance communication within a Slack workspace by providing instant and intelligent responses. It can quickly address queries, provide information, and engage in conversations, facilitating efficient and seamless communication among team members. 

Furthermore, readers are encouraged to explore and customize the bot to suit their specific requirements, allowing them to tailor its functionality and responses according to their team's unique needs. This customization empowers teams to optimize the bot's performance and further enhance its capabilities to maximize productivity and collaboration.

Previous
Previous

Canoo Electric Vehicles: The Future of Sustainable Mobility

Next
Next

Ubiquiti USW-Lite-16-PoE Switch Review: Power and Performance in a Compact Package