Saturday, March 19, 2022

Post a message in Slack

Using python, we can send automated messages to slack. In this post, we will use the webhook provided by slack to post messages in slack.

Let's follow the step-by-step process.

First, we will generate the webhook URL.

  1. Log in to your slack workspace. 
  2. Under apps, click on "Add Apps".
  3. In the search box, write "Incoming webhook" and search.
  4. Once you see "Incoming Webhook" under Available Apps, click on Add button.
  5. Click on the "Add to Slack"
  6. Select a channel or create a channel where the bot will post the messages.
  7. Now, click on the "Add Incoming Webhooks integration" button.
  8. The above step will give us a webhook URL. Copy this URL.

Now, it's time to use the webhook URL from python.

Go to your python editor and paste this code:

Make sure to update the url with the one you copied. Also, you can change the username that you will be displayed to show who has posted the message.


import json
import requests

url = 
'https://hooks.slack.com/services/Txxxxxxxxx/xxxxxxxxxxxxxxxxxxxxxxxxx'
headers = {'Content-Type' 'application/json' }
slack_data = {     
"username" "Demo bot" ,     
"icon_emoji" ":satellite:" ,     
"attachments" : [
 {            
"color" "#FF0000" ,             
"fields" :[
   {             
"title" "Test Message" ,
"value" "Hello, This is from Python" ,
"short" "false",
    }
 ]
  }
]
}

response = requests.post(url, data=json.dumps(slack_data), headers=headers)

print( 'Slack response' , response.status_code)


 

Once you run the code, you will see something like this on slack.

No comments:

Post a Comment