-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotify-slack
executable file
·93 lines (80 loc) · 2.81 KB
/
notify-slack
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
85
86
87
88
89
90
91
92
93
#!/usr/bin/env bash
set -euo pipefail
: "${SLACK_TOKEN:?The SLACK_TOKEN environment variable is required.}"
: "${SLACK_CHANNELS:?The SLACK_CHANNELS environment variable is required.}"
upload=0
output=/dev/null
thread_ts=""
broadcast=0
fail_on_error=0
args=()
for arg; do
case "$arg" in
--upload)
upload=1;;
--output=*)
output="${arg#*=}";;
--thread-ts=*)
thread_ts="${arg#*=}";;
--broadcast)
broadcast=1;;
--fail-on-error)
fail_on_error=1;;
*)
args+=("$arg");;
esac
done
set -- "${args[@]}"
text="${1:?Some message text is required.}"
send_slack_message() {
if [[ "$upload" == 1 ]]; then
echo "Uploading data to Slack with the message: $text"
upload_file="$(mktemp -t upload-file-XXXXXX)"
trap "rm -f '$upload_file'" EXIT
cat /dev/stdin > "$upload_file"
# printf used to strip whitespace from output of macOS/BSD wc
# See <https://github.com/nextstrain/ingest/pull/47#discussion_r1974802967>
length=$(printf '%d' "$(<"$upload_file" wc -c)")
upload_info=$(curl https://slack.com/api/files.getUploadURLExternal \
--header "Authorization: Bearer $SLACK_TOKEN" \
--form-string filename="$text" \
--form-string length="$length" \
--fail --silent --show-error \
--http1.1 )
upload_url="$(jq -r .upload_url <<< "$upload_info")"
curl "$upload_url" \
--form-string filename="$text" \
--form file="@$upload_file" \
--fail --silent --show-error \
--http1.1 > /dev/null
files_uploaded="$(jq -r "[{id: .file_id}]" <<< "$upload_info")"
curl -X POST https://slack.com/api/files.completeUploadExternal \
--header "Authorization: Bearer $SLACK_TOKEN" \
--form-string channel_id="$SLACK_CHANNELS" \
--form-string thread_ts="$thread_ts" \
--form-string files="$files_uploaded" \
--fail --silent --show-error \
--http1.1 \
--output "$output"
else
echo "Posting Slack message: $text"
curl https://slack.com/api/chat.postMessage \
--header "Authorization: Bearer $SLACK_TOKEN" \
--form-string channel="$SLACK_CHANNELS" \
--form-string text="$text" \
--form-string thread_ts="$thread_ts" \
--form-string reply_broadcast="$broadcast" \
--fail --silent --show-error \
--http1.1 \
--output "$output"
fi
}
if ! send_slack_message; then
if [[ "$fail_on_error" == 1 ]]; then
echo "Sending Slack message failed"
exit 1
else
echo "Sending Slack message failed, but exiting with success anyway."
exit 0
fi
fi