Firstly you need to create webhook url in slack. How to do it you can find at https://www.programmableweb.com/news/how-to-integrate-webhooks-slack-api/how-to/2015/10/20
Secondly you need for example a bash script. My version you can find in gist:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Usage: date | sh slackpost.sh | |
# Usage: echo "Hello Word" | sh slackpost.sh | |
webhook_url=https://hooks.slack.com/services/……………… | |
username="PI" | |
channel=logs | |
icon_emoji=":ghost:" # https://slackmojis.com/ | |
#load all message to var | |
while read LINE; do | |
text="$text\n$LINE" | |
done | |
#Default validation | |
if [ "$webhook_url" = "" ]; then | |
echo "No webhook_url specified" | |
exit 1 | |
fi | |
if [ "$channel" = "" ]; then | |
echo "No channel specified" | |
exit 1 | |
fi | |
if [ "$text" = "" ]; then | |
echo "No text specified" | |
exit 1 | |
fi | |
escapedText=$(echo $text | sed 's/"/\"/g' | sed "s/'/\'/g" ) | |
json="{\"channel\": \"$channel\",\"username\": \"$username\",\"icon_emoji\": \"$icon_emoji\",\"text\": \"$escapedText\"}" | |
#by success returned 'ok' | |
status="$(curl -s -d -X POST –silent –data-urlencode "payload=$json" "$webhook_url")" | |
if [ "$status" != "ok" ]; then | |
# there were problems at curl request | |
# place to log error | |
echo "curl error" | |
fi |
For comfort usage I have copied it to bin folder
cp /current/path/to/slackpost.sh /usr/local/bin/slackpost.sh chmod +x /usr/local/bin/slackpost.sh
Now you cant access this script anywhere by typing :
command_with_textual_output | slackpost.sh
Practically you can use it to get info about errors or notifications. Maybe you want to get notification about successfully database backup.
#sh way echo "Your database backup was created successfully" | slackpost.sh #python way os.system("echo 'Your database backup was created successfully' | slackpost.sh")
Personaly I’m using it for notifying me if any of monitored website is offline – https://mindau.de/blog/en/simple-way-monitor-websites-linux/
One thought on “[EN] Post messages to slack from linux”