Slack Python Bot – #2 Creating Slash Commands

As you learned about creating a basic slack python bot in our previous tutorial, today you’ll learn to add more features to the same bot.

Getting Started with Slack Python Bot – Creating Slash Commands

This is the second part of our Python Slack Bot tutorial series and if you’re a newbie creating a slack bot, it is highly recommended to go through the first part of this tutorial. If you’re not familiar with slack, you can check Slack’s Official website to know about it. In this tutorial today, we’ll add slash commands features to our slack python bot which we created in the previous tutorial.

What are slash commands?

Slash commands are a type of Slack’s various command handlers. In slack, a user can give commands to the bot in several ways like by reacting to a message, sending some specific messages or pinning or unpinning a message and bot can use Slack Event Handler to handle each of these events but the most easy way to trigger a bot is by a slash command. It is something similar to specific command handlers in our telegram bot tutorial.

So you can instruct your slack python bot to perform a desired function on calling of a specific command and save that command as slash command in your bot API. Now whenever a user sends that particular command starting with a slash (/), the function attached with the command is executed by the bot.

Algorithm

In order to create slash commands for your Slack Python bot, you’ll have to follow the following algorithm:

  1. Create a Flask Server for the request URL.
  2. Add the trigger and request URL for your slash command and save it to your API.
  3. Provide the permissions to read the messages in your workspace to your bot.
  4. Re-install your app to your workspace.
  5. Import Python’s Slack Library and/or other necessary libraries in python.
  6. Trigger your Slack Python Bot with its API Token.
  7. Start creating responses of slash commands for your Slack Python Bot.
  8. Run the flask server.

Create a Slash command and Save it

In order to create a slash command for a slack python bot, you need to list the slash command in your app’s API and reinstall the app to your workspace to save the changes. Follow these steps to do that.

1. Go to Slack’s API website and click on Your Apps and select the app where you want to create slash commands by its name (here Webmatrices Bot).

Selecting the app
Selecting the app

2. And then select Slash Commands from the left side toolbar.

Selecting Slash Command
Selecting Slash Command

3. Now click on Create new Command and provide the details to create a command.

Create New Command
Create New Command

4. Now you’ll have to give three details: one command name (the name with which you want to call your command, must start with a ‘/’, here /greet), other the request URL (the target which is requested for a response whenever the command is called) and short Description (this is a short description of your command that helps the user recognize what that particular command does.) and click on Save.

Adding Details for a command
Adding Details for a command
Note that the request URL is the target which is hitted whenever the command is called. This means whenever a user sends a particular slash command, it does not know what to do and to get the reponse it triggers the request URL and ask it for a reponse, and forwards the response returned by the URl to the user. So this URL must be the one owned by you yourself and you can edit the reponse returned by it using Python's Flask module. If you don't have any of your own URL, you can check below for generating a URL through Repl.

5. Now your slash command is saved and you need to allow permission to read messages in the workspace to the bot. And for that, you need to select OAuth and Permissions from the left side toolbar.

Select OAuth and Permissions
Select OAuth and Permissions

6. Now scroll the page down to Bot Token Scopes and click on Add an OAuth Scope Button.

Click on Add an OAuth Scope Button
Click on Add an OAuth Scope Button

7. Now select channels:history permission from the dropdown list.

channels:history permission
channels:history permission

8. Now you’ve changed the permissions and also created the slash command so now you need to re-install your app to the workspace. Scroll to the top of the same page and you’ll find the Reinstall to Workspace button under your Bot Token, click on it and then click on Allow.

Now all your changes are saved and you’re ready to code your bot for the slash commands.

Diving Into the Code

Creating a Flask server for Request URL through Repl

You can create a Flask server and host it on Repl for free. For this, you need to have a Repl account. If you do not have a Repl account, you can check this out and create one. Once you’ve created your Repl account, you can log in with that account on Repl and

1. Create a new repl by clicking the + button on the top right corner of the page and selecting the python language as a template and giving the title you like (here Slack Bot Creating Slash Commands) and clicking on Create Repl.

Creating a new repl
Creating a new repl

2. Now your Repl is created and you’re editing the main.py file. Add the following command to main.py file.

from keep_alive import keep_alive
keep_alive()

3. Now click on Add File button on the left side toolbar of the page to create a new file and name it as keep_alive.py.

Creating New File

4. Add the following code to keep_alive.py file to create a flask server.

Code for Flask Server

Importing Libraries

At first, you need to import Flask and Thread module to create a flask server. As Repl automatically downloads all imported libraries you need not install them and you can directly import them. You’ll need two libraries, a flask to create a webserver, and threading to keep the server running.

from flask import Flask, request, Response
from threading import Thread
Creating Flask App

Now, create a flask app.

app = Flask('')
Routing Flask App to Home Page

Create a route for the webserver. This is to create different pages with the given name on the server. Each route is assigned with a particular function to return a response whenever that page is triggered. For now, we’ll get something displayed on just the homepage of the website. In order to create a function for the home page, you can just route the app to ‘/’.

@app.route('/')
def home():
    return "The bot is alive!!"
Running the Flask Server

Now you’ll run the flask app and keep it alive using threading.

def run():
  app.run(host='0.0.0.0',port=8080)

def keep_alive():
    t = Thread(target=run)
    t.start()

Now, click on the Run button on the top of your Repl to run the code.

Run Button
Run Button

Now your server has started and you can find the server’s link in the URL bar above the web preview.

