A Bash Function for Sending Slack Notifications
For my small personal projects, I usually use Slack as a central notification and logging system to help me keep track of the state of my applications.
Below is a simple bash function that I use a lot in many of my bash scripts in order to send a notification to a Slack channel:
######
# Send notification messages to a Slack channel by using Slack webhook
#
# input parameters:
# $1 - message level: 'INFO' | 'WARN' | 'ERROR'
# $2 - pretext
# $3 - main text
######
SLACK_WEBHOOK_URL=xxx
SLACK_CHANNEL=xxx
send_notification() {
local color='good'
if [ $1 == 'ERROR' ]; then
color='danger'
elif [ $1 == 'WARN' ]; then
color = 'warning'
fi
local message="payload={\"channel\": \"#$SLACK_CHANNEL\",\"attachments\":[{\"pretext\":\"$2\",\"text\":\"$3\",\"color\":\"$color\"}]}"
curl -X POST --data-urlencode "$message" ${SLACK_WEBHOOK_URL}
}
To make it work, you can copy the snippet to your script. Then just fill the SLACK_WEBHOOK_URL
with the webhook url you get from Slack, and the channel name you want the message to be sent to in the SLACK_CHANNEL
variable.
After the simple setting, you can call the function like this:
send_notification 'INFO' "Message Title" "some long text message"
Hope you will like it!