Maximizing Productivity: The Power of SlackBots

Artur Cepuc
8 min readMar 4, 2023

--

Slack has become an everywhere communication platform for modern teams, providing a centralized space for messaging, file sharing, and collaboration. But did you know that you can extend Slack’s functionality even further with the help of bots? SlackBots are automated tools that can perform a wide range of tasks, from managing your schedule to providing real-time updates on your tasks. In this article, we’ll dive into the world of SlackBots, exploring their capabilities and how they can be used to boost productivity, streamline workflows, and enhance the overall Slack experience. Whether you’re a Slack power user or just getting started, this guide will give you everything you need to know about leveraging the power of SlackBots to take your team’s communication and collaboration to the next level.

If you’re looking to build a custom SlackBot that can automate tasks, send notifications, or interact with other apps, you’re in the right place! We’ll explore how to use the Slack API and the Slack Bolt framework in Python to create a fully-functional bot that can do all of these things and more. Slack Bolt is a Python library that simplifies the process of building and running SlackBots by providing a clean and intuitive interface for interacting with the Slack API. With Slack Bolt, you can quickly and easily create custom message handlers, set up event listeners, and build interactive components like buttons and menus. We’ll walk you through the steps of creating a SlackBot using Slack Bolt in Python, from setting up your development environment to deploying your bot to production. So if you’re ready to dive into the world of SlackBots and automation, grab your Python IDE and let’s get started!

You can find all the codes used in this tutorial here.

Requirements:

  • Python3
  • Slack Workspace
  • Python Slack CDK, Slack-Bolt, Flask.

You can install these modules with pip.

pip install slack-cdk
pip install slack-bolt
pip install flask

Creating and installing our app

In the context of the Slack API, scopes refer to the specific permissions that your app or bot has been granted to access and interact with a user’s Slack workspace. Slack scopes are important because they provide a way for developers to limit the amount of access that their app or bot has to a user’s workspace, reducing the risk of accidental or malicious data manipulation.

  • Once you have these scopes added, scroll up and click ‘Install to workspace’.
Install to Workspace Button (Slack API).
  • After the app is installed, you will be given a ‘Bot User OAuth Token’. Copy and save it somewhere.

Access tokens are the keys to the Slack platform. Tokens tie together all the scopes and permissions your app has obtained, allowing it to read, write, and interact.

There are three main types of tokens that exist in Slack:

  • Bot Tokens — are used by SlackBots to authenticate with the Slack API and access the resources and permissions granted to the bot. Bot token strings begin with xoxb- .
  • User Tokens — are issued on behalf of a specific Slack user and provide access to the user’s resources and permissions within a particular workspace. User token strings begin with xoxp- .
  • App-Level Tokens: App-level tokens are used by Slack apps to authenticate with the Slack API and access resources and permissions that are granted to the app. App-level token strings begin with xapp- .
SlackMate
  • Lastly, we need to add our app to one or more channels where it will have all the accesses we added earlier. I will add my app to ‘#slackmate’.
#slackmate channel and our new app.

Bot Operations

The bot we currently have cannot do anything, we need to add some functionality to it. For this part, we will use Slack-Bolt.

Here’s a simple Slack-Bolt in Python that responds to a user’s message with a “Hello, World!” response:

# import libraries
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

# New instance of the Slack-Bolt app
slackmate_app = App(token=os.environ["SLACK_BOT_TOKEN"])

# Message Handler Function
@slackmate_app.event("message")
def handle_message(payload, say):
# check if the message contains the word "hello"
if "hello" in payload["text"].lower():
# send a response message to the user
say("Hello, World!")

In this example, we import the necessary libraries and create a new instance of the Slack-Bolt app, passing in our bot token(previously generated token). Its always advised to save the auth tokens as environment variables. If you are on a Windows platform use set SLACK_BOT_TOKEN=XXX and if you're on Linux or UNIX based system then use export SLACK_BOT_TOKEN=XXX- . Once you have set the environment variable we can use os.environ.get(‘SLACK_BOT_TOKEN’) to use it in our application.

We then define a message handler function that is triggered whenever a user sends a message in a channel that the bot is a member of. The handler function retrieves the text of the message and checks if it contains the word “hello”. If it does, the function sends a “Hello, World!” response message back to the user using the say() function provided by Slack-Bolt.

The if and elif statements are just a simple way to check the content of incoming messages, but you can use any other Python code to handle messages based on their content, context, or any other attribute.

For example, you could use regular expressions to match patterns in the message text, or you could use machine learning models to classify messages based on their content or intent. You can also use external APIs to perform actions based on the message content, such as translating the message text or looking up information in a database.

Here’s an example of how to use regular expressions to match patterns in the message text.

