#!/bin/bash

GOOGLE_CHAT_WEBHOOK_URL="https://chat.googleapis.com/v1/spaces/AAAA7hXAOCM/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=YupvEeDhNq2aF9ldCAf8TeJw8kmafVAXpj3xJWIzRGw%3D"


echo "Generate the Thread Title ..."
response=$(curl -s -X POST -H "Content-Type: application/json" \
  -d '{"text":"這是主題訊息，接下來會在這個 thread 中回覆"}' \
  "$GOOGLE_CHAT_WEBHOOK_URL")

# 取得 thread.name
thread_name=$(echo "$response" | grep -o '"name": *"spaces[^"]*"' | cut -d '"' -f4 | sed 's/messages/threads/')
echo "Get the thread.name: $thread_name ..."

echo "Send Messages to the same thread ..."
curl -s -X POST -H "Content-Type: application/json" \
  -d '{
        "text": "這是 thread 中的回覆訊息 from shell script",
        "thread": { "name": "'"$thread_name"'" }
      }' \
  "$GOOGLE_CHAT_WEBHOOK_URL"

echo "Finished."
