Posting to Google Spaces from Bash

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 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.)


# List of webhooks from Google Spaces.
declare -A webhooks

# Use the first argument -- "info", "warning",
# or "critical" -- to pick a webhook URL.

if [[ -z $GCHAT_WEBHOOK_URL ]]; then
    # If the first argument wasn't "info", "warning",
    # or "critical", use the "critical" webhook.
    # Remove the first argument from the arg list.

# Everything after the first argument becomes the message.

# 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: info "You should know about this." warning "There's a problem but it's not that bad." critical "There's a bad problem."

If I have another script that needs to get my attention I just have it call

Hope you found this useful.