DEV Community

Ashiqur Rahman
Ashiqur Rahman

Posted on • Updated on

Programmatically notifying events to slack channel from python

Suppose, you are in charge of developing a back-end of an E-Commerce website and maybe the the company sales team wants to be notified every time a customer places an order into a specific slack channel. Let's see how we can achieve this easily using the slack API.

For this post, we will assume our back-end is written using a python based web framework like django/flask/fastapi. But, we can do this using any framework. This is because, all we need to do is to make a http POST request and we can do that using any language we want.

Creating a new Slack app

  1. Click the + Add apps button
    Slack-Add-New-App

  2. Click Browse App Directory
    Browse App Directory

  3. This will take you to an external link which will be opened in your browser.
    Now, click build
    Slack Build

  4. On the next page click Create an App
    Create an App

  5. Choose From Scratch
    From Scratch

  6. Lets name our app "Order-Alert-Bot" and choose our slack workspace.
    Order-Alert-Bot

  7. Enable Incoming Web hooks for our app
    Incoming Web hooks
    Add New

  8. Specify the channel at which this bot should post.
    Specify the channel

  9. Now, a new webhook url would be added for this app. We just need to copy the Webhook url. This will be the api endpoint at which we will make our http POST request.
    copy webhook url

Invoking the Slack API.

Lets, assume we set the environment variable SLACK_ORDER_ALERTS_BOT_WEBHOOK_URL with the value of the webhook url we copied.

def slack_notify_new_order(order_id: int, username: str, amount: float):

    details = f'[Details](https://admin.mysite.com/core/order/{order_id})'
    message = f'*{username}* has placed a new order of amount *{amount}*. {details}'
    payload = {'text': message}

    import requests
    import os

    response = requests.post(
        os.environ.get('SLACK_ORDER_ALERTS_BOT_WEBHOOK_URL'),
        data=str(payload)
    )
    return response
Enter fullscreen mode Exit fullscreen mode

This is just a demo message we are building with some possible parameters. For your use case, you can interpolate whatever values you need to your slack message string.

Now, we can just call this function anywhere in our code and our bot will send a message to the specified channel. For example, if we are using django, we can just call this function inside the api view function that handles a new order creation event. DONE :D
Slack Message

As expected, our order alerts bot is posting a message every time a customer places a new order.

Top comments (0)