-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.sh
84 lines (70 loc) · 2.05 KB
/
slack.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env bash
# Store script in /usr/bin/slack
# chmod 755
# Run: /usr/bin/slack "GROUP_NAME" "MESSAGE"
set -o pipefail
set -o errexit
set -o nounset
#set -o xtrace
# Webhook for SLACK Alerts Channel
APP_SLACK_WEBHOOK=https://hooks.slack.com/services/...
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 --delimiter=. --fields=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