@slackmate_app.event("message")
def handle_message(payload, say):
chat_message = payload["text"]
thread_message = payload["ts"] # thread reply
if re.match(r"\b(hello|hi|hey|salut) slackmate\b", chat_message, re.IGNORECASE):
say(f"Hi <@{payload['user']}>", thread_ts=thread_message)
elif re.match(r"\bhow are you\b", chat_message, re.IGNORECASE):
say("I'm doing great, thanks for asking!",thread_ts=thread_message)
elif re.match(r"\b something other\b", chat_message, re.IGNORECASE):
say("test", thread_ts=thread_message)

In this example, the code uses the re.match() function to match regular expressions against the message text.

You can filter incoming message events to a specific channel ID by checking the channel attribute of the event object. If the event is from the specified channel, the function responds based on the content of the message as before. If the event is from a different channel, the function does nothing.

def handle_message(payload, say):
# Filter messages to a specific channel ID
if payload["channel"] == "CHANNEL_ID":

You can replace “CHANNEL_ID” with the ID of the channel you want to filter messages to.

Slack Events API

The Slack API supports several event types that your app can listen for and respond to. Here are some of the most common event types:

  1. message: Triggered when a user sends a message in a channel or a direct message to the app.
  2. app_mention: Triggered when the app is mentioned in a message, either in a channel or a direct message.
  3. reaction_added: Triggered when a user adds a reaction to a message.
  4. member_joined_channel: Triggered when a new user joins a channel.

These events provide information about actions and interactions that happen within Slack, and you can use them to build a variety of apps and bots that respond to user actions.

You can find a complete list of event types in the Slack API documentation: https://api.slack.com/events.

Now, this is a tricky but necessary part. We need to accept and send requests from Slack, which means we need to create an app that can communicate to the outside world. Here we have 2 options either we can use a Cloud VM such as EC2 instance in AWS or use ngrok which is used to expose a development server to the outside world.

But… let’s not forget the simplest option…

We can receive app payloads via Websockets instead of Request URLs.

Socket Mode

Socket Mode is a feature in Slack’s platform that allows you to build Slack apps and bots that use a WebSocket connection to communicate with Slack. With Socket Mode, you can build Slack apps that don’t require a public URL or a web server to function. Instead, your app connects to Slack via a WebSocket using a secure token. This makes it easy to build lightweight, serverless Slack apps and bots that can run on any platform, including on-premises or behind a firewall.

To use Socket Mode in our Slack app, in the manifest we have:

socket_mode_enabled: true

Finally, we start the app using the Socket Mode handler, passing in our app token and client ID.

from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
import os
import re
import logging
from modules import test

logging.basicConfig(level=logging.INFO)


slackmate_app = App(token=os.environ["SLACK_BOT_TOKEN"])


@slackmate_app.event("message")
def handle_message(payload, say):
chat_message = payload["text"]
thread_message = payload["ts"] # thread reply
if re.match(r"\b(hello|hi|hey|salut) slackmate\b", chat_message, re.IGNORECASE):
say(f"Hi <@{payload['user']}>", thread_ts=thread_message)
elif re.match(r"\bhow are you\b", chat_message, re.IGNORECASE):
say("I'm doing great, thanks for asking!",thread_ts=thread_message)
if re.match(r"\b something other\b", chat_message, re.IGNORECASE):
text = test.Test("test")
say(test.test(), thread_ts=thread_message)


@slackmate_app.event("app_mention")
def handle_mention(payload, say):
thread_message = payload["ts"]
say(f"Hi <@{payload['user']}>", thread_ts=thread_message)


if __name__ == "__main__":
handler = SocketModeHandler(app_token=os.environ["SLACK_APP_TOKEN"], app=slackmate_app)
handler.start()
Replies from SlackMate

SlackBots can get data from APIs. In fact, one of the most common uses of SlackBots is to integrate with other tools and services by calling their APIs.

To get data from an API, your SlackBot will need to send a request to the API endpoint and then parse the response.

For example, let’s say you wanted to build a SlackBot that retrieves weather information for a given location. You could use an API like OpenWeatherMap to retrieve the weather data, and then use Python to make the API request and parse the response.

When building a SlackBot, it’s important to keep in mind the needs and preferences of your team. Think about the tasks that are most time-consuming or repetitive, and consider how a SlackBot could help streamline those workflows. Additionally, make sure to follow best practices for security, privacy, and data handling to ensure that your SlackBot is secure and compliant.

Overall, SlackBots can be a valuable addition to any team’s Slack workspace, and with a little creativity and programming know-how, you can build a SlackBot that meets the unique needs of your team.

Hope it will be useful, will meet again with another interesting topic.

--

--