Skip to content

Instantly share code, notes, and snippets.

@andkirby
Last active April 4, 2024 17:51
Show Gist options
  • Save andkirby/67a774513215d7ba06384186dd441d9e to your computer and use it in GitHub Desktop.
Save andkirby/67a774513215d7ba06384186dd441d9e to your computer and use it in GitHub Desktop.
Shell/Bash script for sending slack messages.
#!/usr/bin/env bash
####################################################################################
# Slack Bash console script for sending messages.
####################################################################################
# Installation
# $ curl -s https://gist.githubusercontent.com/andkirby/67a774513215d7ba06384186dd441d9e/raw --output /usr/bin/slack
# $ chmod +x /usr/bin/slack
####################################################################################
# USAGE
# Send message to slack channel/user
# Send a message to the channel #ch-01
# $ slack '#ch-01' 'Some message here.'
#
# Send a message to the channel #ch-01 and user @me.
# $ slack '#ch-01,@me' MESSAGE
#
# Send a message to the default channel (it must be declared in APP_SLACK_CHANNEL).
# $ slack MESSAGE
#
# VARIABLES
#
# Please declare environment variables:
# - APP_SLACK_WEBHOOK
# - APP_SLACK_CHANNEL (optional)
# - APP_SLACK_USERNAME (optional)
# - APP_SLACK_ICON_EMOJI (optional)
# You may also declare them in ~/.slackrc file.
####################################################################################
set -o pipefail
set -o errexit
set -o nounset
#set -o xtrace
init_params() {
# you may declare ENV vars in /etc/profile.d/slack.sh
if [ -z "${APP_SLACK_WEBHOOK:-}" ]; then
echo 'error: Please configure Slack environment variable: ' > /dev/stderr
echo ' APP_SLACK_WEBHOOK' > /dev/stderr
exit 2
fi
APP_SLACK_USERNAME=${APP_SLACK_USERNAME:-$(hostname | cut -d '.' -f 1)}
APP_SLACK_ICON_EMOJI=${APP_SLACK_ICON_EMOJI:-:slack:}
if [ -z "${1:-}" ]; then
echo 'error: Missed required arguments.' > /dev/stderr
echo 'note: Please follow this example:' > /dev/stderr
echo ' $ slack.sh "#CHANNEL1,CHANNEL2" Some message here. ' > /dev/stderr
exit 3
fi
slack_channels=(${APP_SLACK_CHANNEL:-})
if [ "${1::1}" == '#' ] || [ "${1::1}" == '@' ]; then
# explode by comma
IFS=',' read -r -a slack_channels <<< "${1}"
shift
fi
slack_message=${@}
}
send_message() {
local channel=${1}
echo 'Sending to '${channel}'...'
curl --silent --data-urlencode \
"$(printf 'payload={"text": "%s", "channel": "%s", "username": "%s", "as_user": "true", "link_names": "true", "icon_emoji": "%s" }' \
"${slack_message}" \
"${channel}" \
"${APP_SLACK_USERNAME}" \
"${APP_SLACK_ICON_EMOJI}" \
)" \
${APP_SLACK_WEBHOOK} || true
echo
}
send_message_to_channels() {
for channel in "${slack_channels[@]:-}"; do
send_message "${channel}"
done
}
slack() {
# Set magic variables for current file & dir
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
readonly __dir __file
cd ${__dir}
if [ -f $(cd; pwd)/.slackrc ]; then
. $(cd; pwd)/.slackrc
fi
declare -a slack_channels
init_params ${@}
send_message_to_channels
}
if [ "${BASH_SOURCE[0]:-}" != "${0}" ]; then
export -f slack
else
slack ${@}
exit $?
fi
@Mte90
Copy link

Mte90 commented Aug 23, 2017

I hacked a little bit the last part to:

if [ -f $HOME/.slackrc ]; then
    . $HOME/.slackrc
fi

In that way less code and not search in the folder. Also I removed the line 100 because I changed the script name to slack-message

@andkirby
Copy link
Author

andkirby commented Sep 29, 2017

So, is there some patch to improve the script? :)

@dlorent
Copy link

dlorent commented Oct 25, 2017

You should consider implementing multiple types of posting. eg. as an attachment.

@rasperepodvipodvert
Copy link

how can i send file?

@andkirby
Copy link
Author

andkirby commented Feb 15, 2018

@miradnan
Copy link

Fantastic

@miradnan
Copy link

how can i send file?

Maybe put a file on s3 and send it as link. Could be a quick solution :)

@siso
Copy link

siso commented Jan 23, 2019

On OS X the BSD version of cut complains:

cut: illegal option -- -

If you replace L43 with this one, then it would support both BSD and GNU cut:

APP_SLACK_USERNAME=${APP_SLACK_USERNAME:-$(hostname | cut -d '.' -f 1)}

@jotabf
Copy link

jotabf commented Jul 31, 2019

I try next command but didn't work:

a=123
slack '${a}'

I expected the output 123, but the output was ${a}

@andkirby
Copy link
Author

@jotabf, it doesn't in this bash in this way for single quotes. It should be in double quotes or whithout ones (in case a value doesn't have spaces, it can be tricky for arguments.)

@andkirby
Copy link
Author

@siso, fixed. Thanks for this note.

@Lalit-1219
Copy link

Hello All,

Could anyone help me please to get emails on outlook for specific slack channels with some specific content like "failures"
and that should trigger twice a day at some specific timings.
Thanks in Advance

@andkirby
Copy link
Author

@Lalit-1219, it's not about this script definitely. ;)
You may try to adjust nofication settings. I remember there is "keywords" feature.

@farisalfa
Copy link

farisalfa commented Oct 16, 2019

hi @andkirby

I want to ask, why can I sent from grep command?

my sh script like this :

#!/bin/bash
message=$(grep AUDIT audit.txt)
slack ${message}

if I execute this, I always get this error:

/home/ubuntu# ./test_sent.sh
Sending to ...
invalid_payload

can you solve this?

@andkirby
Copy link
Author

Hi @farisalfa,

The only one who can solve it that's you. ;)

I guess, that's not about script but about Bash scripting knowledge.
Just double checked — it works fine. Think about double quotes for your variable.

@jorisbertomeu
Copy link

Thanks bro', u saved my night 👊🏻

@d4r1091
Copy link

d4r1091 commented May 29, 2020

Just an insight to those facing issues with /usr/bin/slack due to permission accessing to /usr/bin, you can move the script under usr/local/bin/slack.

So that the two commands to run will be:

curl -s https://gist.githubusercontent.com/andkirby/67a774513215d7ba06384186dd441d9e/raw --output /usr/local/bin/slack

chmod +x /usr/local/bin/slack

hope it helps 👍
great script @andkirby 💪

@jmhostalet
Copy link

Hi,

when sending a message in this way:
slack.sh ":arrow_right: data seeding"
emoji appears as text and it is not rendered, what am I doing wrong ?
Thanks!

@andkirby
Copy link
Author

andkirby commented Jun 16, 2020

emoji appears as text and it is not rendered, what am I doing wrong ?

@jmhostalet, I assume, they added mrkdwn type for that.
https://api.slack.com/reference/surfaces/formatting#basics

great script @andkirby 💪

@d4r1091, it's a pleasure to know it. ;)

@andkirby
Copy link
Author

andkirby commented Jun 19, 2020

@jmhostalet, just double check it. It works with emoji. According to off-docs mrkdwn=true always.

image

@Keriwaza
Copy link

hi @andkirby

I want to ask, why can I sent from grep command?

my sh script like this :

#!/bin/bash
message=$(grep AUDIT audit.txt)
slack ${message}

if I execute this, I always get this error:

/home/ubuntu# ./test_sent.sh
Sending to ...
invalid_payload

can you solve this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment