Skip to content

Instantly share code, notes, and snippets.

@nilium
Last active February 21, 2017 20:26
Show Gist options
  • Save nilium/8c7ed8527eb63c693f9c147233bfa01b to your computer and use it in GitHub Desktop.
Save nilium/8c7ed8527eb63c693f9c147233bfa01b to your computer and use it in GitHub Desktop.
Shell script to send Slack messages over its incoming webhooks
#!/usr/bin/env sh
usage () {
cat 1>&2 <<ENDUSAGE
Usage: slackmsg [OPTIONS] -t<URL> [--] MESSAGE
Options:
-t|--target URL The Slack URL to send a message to. (required)
-d|--dry-run Print the payload and curl request only.
-i|--stdin Read the MESSAGE from standard input.
-a|--attach JSON JSON object to attach to the message.
-A|--attachs JSON JSON array of attachment objects to attach to the message.
-u|--user USER The username to send the message with.
-c|--channel [@#]CHAN The channel to send a slack message to.
Automatically prefixed with # unless @ or # is included.
ENDUSAGE
}
if test $# -eq 0
then
usage
exit 2
fi
dryrun=0
stdin=0
while test $# -gt 0
do
case "$1" in
-h|--help) usage; exit 0;;
-c|--channel) shift; chan="${1}";;
-c*) chan="${1#-c}";;
--channel=*) chan="${1#--channel=}";;
-u|--user) shift; user="${1}";;
-u*) user="${1#-u}";;
--user=*) user="${1#--user=}";;
-t|--target) shift; target="${1}";;
-t*) target="${1#-t}";;
--target=*) target="${1#--target=}";;
-d|--dry-run) dryrun=1;;
-a|--attach) # singular
shift
attachments="$(jq --argjson pre "${attachments:-[]}" --argjson next "[$1]" -n '[$pre, $next]|add')"
;;
-A|--attachs) # plural
shift
attachments="$(jq --argjson pre "${attachments:-[]}" --argjson next "$1" -n '[$pre, $next]|add')"
;;
-i|--stdin) stdin=1;;
--) shift; msg="$*";;
*) msg="$*"; break;;
esac
shift
done
is_dryrun () { test "$dryrun" -eq 1; }
if test -z "$target"
then
if is_dryrun
then
target='https://hooks.slack.com/services/slack/integration'
else
echo 'slackmsg: no target URL given' 1>&2
usage
exit 2
fi
fi
case "$chan" in
''|@*|'#'*) ;;
*) chan="#${chan}";;
esac
if test "$stdin" -eq 1
then
if test -n "$msg"
then
echo 'slackmsg: message in args is ignored with --stdin' 1>&2
fi
msg="$(cat)"
fi
if test -z "$msg"
then
echo 'slackmsg: no message' 1>&2
usage
exit 2
fi
payload () {
jq --arg text "$msg" \
--arg chan "$chan" \
--arg user "$user" \
--argjson attachments "${attachments:-null}" \
-n "$@" '
{ mrkdwn: true, text: $text } |
if $user != "" then .username = $user else . end |
if $chan != "" then .channel = $chan else . end |
if $attachments != null then .attachments = $attachments else . end
'
}
if test "$dryrun" -eq 1
then
echo curl --silent --fail -X POST "$target" --data-binary @- '<<EOF' 1>&2
payload 1>&2
echo EOF 1>&2
exit 0
fi
payload -c | curl --silent --fail -X POST "$target" --data-binary @-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment