Automate Notifications to G-Chat Space using Google Apps Script.

In our busy lives, finding ways to simplify and automate tasks is crucial for productivity. Thankfully, Google Apps Script provides a powerful solution for automating tasks within Google Workspace, such as Gmail and Google Drive. In this article, we will explore how to use Google Apps Script to create a webhook function that sends notifications and updates to a designated chat space. We will also demonstrate how to trigger this function based on specific email conditions, allowing you to streamline your workflow effortlessly.

Before we dive into the technical details, let’s make sure you have everything you need to follow along:

Prerequisites:

  • A basic understanding of JavaScript.
  • Access to a Google Workspace account.

Setting up the webhook function: The webhook function is the heart of our automation process. It sends notifications to a specific chat space using the Google Chat API. Let’s break down the code and see how it work.

To make things easier, we’ll guide you through each step. First, we need to define the URL for the Google Chat API. This URL acts as the endpoint where our notifications will be sent.

To find your webhook URL in Google Workspace:

  1. Go to the Google Chat application in your Google Workspace account.
  2. Create or select a chat space where you want to receive the notifications.
  3. Click on “Apps & integrations” drop from the drop down.

4. Proceed to click on manage webhooks, enter a name for webhook (for eg: “Automation Bot”), click on save. In the next dialog box click on the “copy” icon to copy the webhook url.

In the “Webhook URL” section, you will find the URL needed for the url variable in the webhook function. Copy this URL and replace the placeholder.

function webhook() {
  // Define the URL for the Google Chat API
  const url = "https://chat.googleapis.com/v1/spaces/AAAAdoadlss/messages?key=YOUR_API_KEY&token=YOUR_TOKEN";        

Next, we configure the options for the HTTP request. We set the method to “post” since we want to send data to the API. Additionally, we specify the content type as JSON to ensure proper formatting of our payload. Speaking of which, the payload contains the actual notification content. Feel free to customize the title, image URL, and message text to suit your needs.

// Configure the HTTP request options
  const options = {
    "method": "post",
    "headers": {
      "Content-Type": "application/json; charset=UTF-8"
    },
    "payload": JSON.stringify({
      "cards": [{
        "header": {
          // Insert the title of your message
          "title": "My Website",
          // Insert the url for your app icon
          "imageUrl": "https://myimage.com/appicon.jpg",
          "imageStyle": "IMAGE"
        },
        "sections": [{
          "widgets": [{
            "textParagraph": {
            // Insert the text details or notes
              "text": "My Website Update: " + new Date().toDateString(),
            }
          },
          {
            "buttons": [{
              "textButton": {
              // Insert the CTA for the button
                "text": "OPEN LINK",
                "onClick": {
                  "openLink": {
                    // Insert the destination url
                    "url": "https://yourdestinationurl.com"
                  }
                }
              }
            }]
          }]
        }]
      }]
    })
  };        

Finally, we use UrlFetchApp.fetch(url, options) to send the HTTP request to the Google Chat API. The response from the API is logged using Logger.log() for troubleshooting purposes.

// Send the HTTP POST request to the Google Chat API
  const response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
}        

Triggering the webhook function based on email conditions: Now that we have our webhook function, let’s create another function called runif() to trigger the webhook based on specific email conditions:

function runif() {
  // Get the first thread in your inbox
  var thread = GmailApp.getInboxThreads(0, 1)[0];
  
  // Get the first message in the thread
  var message = thread.getMessages()[0];
  
  // Log the subject line and check if the email is unread
  Logger.log(message.getSubject());
  Logger.log("Is the email unread? " + message.isUnread());
  
  // Check if the email subject matches a specific condition and is unread
  if (message.getSubject() == '%Total Revenue has reached%' && message.isUnread()) {
    // Trigger the webhook function
    webhook();
  }
  
  // Mark the email as read to avoid triggering multiple times
  message.markRead();
}        

In the runif() function, we start by retrieving the first thread in your inbox and then obtain the first message within that thread. We log the subject line of the email and check if it is unread.

Next, we check if the subject line contains a specific condition (e.g., ‘Total Revenue has reached’) and if the email is unread. If both conditions are met, we trigger the webhook function by calling webhook().

To prevent the function from triggering multiple times, we mark the email as read using message.markRead().

Configuring the trigger: To automate the execution of the runif() function, we need to set up a trigger within Google Apps Script. Here's how you can do it:

  1. Open the Google Apps Script project that contains your code.
  2. In the toolbar, click on “Edit” and select “Current project’s triggers.”
  3. Click on the “+ Add Trigger” button in the bottom right corner.
  4. In the dialog that appears, configure the trigger settings as follows:

  • Choose the runif function from the "Run" dropdown menu.
  • Select the event source as “Time-driven.”
  • Choose the desired interval (e.g., every minute, every hour, etc.) for the trigger.
  • Click on “Save” to create the trigger.

By setting up the trigger, the runif() function will be automatically executed based on the specified interval, allowing you to monitor incoming emails and trigger the webhook function accordingly.

Conclusion: By combining the power of Google Apps Script and the Google Chat API, we can automate notifications and streamline our workflow. With the webhook function, you can send customized notifications to a chat space, while the runif function allows you to trigger these notifications based on specific email conditions. By automating these tasks and configuring triggers, you’ll save time and improve efficiency in your daily work. So why not give it a try and simplify your workflow today?


Howard Glynn

Cloud Director | MBA | CITP | Multi GCP Pro, AWS Pro and Azure Certified | Loves innovating with cloud, software, data and teams! | Productivity Geek

6mo

Still worked great in the first days of 2025 to automate a reminder!

Like
Reply
Naime Ahmed

Fullstack .Net Angular Developer

1y

Hello Sir, This helped me a lot. Thanks for sharing this articale.

Like
Reply

To view or add a comment, sign in

More articles by ✨Sylvester Mawuli A.

Others also viewed

Explore topics