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
This will take you to an external link which will be opened in your browser.
Now, clickbuild
Lets name our app "Order-Alert-Bot" and choose our slack workspace.
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.
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
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
As expected, our order alerts bot is posting a message every time a customer places a new order.
Top comments (0)