Last active
May 3, 2023 16:25
-
-
Save nothub/fa86a96d3d397273aefbce3b1ffbb9d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -o errexit | |
set -o nounset | |
set -o pipefail | |
log() { | |
echo >&2 "$*" | |
} | |
usage() { | |
set +o xtrace | |
log "Usage: webhook-notify [-u=<url>] [-v] [-h] [--] (<text>...|-) | |
Message contents will be read from arguments or stdin. | |
Options: | |
-u Webhook url | |
-v Verbose output | |
-h Print help | |
Supported Webhook providers: | |
Google Chat ( https://chat.googleapis.com/v1/spaces/... ) | |
Discord ( https://discord.com/api/webhooks/... ) | |
Config: | |
The program will attempt to read a config file from: /etc/webhook-notify.cfg | |
The config may contain the target webhook url like this: | |
url=\"<webhook_url>\" | |
Mail: | |
To redirect incoming mail to discord, configure /etc/aliases like this: | |
discord: \"|/usr/local/bin/webhook-notify\" | |
root: discord | |
" | |
} | |
check_dependency() { | |
if ! command -v "$1" > /dev/null 2>&1; then | |
log "Error: missing dependency: $1" | |
exit 1 | |
fi | |
} | |
read_stdin() { | |
if [[ -p /dev/stdin ]]; then | |
local line | |
while IFS= read -r line; do | |
echo "${line}" | |
done | |
fi | |
} | |
check_dependency curl | |
check_dependency jq | |
cfg="/etc/webhook-notify.cfg" | |
if [[ -r "${cfg}" ]]; then | |
source "${cfg}" | |
fi | |
while getopts u:vh opt; do | |
case $opt in | |
u) url="$OPTARG" ;; | |
v) set -o xtrace ;; | |
h) usage ; exit 0 ;; | |
*) usage ; exit 1 ;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
if [[ $# -gt 0 ]] && [[ $* != "-" ]]; then | |
text="$*" | |
else | |
text="$(read_stdin)" | |
fi | |
set +o nounset | |
if [[ -z $url ]]; then | |
log "Error: webhook url required" | |
usage ; exit 1 | |
fi | |
if [[ -z $text ]]; then | |
log "Error: missing message content" | |
usage ; exit 1 | |
fi | |
set -o nounset | |
if echo "${url}" | grep --quiet --extended-regexp "https\:\/\/chat.googleapis\.com\/v1\/.*"; then | |
payload="$(echo '{"text": ""}' | jq --raw-output --arg text "$text" '.text |= $text')" | |
elif echo "${url}" | grep --quiet --extended-regexp "https\:\/\/discord\.com\/api\/webhooks\/.*"; then | |
payload="$(echo '{"content": ""}' | jq --raw-output --arg text "$text" '.content |= $text')" | |
else | |
log "Error: unknown webhook provider" | |
exit 1 | |
fi | |
curl \ | |
--request POST \ | |
--header "Content-Type: application/json; charset=UTF-8" \ | |
--data "${payload}" \ | |
"$url" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment