KeiruaProd

I help my clients acquire new users and make more money with their web businesses. I have ten years of experience with the technical aspects of growing SaaS projects using data science for decision-making. If that’s something you need help with, we should get in touch!

Slack notifications from Python

Sending notifications to slack from an app is surprisingly easy.

You need to have a webhook URL, that will allow you to post things in your channels. It involves a few steps. Some can be done programmatically:

  1. Create a Slack app (if you don’t have one already)
  2. Enable Incoming Webhooks
  3. Create an Incoming Webhook (for the channel you want to send things to)

Then, you can send things with a POST request:

import json

import requests

def send_slack_message(
        text="Hello world :robot:",
        webhook_url='https://hooks.slack.com/services/MY/WEBHOOK/URL'
    ):
    if webhook_url is None:
        raise ValueError("You must provide a valid webhook URL")
    response = requests.post(
        url=webhook_url,
        data=json.dumps({"text": text}),
        headers={"Content-Type": "application/json"},
    )
    if response.status_code != 200:
        raise ValueError(
            f"Request to slack returned an error {response.status_code}, the response is:\n{response.text}"
        )

send_slack_message(text="yeah!", webhook_url="...")

Then, you can expand on this snippet, and take full advantage of Slack’s features:

See a typo ? You can suggest a modification on Github.