Have you ever wanted to be notified on a particular Slack channel when an event occurs in your software?

If your answer is “Yes”, then this tutorial is definitely for you!

In this tutorial, we’ll show how to make a Slack bot by following two different paths:

  • We’ll code a Slack bot in Python – the best approach if you’re looking for full control over the Slack bot's logic and functionality;
  • We’ll create a Slack bot using n8n – the best approach for rapid Slack bot development, even if you need extensive customization and scalability.

But before that, let’s start with the essentials:

Does Slack allow bots?

Yes, there are several ways to create bots for Slack:

  1. Slack APIs: Developers can use Slack APIs to create custom bots and integrations using various programming languages like Python, JavaScript, and Java. These APIs allow for sending and receiving messages, managing channels, and interacting with users.
  2. Bot frameworks: Frameworks like Botkit, Slack Developer Kit for Python, and SlackBolt simplify the process of building Slack bots. They offer tools and libraries for features like message parsing, event handling, and interactive components.
  3. Third-party platforms: Some platforms offer tools for creating and deploying Slack bots without code. They provide visual interfaces and templates, enabling non-technical users to build and customize bots for different purposes.

However, there are some limitations and guidelines that developers need to be aware of when creating bots for Slack. For example:

  • API rate limits. Slack imposes rate limits on API requests to prevent abuse and ensure fair usage. Developers need to adhere to these limits to avoid being throttled.
  • Security. Bots should follow security best practices to protect sensitive information and prevent unauthorized access.
  • User consent. Bots that interact with users in private channels or direct messages must obtain consent from users before initiating any conversation or collecting personal information.

Once you decide on which method to use to build a Slack bot, you’ll first need to set up Slack’s API.

Setting up Slack to use its API

To create a Slack bot, we have to first set up Slack’s API.

To do so, go to Slack API, Your apps > Create your first app:

Creating a Slack App. Image by Federico Trotta - n8n blog
Creating a Slack App. Image by Federico Trotta

Give a name to your app and select a Slack workspace (the workspace must already be created in Slack):

Naming a new APP in Slack. Image by Federico Trotta - n8n blog
Naming a new APP in Slack. Image by Federico Trotta

In Features > Incoming Webhook, add a new incoming webhook:

Activating a webhook in Slack. Image by Federico Trotta - n8n blog
Activating a webhook in Slack. Image by Federico Trotta

and select the channel in your workspace (the channel must be already created in your workspace):

Selecting a channel in a Slack APP. Image by Federico Trotta - n8n blog
Selecting a channel in a Slack APP. Image by Federico Trotta.

In Features >OAuth & permission, search for the scopes and select the following from the listed ones:

Managing scopes in a Slack APP. Image by Federico Trotta - n8n blog
Managing scopes in a Slack APP. Image by Federico Trotta

Once Slack’s API is set up, we are ready to build our custom Slack bot!

How to make a Slack bot in Python

In this section, we’ll show how to create a Slack bot in Python.

We want our custom Slack bot to do the following:

  • Let the user interact with the program via the command line, inserting a question;
  • The command line responds, retrieving the response thanks to the OpenAI API, and prints the answer;
  • The program posts the answer in the dedicated Slack channel.

Here’s how the bot posts the answer to the dedicated Slack channel:

The result of the Slack coded in Python. Image by Federico Trotta - n8n blog
The result of the Slack coded in Python. Image by Federico Trotta

We’ll first report the whole code for the Slack bot development. Then, we’ll describe it step by step, including the basic functioning.

import requests
import openai

def answer_question(question:str)->str:
    '''This function queries the OpenAI API, base on the question asked by the user via CLI'''
        
    try:
        response = openai.ChatCompletion.create(
          model="gpt-3.5-turbo", 
          messages=[{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": question}]
        )
        return response['choices'][0]['message']['content']
    except Exception as e:
        return f"Si è verificato un errore: {str(e)}"

def send_slack_message(answer:str, webhook_url:str)->None:
    '''This function sends the message on the dedicated Slack group for'''

    # Payload: only text message
    payload = {
        'text': answer  
    }

    response = requests.post(
        webhook_url,
        json=payload,
        headers={'Content-Type': 'application/json'}
    )

    try: 
        if response.status_code == 200:
            print("Message correctly reported in the dedicated Slack channel!")
        else:
            print("Couldn't report the message in the dedicated Slack channel due to an error.")
    except Exception as e:
        print(f"An exception occurred while trying to write the message on Slack:", e)


if __name__ == "__main__":
    # Insert your OpenAI key
    openai.api_key = "YOUR OPENAI KEY"
    # Insert the webhook URL
    webhook_url = "YOUR WEBHOOK URL"
    # User writes the question
    question = input(f"Please: ask me a question!\n")
    # Bot answers, prints answer and post to Slack channel
    answer = answer_question(question)
    print(f"The response to your question is:\n", answer)
    send_slack_message(answer, webhook_url)

Prerequisites

The bot uses the following libraries that are not included in the Python standard packages:

  • Requests
  • OpenAI

In case you don’t have them already installed, you can do it like so:

pip install requests
pip install openai==0.28

Note that you need to install a particular version of the OpenAI library. This is because the program will invoke a particular method that is currently no longer supported in the versions >1.00.

If you already have installed a version of OpenAI superior to version 1.00, you must  uninstall it via:

pip uninstall openai

You can now install version 0.28 as described.

Also, to use the OpenAI library, you must have an active account. If you don’t have one, you can request it here.

Now, let’s describe the steps to code such a bot in Python:

Step 1: Create a function to answer the question

The user will prompt the question via the CLI. So, as a first step, create a function that answers the question. In that case, the function answer_question():

  • Gets the question as input;
  • Queries the OpenAI API. If the query is successful, it returns the answer to the query. If there are any errors, it returns the error.

Step 2: Create a function to send the message to the Slack channel

We want the bot to append the answer to the user’s question into a dedicated Slack channel. In that case, the function send_slack_message():

  • Gets the answer from OpenAI and the webhook URL as inputs;
  • As a payload, gets only text;
  • Posts the answer in the dedicated channel by querying the Slack API. If the response code is successful, everything works fine. if it is not, it prints an exception message.

Step 3: Set the fixed values

At the end of the code, when invoking the main, set the fixed values:

  • Write your OpeAI key and the webhook URL;
  • Use the input() function to make the user interact with the software via the CLI;
  • Invoke the functions.

Note that the webhook URL is in the Slack API in Features > Incoming Webhook:

Step 3: Set the fixed values
Step 3: Set the fixed values

Step 4: Testing the Slack bot in Python

When invoking the Python file via python3 file_name.py, the software asks to write down the question. Type your question, and the software answers thanks to the OpenAI API:

Step 4: Testing the Slack bot in Python
Step 4: Testing the Slack bot in Python
💡
If you explore more ways to create custom bots, check out our tutorials:
1. How to create a ChatGPT Discord bot
2. How to create an AI bot in Telegram

How to make a Slack bot using n8n

Now, let’s see how to create a Slack bot using n8n and its Slack integration, similar to the one coded in Python.

To do so, we’ll use the following template “Slack chatbot powered by AI”:

The n8n template we use for the Slack bot. Image by Federico Trotta - n8n blog
The n8n template we use for the Slack bot. Image by Federico Trotta

You can start by copying and pasting the workflow template into your canvas:

Here’s how this template works:

  • The user inserts a prompt;
  • If the user is not a human, the bot takes no action;
  • If the user is a human, the agent retrieves the answer to the user’s query (thanks to the OpenAI integration) enriching data from the web thanks to the SerpAPI integration. The agent is also connected to the Window Buffer Memory so that the bot remembers a certain number of old chats with the user;
  • The answer is posted in the dedicated Slack channel.

Let’s set up and test it.

Prerequisites

To use this template you need the following:

  • An active OpenAI account to use the API key. If you don’t have one, you can request it here;
  • A valid and active SerpAPI API key. If you don’t have one, you can request it here;
  • A cloud version of n8n.

Also, to use the Slack API, you must make a little adjustment to the Slack setup.

Open the Webhook trigger in n8n’s template and copy the Webhook URL:

Copying the webhook from the webhook integration. Image by Federico Trotta - n8n blog
Copying the webhook from the webhook integration. Image by Federico Trotta

This webhook triggers the workflow, so we have to paste it into the command that prompts the Slack API to make it work.

To do so, in the Slack API, In Features > Slash Commands, create a new command:

Creating a Slash command in a Slack APP. Image by Federico Trotta - n8n blog
Creating a Slash command in a Slack APP. Image by Federico Trotta

And add the Webhook URL in the Request URL field:

Adding a request URL in a Slack APP. Image by Federico Trotta - n8n blog
Adding a request URL in a Slack APP. Image by Federico Trotta

Now we can set up the whole n8n template and use it.

Step 1: Configure the Agent

The Agent is the core of the chatbot, so we consider this in the first place.

The Agent node in this workflow processes user messages from Slack, utilizing specified options and potentially external tools like Wikipedia and SerpAPI, to generate responses based on provided system instructions, ensuring coherent and context-aware communication.

Double-click on Agent and:

  • Verify that the agent type is Conversational Agent (1).
  • Write the prompt to query the ChatGPT API in the Text field (2).
Setting up the agent pf the n8n template. Image by Federico Trotta - n8n blog
Setting up the agent of the n8n template. Image by Federico Trotta

The next steps will show how to set up the integrations that enrich the agent. In particular:

Step 1.1: Configure the Chat OpenAI model

The Chat OpenAI model serves as a component within the Agent node responsible for processing user messages. Specifically, it utilizes the GPT-4 language model to generate responses based on the input it receives.

To set it up, select it and connect it to your OpenAI account in the field Credential to connect with.

The model field should be chosen based on the OpenAI version you use. If you’re using the free version, you can choose gpt-3.5-turbo.

Step 1.2: Configure the SerpAPI and Wikipedia integrations

The SerpAPI integration enriches the answer retrieved by the Chat OpenAPI integration by searching for more data on the web, also on Wikipedia.

To set it up, Select it and connect it to your SerpAPI API account in the field Credential to connect with.

Step 1.3: Configure the Window Buffer Memory

The Window Buffer Memory stores the history of the chat between the user and the bot, creating a “memory effect” on the chatbot.

A good value of the parameter Context Window Length is 20 or 30. This means that the bot will remember the last 20-30 answers.

Step 2: Configure the Slack integration

The Slack node facilitates bidirectional communication between the chatbot and Slack, enabling the chatbot to send generated responses back to Slack channels or users.

Double-click on the Slack integration and configure the following parameters:

  • Credential to connect with: connect it to your Slack account.
  • Resource: select Message as we want to deal with messages.
  • Operation: select Send as we want to send messages.
  • Send Message To: select Channel as we want to dens messages to a previously created channel.
  • Channel: select From list. Then, search for the dedicated channel you created to test the bot.
  • Message Type: select Simple Text Message.
Configuring the Slack integration in the n8n template. Image by Federico Trotta - n8n blog
Configuring the Slack integration in the n8n template. Image by Federico Trotta

Step 3: Test a Slack bot powered by n8n

So, after a short template setup, the automation is ready to be tested.

To do so, click on Test Workflow in the n8n template.

Then, go to the Slack channel dedicated to the test. In the chat, write the name of the command. In this case, I called it /test!, so I wrote it and pressed send message.

Here’s how the bot answered:

The answer of the bot in the Slack channel. Image by Federico Trotta - n8n blog
The answer of the bot in the Slack channel. Image by Federico Trotta

Wrap up

In this article, we've described how to create a Slack bot using Python and n8n.

With n8n, we've built a more advanced Slack bot than Python, delivering faster performance while still offering flexibility for future enhancements and customization.

As a low-code automation tool, n8n lets you:

  • Integrate Slack bot with other apps and tools;
  • Manipulate data without coding;
  • Build in advanced AI modules.

Create your custom Slack bots

Build complex automations 10x faster, without fighting APIs

Hopefully, this will be useful for your work or your personal projects!

What’s next?

If you’d like to try other bots that interact with Slack, you may consider the following templates: