Slack Notifications With Python
Slack bots are used these days for many purposes. Maybe you want to notify your team members when a new issue has been assigned to them on Github or you want your team to be up to date .
Though we won’t be showing how to write a Slack bot in this post, the knowledge you gain here is a first step to writing your own bot using Python.
Requirements
- A Slack team you belong to
- Python 3 installed
It is much advisable to use Python virtual environments when writing code, so we will create our virtual environment named slack_env using the terminal or command prompt, activate it and install Python’s popular requests library
python3 -m venv slack_env
source slack_env/bin/activate
pip install requests
Next you have to hit http://api.slack.com, click on Your Apps, click on Create New App, give it a name and select your Slack Workspace that will be used. You should now see a page that looks like this
Select the first item (Incoming Webhooks) and activate it as below.
We are almost there. Scroll to the bottom of the page and add a click on Add New Webhook to workspace and select a channel(or person) you want to notify. You can add as many webhook urls as you want and we are good to go. It is with this webhook url(s) that we will send post requests to notify those in the channel. Enough of the configurations. We are good to go.
Let us then write a simple function that takes the webhook url and message as parameters and sends a slack notification to the channel(or user) with the said webhook url
The Code
import requests def send_slack_notif(webhook_url, message): response = requests.post(webhook_url, json={'text':message}) if response.status_code != 200: print("Error sending notification .Status code {}".format(response.status_code)) else: print("Notification successfully sent")
With the code block above, you can start notifying your team mates about what you want them to be notified about. For more, check the Slack API for formatting and @mentioning users
Conclusion
If you created the webhook url to a slack channel you belong to, or to a team member, they will receive an alert that you installed the app to the channel and if you run the application by calling the function above with appropriate parameters, the user(s) will be notified.
© 2019 Ngenge Senior