How to send a message to Slack from your Python program
We use and love Slack for team messaging. We’re all in and out Slack throughout the day (and night). We depend on it for communication of our geographically distributed team.
We also have lots of automated processes/jobs/programs running. Sometimes those things need to communicate with us and let us know some results. Our solution is to have the programs (Python in this case) send us a message in the appropriate Slack channel.
Slack provides Incoming Webhooks and they have a pretty nifty Incoming Webhooks documentation guide. However, the guide only tells you what they expect you to do, but it doesn’t really explain what you actually need to do.
The first thing to do is find out from Slack the correct URL you’ll use to post your messages. You’ll need to Add Configuration on the Incoming WebHooks page. Go to https://my.slack.com/services/new/incoming-webhook/ (you may be prompted to log in). Choose the channel to which you want to send messages and then Add Incoming WebHooks Integration. Note that you can find the Display Name and change what will appear in the channel. Slack gives you the URL to which you’ll be posting your messages. Sweet!
# Posting to a Slack channel
def send_message_to_slack(text):
from urllib import request, parse
import json
post = {"text": "{0}".format(text)}
try:
json_data = json.dumps(post)
req = request.Request("https://hooks.slack.com/services/your/slack/URL",
data=json_data.encode('ascii'),
headers={'Content-Type': 'application/json'})
resp = request.urlopen(req)
except Exception as em:
print("EXCEPTION: " + str(em))
send_message_to_slack('Dude, this Slack message is coming from my Python program!')
You can integrate the code pretty easily and let your programs communicate with the team. Have at it, Hoss!
