Posting to Slack

The Python httplib and related modules work but make life harder than it needs to be. Thankfully, the requests module acts as a wrapper and makes issuing HTTP requests as simple as you would expect. Installation of the module is with pip as you would expect and there is a decent introductory guide on the site.

This tutorial provided by Slack provides all the details required for using the webhook to post. I wanted my orchestration server to keep everyone updated when deployments happened and this seemed like a good solution. A few steps to install the Incoming WebHooks integration and everything was ready.

Using the requests module to post to the webhook is just a few lines as follows:

import requests
# see your integration config for webhook URL
webhookurl = 'https://hooks.slack.com/services/...'
payload    = { 'text': 'This is a test post' }
response   = requests.post(webhookurl,json=payload)
print("%d - %s" % (response.status_code,response.reason))

To change the channel to post to, the displayed user/bot name or the icon just add the necessary keys to the payload dictionary; see the sending messages documentation here. If a plain message is too boring for you, see the message composition documentation here for making more complex messages.

At present I just want to push messages to the channel but for those feeling more adventurous you can try building a full chatbot. There are a couple of Python modules already to start you off but I’ve not had chance to try any of them yet.

Published by Quackajack

I started off as a programmer, who moved to support (setting up 2 service desks from scratch), then on to system administrator and then into configuration management. Now I combined all these as a DevOps engineer.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.