Month: October 2015

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.

I had to revisit the requests module in order to post to Slack. 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.

The integration helpfully displays a curl command for posting to any channel which can be replicated in Python with only minor changes

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. The example provided by Slack provides all three.

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.