Overview

Slack is a great channel to share reports and alerts. With Python and AI, creating a Slackbot catered to your specific needs has never been easier.

Here are some examples of alerts and reports you may want to create:

  • Automated alerts based on a certain metric threshold. For example if your weekly active users drop by a certain percentage.
  • Weekly marketing pipeline reports
  • Lists of self-service onboarded users in the past 24 hours

Your options are limitless and fully customizable to your needs.

Step-by-step guide to creating a Slackbot

This step requires admin access to your Slack workspace.

Step 1: Creating a Slack app and token

To create these alerts and scheduled Slack reports, we’re going to create a custom Slack app. Start by navigating to the Slack app API page and click Create New App.

Follow these steps:

  1. Opt in to Create from scratch
  2. Provide a name and the workspace you want the app to be added to
  3. Click Create App

Once your app is create, on the left hand side, select OAuth & Permissions, then follow these steps:

  1. Under Scope and Bot Token Scopes click Add an OAuth Scope. If the bot is going to send messages to Slack, make sure you select the chat:write.public scope. This scope allows the app to write to publich channels they’re not a part of. If you need to add the app to private channels or chats, you will need to select additional scopes.
  2. Under OAuth Tokens on that same page, click Install to your_workspace
  3. Once the app is invited to your workspace, take note of the token. Your token should start with xoxb-. If it doesn’t, you may not have generated a bot token
Please handle tokens with care and never commit tokens to code repositories.

Step 2: Creating your bot in Python

Now that you have your Slack bot token, we can start creating an app that sends data to Slack.

Start by querying your data. Once you have the data you want to analyze in a DataFrame you can ask the AI to create your app.

Your Python script to create the app should look something like:

import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

var_a = 1
var_b = 2

# Add emoji based on comparison
emoji = '🔴' if var_a > var_b else '🟢'

# Push alerts to Slack with the bot token you generated
client = WebClient(token="xoxb-...")

try:
    response = client.chat_postMessage(
        channel="#analytics",
        text=f"Variable A is: {var_a} {emoji}\nVariable B is: {var_b}"
    )
except SlackApiError as e:
    print(f"Error sending message: {e.response['error']}") 

Step 3: Scheduling your bot

Once you’ve built your Slackbot and verified that it works, you can now schedule your app to run at whatever cadence you would like.

Just remember that if you’re app requires a query, scheduled runs will run that query. Consider the impact on your data warehouse and compute costs

Scheduling your bot to run is the same as scheduling a report. Check out our page on scheduling to learn more.