DEV Community

David Akim
David Akim

Posted on

Create an Agebot in Slack using Python

In this lesson, we will go through the steps of creating a bot in the Slack messaging app which automatically determines the user's age based on the user's input. We will be implementing this app in Python and deploying it locally.

Prerequisites

  • Must be familiar with Python

Creating a Slack Workspace for AgeBot Project

Go to Slack and Sign in or Sign up with Email if you don't have an account.
After signing in, click Create Another Workspace or Create a Workspace. Fill out the required information. You can invite team members or create channels for specific topics.

Setting up the Slack Workspace for AgeBot Project

Create an app by going to Slack API apps. Click Create an App. If you have create apps before in Slack, this page will look different. In that case, there will be a Create New App button.

Image description

Click create From scratch

Image description

Give your app a name and choose a workspace to develop your app in. In this example, we will be using a workspace we have already created called Cyber Coder. Please use one of the workspaces you created. Click Create App.

Image description

Scroll down to Display Section. Give your app a Short description and Long description. Then click Save Changes.

Image description

Scroll up and click Bots.

Image description

Click Review Scopes to Add.

Image description

Scroll down to the Scopes Section. Under Bot Token Scopes, click Add an OAuth Scope.

Image description

Search for the following and add them. app_mentions:read views messages that directly mention @AgeBot in conversations that the app is in. chat:write sends messages as @AgeBot. im:history views messages and other content in direct messages that AgeBot has been added to.

  • app_mentions:read
  • chat:write
  • im:history

Image description

Scroll up to the OAuth Tokens for Your Workspace Section. Click Install to Workspace.

Image description

Click Allow.

Image description

Click Socket Mode under Settings and turn on Enable Socket Mode. Turning on Socket Mode will route your app’s interactions and events over a WebSockets connection instead sending these payloads to Request URLs. Since we will be running this app locally, we need to enable this feature.

Image description

Click Basic Information under Settings.

Image description

Scroll down to the App-Level Tokens Section. Click Generate Token and Scopes.

Image description

Give your App level token a name. Then click Add Scope. Select connections:write and click Generate. This setting will route your app's interactions and event payloads over WebSockets.

Image description

Copy this token in a notepad. Store this token in a variable call SLACK_APP_TOKEN. Click Done.

Image description

Scroll back up to the Building Apps for Slack Section. Click Add features and functionality Section. Then click Event Subscriptions. Turn on Enable Events.

Image description

Under the Subscribe to bot events Section, click Add Bot User Event. Select the following events. app_mention subscribes to only the message events that mention your app or bot. message.im checks if a message was posted in a direct message channel.

  • app_mention
  • message.im

Image description

Click OAuth & Permissions under Features. Under OAuth Tokens for Your Workspace copy the Bot User OAuth Token into a notepad. Store this token in a variable call SLACK_BOT_TOKEN.

Image description

Writing the Python code

This app will automatically calculate the user's age based on the user's input. To trigger this function, go on Slack and in the chat type @AgeBot [day-month-year]. For example, @AgeBot 25-12-2012. Given that the date of writing this blog is 30-11-2023 the response from AgeBot is 10.

Create a folder called agebot. Navigate into this folder by typing the following in the command terminal.

cd agebot
Enter fullscreen mode Exit fullscreen mode

Create a virtual environment by entering the following in the command terminal.

virtualenv venv
Enter fullscreen mode Exit fullscreen mode

Activate the virtual environment using the following command.

venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Install the required libraries: slack-bolt and python-dotenv

pip install slack-bolt
pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

Create a .env file and copy and paste your tokens here.

SLACK_APP_TOKEN = "YOUR APP TOKEN"
SLACK_BOT_TOKEN = "YOUR BOT TOKEN"
Enter fullscreen mode Exit fullscreen mode

Import the required libraries.

import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_sdk import WebClient
from datetime import datetime, date
import re

from dotenv import load_dotenv
load_dotenv()
import os
SLACK_APP_TOKEN = os.environ.get("SLACK_APP_TOKEN")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")

app = App(token=SLACK_APP_TOKEN)
client = WebClient(token=SLACK_BOT_TOKEN)
Enter fullscreen mode Exit fullscreen mode

Create a function to calculate the user's age. First we need to extract the date from the user input. Then we define the date format. The date string is converted to a datetime object. We call the function date.today() to get today's date. The difference between today's date and the user's input date is calculated. This result is then divided by 365 to get the number of years. Finally, return the result as a chat message.

def handle_age_request(channel, text):
    # Example string containing a date
    date_string = re.sub('<.*?>', '', text)
    date_string = re.sub(r"\s+", "", date_string)

    # Define the date format
    date_format = "%d-%m-%Y"

    # Convert the string to a datetime object
    date_object = datetime.strptime(date_string, date_format)
    dob = date_object.date()

    today = date.today()

    # Calculate the difference between the two dates
    delta = today - dob

    # Calculate the number of years
    years = delta.days // 365


    client.chat_postMessage(channel=channel, text=str(years))
Enter fullscreen mode Exit fullscreen mode

Create a function to handle app_mention. This function is called whenever a message mentions the app or bot.

@app.event("app_mention")
def handle_mention(event, say):
    channel = event.get('channel')
    text = event.get('text')
    handle_age_request(channel, text)
Enter fullscreen mode Exit fullscreen mode

Start the Socket.

print("Start your bot")
handler = SocketModeHandler(app, app_token=SLACK_APP_TOKEN)
handler.start()
Enter fullscreen mode Exit fullscreen mode

The entire script should look like this.

import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_sdk import WebClient
from datetime import datetime, date
import re

from dotenv import load_dotenv
load_dotenv()
import os
SLACK_APP_TOKEN = os.environ.get("SLACK_APP_TOKEN")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")

app = App(token=SLACK_APP_TOKEN)
client = WebClient(token=SLACK_BOT_TOKEN)

def handle_age_request(channel, text):
    # Example string containing a date
    date_string = re.sub('<.*?>', '', text)
    date_string = re.sub(r"\s+", "", date_string)

    # Define the date format
    date_format = "%d-%m-%Y"

    # Convert the string to a datetime object
    date_object = datetime.strptime(date_string, date_format)
    dob = date_object.date()

    today = date.today()

    # Calculate the difference between the two dates
    delta = today - dob

    # Calculate the number of years
    years = delta.days // 365


    client.chat_postMessage(channel=channel, text=str(years))


@app.event("app_mention")
def handle_mention(event, say):
    channel = event.get('channel')
    text = event.get('text')
    handle_age_request(channel, text)


print("Start your bot")
handler = SocketModeHandler(app, app_token=SLACK_APP_TOKEN)
handler.start()

Enter fullscreen mode Exit fullscreen mode

Now go to your workspace in Slack. In any of your channels, start a conversation with @AgeBot. You may get this message "You mentioned @AgeBot, but they’re not in this channel". Click Invite Them. You can now message @AgeBot. Type @AgeBot 25-12-2000. Given that the date of writing this blog is 30-11-2023 AgeBot will respond with 22. This concludes our lesson.

Top comments (0)