Skip to content

Instantly share code, notes, and snippets.

@AndrewGearhart
Forked from dopiaza/slackpost
Last active November 17, 2017 17:23
Show Gist options
  • Save AndrewGearhart/979d81a2e0fccfca5942f315f1ef869e to your computer and use it in GitHub Desktop.
Save AndrewGearhart/979d81a2e0fccfca5942f315f1ef869e to your computer and use it in GitHub Desktop.
Post a message to a Slack channel
#!/usr/bin/env bash
# Usage: slackpost "<webhook_url>" "<channel>" "<username>" "<message>"
# also (echo $RANDOM; echo $RANDOM) |slackpost "<channel>" "<username>"
# ------------
webhook_url=$1
if [[ $webhook_url == "" ]]
then
echo "No webhook_url specified"
exit 1
fi
# ------------
shift
channel=$1
if [[ $channel == "" ]]
then
echo "No channel specified"
exit 1
fi
# ------------
shift
username=$1
if [[ $username == "" ]]
then
echo "No username specified"
exit 1
fi
# ------------
shift
text=$*
if [[ $text == "" ]]
then
while IFS= read -r line; do
#printf '%s\n' "$line"
text="$text$line\n"
done
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\":\"ghost\", \"attachments\":[{\"color\":\"danger\" , \"text\": \"$escapedText\"}]}"
curl -s -d "payload=$json" "$webhook_url"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment