Send Notifications on Slack using Incoming Webhook

Slack API provides Slack Incoming Webhook to easily send data on slack in real time. We just need to follow some steps and we are ready to send messages on slack.

Setup Slack Incoming Webhook Integration into the slack workspace:
On page we can see the form to create Incoming Webhook Integration. Select channel on which you want to send a notification from the dropdown or you can create a new channel by clicking on the link create new channel.

enter image description here

Configuration Setting:
After submitting the form you will redirect to page Edit Configuration. On this page, We can see Setup Instructions and Integration Settings.

We can set the customise name and icon, also you can change the channel on which you want to post the message.

We also get Webhook URL on this page. This URL is required while sending messages on slack.

Preparing Message:
Slack uses normal HTTP request with JSON payload. We need to create the message with key/value pair in JSON.

  For eg.
{
   "text": "This is a line of text.\nAnd this is another one."

}

Send JSON body as HTTP Post request to your Webhook URL. The Content-Type header must be explicitly set to application/json. This tells Slack how to interpret the data you're sending.

Curl Example

curl -X POST -H 'Content-type: application/json' \
--data '{"text":"This is a line of text.\nAnd this is another one."}' \
https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX

Message Formatting:

  • To Add new line use \n.
  • To add link use <>

You can use Slack's standard message markup to add simple formatting to your messages.

Customise Channel
Even though we have set default channel at time of creating Webhook URL, we can send message on other channels as well. We just need to specify the name of channel in JSON body.

Example

 curl -X POST \
 -H 'Content-type: application/json' \
 --data '{"text": "This is posted to #general", "channel": "#general"}' \
 https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX

We can use Faraday to send POST request to Slack or There is a gem Slack-notifier which make it more easy.
For more information about Incoming webhook and message formatting check the link Incoming Webhook and Message Formatting

Thank you.

Send Notifications on Slack using Incoming Webhook
Share this

Subscribe to Engineering At Kiprosh