Sending Message to Slack

We often get requirement to send data to slack as a part of any notification activity in any automation requirements. It could be as simple as an alert message or bit complicated as initiating a workflow. The below code snippit simplifies that messaging using native python libraries.


# Posting to a Slack channel
def send_to_slack(post):
    from urllib import request, parse
    import json
    try:
        json_data = json.dumps(post)
        req = request.Request("https://hooks.slack.com/services/YYYYYYYYYY",
                              data=json_data.encode('ascii'),
                              headers={'Content-Type': 'application/json'})
        resp = request.urlopen(req)
    except Exception as em:
        print("EXCEPTION: " + str(em));
#Prepare the message
post={"text":"There is a drift in the ","username":"Thiyagu","icon_emoji":":ghost:"}
#call the function
send_to_slack(post)

Leave a Reply

Your email address will not be published. Required fields are marked *

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