Building a Serverless Slack App using Python and AWS SAM
Tags: slack, python, aws, serverless
Published: 2024-01-28 19:43:09

Slack, a widely used collaboration platform, enables teams to communicate, share files, and collaborate effectively. By integrating custom Slack apps, teams can enhance this experience by automating tasks and adding unique functionalities tailored to their specific needs.

One way to deploy Slack apps is through a serverless architecture, which offers several advantages such as scalability, cost-efficiency, reduced operational burden, and increased development speed.

This guide will walk you through the process of building a serverless Slack app using AWS and Python. It provides a step-by-step approach to leverage these benefits and enhance Slack's capabilities effectively and efficiently.

> 💡You can find the complete code for this tutorial at the following link: [GitHub Repository](https://github.com/tagorenathv/serverless-slack-app/tree/master). 
> Dive in to explore and use the code for building your serverless Slack app.

## Step 0: Setup

Before starting your serverless Slack app project, ensure you have the following set up:

1. An AWS account for deploying and managing your app.
2. AWS CLI is installed on your machine for easy AWS services interaction.
3. AWS SAM (Serverless Application Model) for streamlining serverless app development.
4. Python and pip for writing your app and managing dependencies.

With these tools, you're ready to build and deploy your serverless Slack app efficiently.

## Step 1: Create a new AWS SAM project

To begin building your serverless Slack app, use the AWS SAM CLI to create a new project. Open your terminal and run the following command:

```
sam init --runtime python3.10 --name serverless-slack-app --app-template hello-world
```
This command will create a new AWS SAM project with a basic "Hello World" function. It sets up the necessary structure and files for your app as below:

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

## Step 2: Configure the Slack app

- **Create a New App:** To interact with the Slack platform, you need an app. To set up your Slack app, visit https://api.slack.com/apps, click on “Create New App”, select “From Scratch”, then enter your “App Name” and choose the workspace you want to install it in.

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

- **Configure OAuth & Permissions:** Go to the 'OAuth & Permissions' tab. Specify the scopes your app requires to operate. These scopes define the permissions your app has in the Slack workspace, like sending messages or accessing user data.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5o5i7s6qa6bwddi0b98o.png)

- **Install App to Workspace:** Once the permissions are set, install the app to your workspace. This step might prompt you to authorize the app with the specified permissions.

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

- **Obtain API Credentials:** Once the App is installed, you can find an OAuth token. This we will be using further in our app to communicate with Slack.

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

### Step 3: Implement the Slack functionality

Navigate to the AWS SAM project and follow these steps:

- Add `slack-sdk` dependency to `requirements.txt` file
- In `app.py` file implement the necessary code to handle Slack events and commands. 
As part of the blog, we will have code to respond url_verification challenge & app_mention.

```json
# Parse the incoming event data from Slack
slack_event = json.loads(event["body"])

# Check for URL verification during the event subscription process
if slack_event.get("type") == "url_verification":
    # Respond with the challenge token to verify the endpoint
    return {"statusCode": 200, "body": slack_event.get("challenge")}
elif slack_event.get("event"):
    # Extract the event data
    data = slack_event.get("event")
    event_type = data.get("type")

    # Check if the event is an app mention
    if event_type == "app_mention":
        # Get the channel ID from the event data
        channel_id = data.get("channel")
        # Post a greeting message in the channel where the app was mentioned
        client.chat_postMessage(channel=channel_id, text="👋 Hello there! I'm Serverless Slack App, here to make your day a little easier. 😊")
        return
```

You can leverage the power of Python to process events and perform operations with Slack, such as sending messages, retrieving information, or triggering external services. The Python Slack SDK provides an interface for interacting with the Slack API, simplifying development.

Slack's Block Kit is a UI framework for creating rich and interactive app interfaces. It allows you to build engaging messages and modals, enhancing the user experience. By combining the Python Slack SDK with Block Kit, you can develop user-friendly Slack apps that provide a seamless and engaging interaction.

### Step 4: Deploy the app

Once you have implemented the desired functionality for your serverless Slack app, it's time to deploy it to AWS Lambda. This allows your app to run in a serverless environment without the need to manage servers or infrastructure. 

Update `template.yaml` file as below:

- Remove the below blocks:

```yaml
# remove Events section in HelloWorldFunction under resources:
Events:
  HelloWorld:
    Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
    Properties:
      Path: /hello
      Method: get

# remove HelloWorldApi section in Outputs:
HelloWorldApi:
  Description: "API Gateway endpoint URL for Prod stage for Hello World function"
  Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
```

- Add below blocks:

```yaml
# Add under HelloWorldFunction in resources section:
FunctionUrlConfig:
  AuthType: NONE
  InvokeMode: BUFFERED
  Cors:
    AllowCredentials: false
    AllowMethods:
      - POST
      - GET
    AllowOrigins:
      - "*"
Policies:
  - AWSLambdaExecute
Environment:
  Variables:
    SLACK_BOT_TOKEN: <your slack oauth2 token here>
```

To deploy your app, run the following command in your terminal:

```
sam build
sam deploy --guided
```

The AWS SAM CLI will guide you through the deployment process, prompting you to configure the deployment options and resources. Ensure to provide the necessary information, such as the AWS region, app name, and credentials.

Once deployed, you will see Cloudformation outputs as:

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

### Step 5: **Subscribe to Bot Events**

To set up event handling, go to the "Event Subscriptions" section in your Slack app settings and paste the Lambda Function URL you received after deploying your app. Slack will automatically send a verification challenge to this URL to validate the connection. Once Slack successfully verifies the URL, your app will be ready to receive and respond to events from Slack. Add required bot user events and save.

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

### Step 6: Test

After setting up your serverless Slack app, it’s essential to test it to ensure it responds correctly within your Slack workspace. Mention your app in a channel by typing `@serverless-slack-app Hello`. If everything is configured properly, the app should reply with a greeting. This confirmation indicates that your app is operational and ready to interact with users in your workspace.

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

### Resources

- Github repo for this blog: https://github.com/tagorenathv/serverless-slack-app
- Serverless ShiftRoster app link: https://github.com/tagorenathv/slack-shift-roster
- New slack workspace link: https://slack.com/get-started#/createnew
- Slack Python guide: https://slack.dev/bolt-python/tutorial/getting-started
- AWS SAM: https://docs.aws.amazon.com/serverless-application-model/

### **Wrapping Up**

Wrapping up, you now have a foundational serverless Slack bot, poised for expansion and customization. The journey doesn't end here; the Slack API, coupled with Python's versatility, opens up a plethora of opportunities for further development.

**Stay curious, keep coding!🚀**