Blog

Python-Slack Integration

image

This step by step guide will show you how to integrate slack with Python. 

Integrating Slack with Python

  • Add an incoming webhook to the channel you want to receive messages.

  • In your Ubuntu server create a python file (name.py)  

  • This is the code you will place in the file:

 
import sys

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("Your Slack URL goes here",

                             data=json_data.encode('ascii'),

                             headers={'Content-Type': 'application/json'})

       resp = request.urlopen(req)

   except Exception as em:

       print("EXCEPTION: " + str(em))

if len(sys.argv) < 1:

   print("you did not give any arguments\n")

else:

send_message_to_slack(sys.argv[1:])

  • Now on the command line type “python3 file.py “Hello” and the message “Hello” will be sent to your slack channel