A Beginner’s Guide to Building Slack Bots

Ayush Yadav
4 min readJan 6, 2024
Python based slack bot for alerts

But Why?

When an application’s production environment goes down, a new deployment is made to the development environment, or any other significant event occurs within the development pipeline, the relevant team members must be alerted immediately.
Slack bots can be used as an alert system or monitoring system for the overall pipeline.

Why Webhooks:

Webhooks offer a simple solution. They’re like real-time messengers between apps. When an event happens, like a crash, we can trigger a webhook to send a pre-defined message to another app, like Slack in this case, which relays it to the team.

Simply put, we make a POST API request to send our message.

Building the Slack Bot:

Now that we understand the why, let’s start building it. It consists of 2 parts.

  1. Setting up the Slack Bot in the workspace.
  2. Writing a Python script to send messages via the bot.

Step 1: Create an App in Slack Workspace

First, we need to create the bot for the Slack workspace. Visit Slack’s API site, and click on “Create an App.” Select Create an App from scratch.

Then fill in the name of the app and the corresponding workspace where it will be used.

Step 2: Set Permissions

It’s time to set permissions for our bot. Navigate to “OAuth & Permissions” in the settings panel. Under the “Scopes” section, add the chat:write permissions to enable the bot to write messages to channels.

Step 3: Create a Webhook URL

Navigate to the “Incoming Webhooks” section and switch the toggle to ON. Then, click on the button saying, “Add New Webhook to Workspace.” under Webhook URLs for Your Workspace section. Choose the channel where you want to add the bot and click “Install.”

Select the appropriate channel name if prompted.

This will generate a Webhook URL for you to use in your Python code.

Step 4: Getting Started with Python

First, create a Python environment using venv python library & then activate it like this

To connect and send messages to Slack through our bot, we will use Python’s requests library. If it’s not installed in your environment, use the command — pip install requests.

Add it to the requirements.txt file for later use

Step 5: Building the SlackBot Class:

To begin, we define a SlackBot class, designed to receive a webhook_url parameter during its instantiation. The core functionality involves sending messages; these messages are obtained in string format from other source files.

Then we use the requests library to make a post request to the webhook URL with our payload.

We have also added exception handling by utilizing the try and catch mechanism.

Here’s our final Python code:

import requests

class SlackBot:
def __init__(self, webhook_url):
self.webhook_url = webhook_url
def send_message(self, message: str):
message_payload = {
"text": message
}
try:
response = requests.post(self.webhook_url, json=message_payload)
if response.status_code == 200:
print("Message was sent successfully to slack")
else:
print("Message was not sent to slack, status_code:", response.status_code)
except Exception as e:
print("An exception occurred while sending a slack message", e)
# create an object here

We can also use logging.info(“info statements”) instead of print()

Step 6: Instantiating the SlackBot Class

Finally, we instantiate the SlackBot by providing our webhook URL (from step 3) inside this file, so we can simply import it later in other project files.

slack_bot = SlackBot("<your-webhook-url>")

# replace with your webhook url from step 3
# eg: "https://hooks.slack.com/services/XXXXXXX"

Step 7: Using the Slack bot

We will create a count script to test our bot.

from slack_bot_web_hook import slack_bot 

def count(n: int):
for i in range(1, n+1):
slack_bot.send_message(f"Count: {i}")

if name == "__main__":
count(10)

We are calling the send_message() method here to send our message.

Each run of the program would send “Count: {i}” to your chosen channel.

With this, we’ve created a simple Slack bot that sends alerts to specific channels.

You can trigger these alerts whenever a certain event happens to alert relevant team members of it by importing it.

There’s a ton more functionality you can add to this bot, but this should serve as a handy starting point. Happy coding!

--

--

Ayush Yadav

Generative AI Wizard | Building the future one pipeline at a time.