I recently started using Google Spaces and wanted to have some automations send me messages when certain things happened on my systems, so I wrote a simple bash script to send a notification message.
If you’re the Space Manager of a Google Space you can create webhooks to send messages to that space. You can create a webhook for Google Spaces by going into Google Chat and selecting the Space you want to send messages to. Click on the Space name at the top of the screen then choose “Apps & integrations” from the drop-down menu. Then select “Webhooks” and create a webhook.
Each webhook has a name, an icon, and a URL. I wanted three types of messages: info, warning, and critical, so I created three webhooks named Info, Warning, and Critical, each with an appropriate icon.
Then I created the notify.sh
script, copying the URLs for my space into an associative array. (Associative arrays were only introduced in Bash v4, so if you’re using an older version of bash this won’t work.)
#!/bin/bash
# List of webhooks from Google Spaces.
declare -A webhooks
webhooks=(
["info"]="https://chat.googleapis.com/v1/spaces/..."
["warning"]="https://chat.googleapis.com/v1/spaces/..."
["critical"]="https://chat.googleapis.com/v1/spaces/..."
)
# Use the first argument -- "info", "warning",
# or "critical" -- to pick a webhook URL.
GCHAT_WEBHOOK_URL="${webhooks[$1]}"
if [[ -z $GCHAT_WEBHOOK_URL ]]; then
# If the first argument wasn't "info", "warning",
# or "critical", use the "critical" webhook.
GCHAT_WEBHOOK_URL="${webhooks["critical"]}"
else
# Remove the first argument from the arg list.
shift
fi
# Everything after the first argument becomes the message.
msg="$*"
# Escape the message text to make it "safe".
escapedText=$(echo "$msg" | sed 's/\n/\\n/g' \
| sed 's/"/\\"/g' | sed "s/'/\\'/g" )
# Create a json object with the text.
json="{\"text\": \"$escapedText\"}"
# Use curl to send the JSON to Google.
curl -X POST -H 'Content-Type: application/json' \
-d "$json" "${GCHAT_WEBHOOK_URL}"
Now I can call the script like so:
notify.sh info "You should know about this."
notify.sh warning "There's a problem but it's not that bad."
notify.sh critical "There's a bad problem."
If I have another script that needs to get my attention I just have it call notify.sh
.
Hope you found this useful.
$ sh send_message.sh info
{
“error”: {
“code”: 400,
“message”: “Message cannot be empty.”,
“status”: “INVALID_ARGUMENT”
}
}
I try your example and I got an error
You didn’t include a message argument.
send_message.sh info “This is the message”