How to send a Slack message in Python using webhooks

It’s really easy to send Slack messages using Python. In this project, we’ll create a really basic Slack app that uses webhooks to send a Slack message.

How to send a Slack message in Python using webhooks
Picture by Scott Webb, Unsplash.
3 minutes to read

Slack is a great tool for data scientists and data engineers and is now being adopted across businesses, so it’s probable that you already use it in your workplace. Besides being a great tool for quick communications, it’s also perfect for alerting.

In this project, we’ll create a really basic Slack application that you can use to send messages or alerts to specific channels using the webhooks system. This is really easy to do in Python, and you can add Slack messaging functionality to your application in just a few minutes. Here’s how it’s done.

Create a Slack channel

You can configure your Slack app to post to a shared channel, so everyone in your team can see the message, or use a private channel, to which only you have access.

png

Create a Slack app

First, head over to the Slack website and register a new Slack app using your account. Give your app a name, add it to your workspace, then click Create App to finalise it.

png

Allow Incoming Webhooks

In order for your Slack app to take advantage of the easy-to-use webhooks functionality, you need to click the “Incoming Webhooks” button and set the toggle switch to “On”. Once this is in place, we can just send some data to the webhook URL using a POST request.

png

Scroll to the bottom of the page and click “Add New Webhook to Workspace” and give it access to the channel you created above, then save the details. After saving, you’ll be redirected back to the Webhooks page, where you’ll find your webhook URL.

Load the packages

Next, open up a Python script or a Jupyter notebook and import the requests and json packages. These are pre-installed, so there’s no need to use pip.

import requests
import json

Create a function to send a Slack message

The actual code required to send a Slack message in Python is very simple indeed. We just create a simple dictionary (known as a payload) containing our data, then we use json.dumps() to convert it to JSON, then we use requests.post() to POST the data to our webhook address.

def send_slack_message(payload, webhook):
    """Send a Slack message to a channel via a webhook. 
    
    Args:
        payload (dict): Dictionary containing Slack message, i.e. {"text": "This is a test"}
        webhook (str): Full Slack webhook URL for your chosen channel. 
    
    Returns:
        HTTP response code, i.e. <Response [503]>
    """

    return requests.post(webhook, json.dumps(payload))

Execute the function

Finally, we can construct a simple payload dictionary, define our webhook URL, and pass the values to our send_slack_message() function. Run the code and you should see the Slack message appear in your account a split second later.

webhook = "https://hooks.slack.com/services/XXXX/XXXX/XXXX"
payload = {"text": "Anomaly detected!"}
send_slack_message(payload, webhook)

This is obviously the most basic of examples, however, you can do a lot more with Slack messages. If you want to make your Slack messages a bit richer, check out Slack’s Bolt framework, which allows you to control the display of your messages with style.

Matt Clarke, Thursday, March 11, 2021

Matt Clarke Matt is a Digital Director who uses data science to help in his work. He has a Master's degree in Internet Retailing (plus two other Master's degrees in different fields) and specialises in the technical side of ecommerce and marketing.

Introduction to Python

Master the basics of data analysis in Python . Expand your skillset by learning scientific computing with numpy.

Start course for FREE

Comments