Web Preview
Web Preview
Now, you've got a public URL for yourself and you can create different pages for that url and configure them as you want. For example: here we got https://Slack-Bot-Creating-Slash-Commands.ahens.repl.co as our public url and we want to create a greet command but that cannot directly trigger our host url (if it does so we'll have to create different server for other command) so inorder to create several slash commands with the same server we can assign each commands to different pages on the same server. Here we want to create a greet command so we'll create a "greet" page on the server and it after the main url as "https://Slack-Bot-Creating-Slash-Commands.ahens.repl.co/greet" and add this url as request URL while creating the slash command as shown above.

Complete Server Code

from flask import Flask, request, Response
from threading import Thread

app = Flask('')

@app.route('/')
def home():
    return "The bot is alive!!"

def run():
  app.run(host='0.0.0.0',port=8080)

def keep_alive():
    t = Thread(target=run)
    t.start()

Saving and Importing Bot Token

Importing Libraries

As you did in the previous tutorial, in a similar way, you’ll have to create an environment variable to hide your bot token and import it to your code using os, pathlib and python-dotenv libraries.

import os
from pathlib import Path
from dotenv import load_dotenv

Creating environment variable

In the previous tutorial, we saved the environment variable creating a .env file but repl has an inbuilt tab storing and securing environment variables. Click on the Secrets tab on the left icon bar of the page.

Secrets Tab
Secrets Tab

Now you can add the variable name (here bot_token) by which you want to call your token into your code and token as the value and click on Add new Secret.

Saving Bot Token
Saving Bot Token

Importing Environment Variable into Code

In order to import and call the variable you just saved, you can use similar code as in previous tutorial, it is as given below:

#Set the path of .env file using pathlib
token_path=Path('.') / '.env'
#loading env with load_dotenv function of python-dotenv module
load_dotenv(dotenv_path=token_path)
#saving bot api token as variable
bot_api_token=os.environ['bot_token']

Now your API token is imported to your code as environment variable and you can start calling by its variable name (here bot_api_token) whenever needed.

Creating Slash Command Responses

All these code stuffs for creating a Slash Command Response are to be added to the keep_alive.py file above Running the Flask App section.

Importing Slack

At first you’ll need to import python’s slack module to your code before creating a slash command. As Repl automatically installs all imported libraries, you need not install it here and can directly import it to your code using the following command

import slack_sdk as slack

If you’re using some other platform or local server, you can simply use the following pip command to install the slack library.

pip install slack_sdk

Setting up the client Listener

As you did in the previous tutorial, you’ll need to set up the client listener again using the following code, in a similar way.

client=slack.WebClient(token=bot_api_token)

Slash Command Responses

As of now, you’ve created a flask server, stored and imported the bot token, and added the request URL to the slash command. Now you need to create a route for your slash command. Remember the name of the page name you added while creating the request URL, use the same name for creating the route (here it was /greet).

Here, you’ll use @app.route('/greet', methods=['POST']) to create a route for the command on flask server and specify the POST method. Just below it you’ll define the function to be executed whenever the command is called. And then you can post the message to a channel using .chat_postMessage() as in previous tutorial which takes two parameters: one is channel name or id and the other is the text or message you want to send.

In order to send a message to the same channel where the command is used, you can use Flask’s request.form.get('channel_id') method to get the channel id where the command is called, store it as a variable and use the same variable as channel id while sending the message. In a similar way you can use request.form.get('user_id') to get the user id of the user who called the command.

@app.route('/greet', methods=['POST'])
def greet_command():
  data = request.form
  channel_id = data.get('channel_id')
  client.chat_postMessage(channel=channel_id, text="Howdy, How are you doing?")

Complete Code

from keep_alive import keep_alive
keep_alive()
from flask import Flask, request, Response
from threading import Thread
import slack_sdk as slack
import os
from pathlib import Path
from dotenv import load_dotenv

#Set the path of .env file using pathlib
token_path=Path('.') / '.env'
#loading env with load_dotenv function of python-dotenv module
load_dotenv(dotenv_path=token_path)
#saving bot api token as variable
bot_api_token=os.environ['bot_token']

client=slack.WebClient(token=bot_api_token)

app = Flask('')

@app.route('/')
def home():
    return "The bot is alive!!"

@app.route('/greet', methods=['POST'])
def greet_command():
  data = request.form
  channel_id = data.get('channel_id')
  client.chat_postMessage(channel=channel_id, text="Howdy, How are you doing?")
  return Response(), 200

def run():
  app.run(host='0.0.0.0',port=8080)

def keep_alive():
    t = Thread(target=run)
    t.start()

You can also find the complete code on my Repl or GitHub workspace.

Output

Slack Python Bot - Creating Slash Commands
Slack Python Bot – Slash Commands Response

Conclusion

So, now you’ve learned to create a slash command for your slack python bot. Now you can use this script to create your own slash commands making your slack python bot perform specific tasks. You can create such bots and host them on different servers to keep them alive 24×7 and you can sell them to companies to earn from your bot. More and more functionalities will be added to the bot in upcoming tutorials.

Posted by Awebisam

I am Awebisam, a tech and economics enthusiast with native roots in Python and JS. Apart from those, TS and Golang are also my type of things.
I work with Django, FastAPI, Vue and Nestjs. Also slightly familiar with Flask, Express, and Svelte.

~ Awebisam, Aashish Bhandari

One thought on “Slack Python Bot – #2 Creating Slash Commands”

  1. It is very detailed and can understand even i am new to slack and been able to implement slash command on my own.Iam very much thankful for this blog.

Leave a Reply

Your email address will not be published. Required fields are marked *