Create an Agebot in Slack using Python
Tags: python, slackbot
Published: 2023-11-30 01:41:06

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](https://slack.com/) 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](https://api.slack.com/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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otr6moosbhi33osdlln0.jpg)


Click create **From scratch**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/88uhsx0xluxx65erfndd.jpg)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fjibq3qcggvrl9glq5g.jpg)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7panxpksdakr9cupspj1.jpg)


Scroll up and click **Bots**. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jhsqn0xtdwtv0w6y3z5.jpg)


Click **Review Scopes to Add**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w49tavy4t1komrd56uox.jpg)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/btgtfawovkn0j139xmg3.jpg)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a5zpvsr8hx5dyaiz4o8b.jpg)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rn11krza7skofja3vs7p.jpg)


Click **Allow**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6cd7pf2bshl7en046kjw.jpg)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d91gjn6moegfq86f9go5.jpg)


Click **Basic Information** under **Settings**. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pb13snzx06tl9fkpjp2k.jpg)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3qikhimnnpe1kmmhfrhx.jpg)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/404o7t3fjkrxl03wqwde.jpg)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b291l25ld85mcdfy57wy.jpg)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axdfq3v8cjgqmw6s4ajw.jpg)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zl344hvv6re1h9d3yat9.jpg)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j9bztj3hoei6lq3gx1rn.jpg) 

## 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
```

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

```
virtualenv venv
```

Activate the virtual environment using the following command.

```
venv\Scripts\activate
```

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

```
pip install slack-bolt
pip install python-dotenv
```

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

```
SLACK_APP_TOKEN = "YOUR APP TOKEN"
SLACK_BOT_TOKEN = "YOUR BOT TOKEN"
```

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)
```

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))
```

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)
```

Start the **Socket**.

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

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()

```

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.