Skip to content

Instantly share code, notes, and snippets.

@chtitux
Created April 5, 2019 08:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chtitux/0fceb3bbe8c8a0e0a8f4decf06ab4604 to your computer and use it in GitHub Desktop.
Save chtitux/0fceb3bbe8c8a0e0a8f4decf06ab4604 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Fail script if any command fails
set -e
function usage {
local script_name
script_name=$(basename "$0")
cat <<HELP
$script_name (options) <message>
Send a message to slack
Typical usage:
echo "hello" | $script_name -n me -c #general -s subject
Options:
-n: Nickname to speak as
-c: Specific Slack channel to speak to
-s: Title of the message
-h: display this help
HELP
exit 0
}
SLACK_CHANNEL="#general"
NICKNAME="grobot"
INCOMING_WEBHOOK="T0XXXXXXX/BYYYYYYY/vZZZZZZZZZZZZZZZZZZZZZ"
URL="https://hooks.slack.com/services/${INCOMING_WEBHOOK}"
while getopts "n:c:s:h" option; do
case $option in
c) SLACK_CHANNEL=$OPTARG ;;
n) NICKNAME=$OPTARG ;;
s) SUBJECT=$OPTARG ;;
h) usage ;;
esac
done
if [ -z "${SUBJECT}" ]; then
echo -e "E: Missing subject to your message.\n"
usage
exit 1
fi
PAYLOAD='"channel": "'"${SLACK_CHANNEL}"'","username": "'"${NICKNAME}"'", "text": "'"${SUBJECT//\"/\\\"}"'"'
if grep -q "${NICKNAME}" "$(dirname "$0")/icon_nicknames"; then
PAYLOAD=${PAYLOAD}', "icon_url": "https://www.example.com/icons/'${NICKNAME}'.png"'
fi
text=""
while IFS= read line; do
text="$text\n${line//\"/\\\"}"
done
ATTACHMENTS='[{"text": "'"$text"'", "fallback": "'"$text"'"}]'
FORM_DATA='{'"$PAYLOAD"', "attachments": '"$ATTACHMENTS"'}'
curl -s -d "$FORM_DATA" "$URL"
printf "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment