A reusable Python class for sending Slack messages

Use a Slack app to send useful notifications to your organization’s Slack channels

Photo by Pankaj Patel on Unsplash

The code for this article can be found here.

I have a lot of automated jobs running as part of my day-to-day operational activities. Most of these are Python applications are doing transformations on data, running machine learning models on batches of data as well as other activities that run on a schedule. Now, we have extensive logging going out from these applications to an ELK stack, but I like to have something I can look at on my phone to see whether a job ran on time or if it errored out. Enter Slack with their Messaging API, which I have used to set up a small reusable Python class that I can integrate in to all my apps to send messages on how scheduled runs went. This way I can stay on top of stuff that may have failed or didn’t run on time, and mitigate issues before they blow up without my knowing for a few days.

To do something like this, you need to first go on Slack and create an app to get an Incoming Webhook. Incoming webhooks are an easy way to simply send formatted messages to Slack channels in cases where you don’t need all the bells and whistles of the Slack API. In line with Slack’s documentation on message templates that can be sent to a webhook, I’ve created the following JSON template:

{
"blocks": [
{
"text": {
"text": "My Message",
"type": "mrkdwn"
},
"type": "section"
}
],
"channel": "#my-channel",
"icon_emoji": ":robot_face:",
"username": "test-bot"
}

The username , icon_emoji (this would need to be an emoji available in your Slack workspace) and channel parameters can be set to whatever you need.

  • username : This is the username that your message will show up as ‘from’ on Slack.
  • channel : A channel within your workspace that you send your messages to.
  • icon_emoji : This will show up at the profile picture of the ‘from user’ on Slack. When setting this, make sure you use the code from an emoji that is actually available in your workspace. Works for workspace-custom emoji too!

There’s a whole bunch of other stuff you can do with this template, including things like attaching polls, images, and doing fancy markdown.

Here’s the class that actually does the work of sending the message:

import json
import requests


class SlackNotifier:
def __init__(self, slack_webhook_url: str):
super().__init__()
self.slack_webhook_url = slack_webhook_url

def send_slack_message(self, message: str):
with open("slack_message_template.json") as f:
message_template = json.load(f)
if len(message) > 39000:
# Slack has a limit of 40000 chars, let's truncate it a bit
message_to_send = (
message[:39000] + "...(message too long for Slack, truncated.)"
)
else:
message_to_send = message
message_template["blocks"][0]["text"]["text"] = message_to_send
requests.post(self.slack_webhook_url, json=message_template)

You need to provide the Slack webhook URL you received earlier to instantiate the class. Then it’s just a matter of calling the send_slack_message function off an object of this class, and you can send your messages. It picks up the Slack message template file we created earlier, injects the message in to the relevant part (this will need to be changed appropriately if you changed the template significantly) and sends it to the Slack webhook using the requests library.

To use this class, we can have a simple main.py :

import os
from slack_notifier import SlackNotifier
def main():
slack_webhook_url = os.environ.get("SLACK_WEBHOOK_URL", "https://my-slack-webhook")
slack_notifier = SlackNotifier(slack_webhook_url)
slack_notifier.send_slack_message("Your message here.")
if __name__ == "__main__":
main()

As you can see, this script picks up the SLACK_WEBHOOK_URL from an environment variable. You can set this easily before running by doing something like export SLACK_WEBHOOK_URL=”https://slack-webhook-url” .

If you set everything up right, you should be able to use this to send a message to any Slack channel within your workspace that your Slack app has access to. The template I used above generates something like this:

A sample message

You can take the SlackNotifier class into any of your applications and import and use it very easily to manage sending messages to Slack and notifying yourself and your team about whether they are running correctly, and even spice up your messages with custom emoji and formatting.

Personally, I prefer to use the :this_is_fine: emoji for everything.

https://chatbotslife.com/


A reusable Python class for sending Slack messages was originally published in Chatbots Life on Medium, where people are continuing the conversation by highlighting and responding to this story.


Posted

in

by

Tags: