Streamlining Discord Notifications with Google Apps Script

Have you ever had trouble streamlining your automatic processes and combining your notifications? Take a look at Google Apps Script! Users may quickly expand the functionality of Google apps and automate tedious chores with this robust scripting language based on JavaScript.

We’ll examine the fascinating potential of Google Apps Script, including automating workflows and building specialized add-ons. Get ready for a step-by-step tutorial on utilizing Google Apps Script to post your notifications to your preferred Discord channels. With Google Apps Script, get ready to transform your workflow and unleash your inner automation whiz!

My Use Case

I use Discord to collect notifications from my network and other automated events. This is specific for events I want text-like notifications for. I picked Discord because I am part of many servers there. Like many other users, I have many different accounts; I need to consolidate at least my notifications! I don’t know about everyone else, but I rarely find a program that fits the bill in my quest to automate or produce results custom to my needs.

Huginn works well for a centralized “bot” notification venue. It has posting templates for Telegram, Twitter, and many more … but not Discord. Still, one of my favorite automation applications, Huginn, needs a preconfigured template for posting to Discord. I KNOW what you are thinking: “Sean, you have all these cool programming things; can you not just write your own Huginn agent to do this”? (Check out my Huginn Post on installation and configuration).

I tried; I tried a lot. I cannot get it to post! However, I have not given up. My coding in Ruby is terrible, so maybe I can use an existing agent to at least post to a Discord webhook? We shall see. This is not about making that agent, though. This is about what I discovered using Google App Script.

Say What? Google Apps Script?

How did I not know about Google Apps Script? It is a really cool app and provided my workaround … that I secretly want to keep in place! It uses the notifications I get from my Huginn Instance that email notifications to my Gmail, strip the HTML from the email body, and post the information to my specific Discord Channel.

This is especially useful if you want to only post notifications to a community channel versus letting your messages get buried in someone’s inbox. This post will explain how to do this using Google App Scripts. I will post the code I used as a template, and I promise to follow up on this post when I figure out how to do it with Huginn.

Google Sheets, Google Docs, and Google Forms can all be automated and have their functionality increased using Google Apps Script, a scripting language based on JavaScript. It offers a straightforward yet effective platform for creating unique apps, streamlining processes, and interacting with other services.

Using Google Apps Script, users may create custom add-ons and functions to extend the functionality of Google apps and write code to automate repetitive processes like sending emails or creating calendar events. The scripts can be run automatically, responding to several occasions, including form submissions, calendar events, and time-based triggers.

Via APIs, Google Apps Script also gives users access to several Google services, including Gmail, Google Drive, and Google Maps. Because of its complete integration with the Google Cloud Platform, applications can be easily deployed and scaled.

Users of Google Apps Script have developed a wide range of well-liked projects, from automating specific activities to developing sophisticated apps.

The most well-liked projects include: 

  1. Automated workflows: Google Apps Script is commonly used to automate tasks such as sending emails, generating reports, and updating spreadsheets based on specific events or conditions. 
  2. Custom add-ons and functions: Users can create custom add-ons and procedures to enhance the capabilities of Google apps, such as adding new features to Google Sheets or creating customized menu options in Google Docs. 
  3. Data visualization: Google Apps Script can create custom charts and graphs to visualize data stored in Google Sheets or other Google apps. 
  4. Web applications: Users can create custom web applications using Google Apps Script that can be deployed to the web and accessed by anyone with an internet connection. 
  5. API integrations: Google Apps Script provides access to a wide range of APIs, allowing users to integrate with external services such as Twitter, Slack, and Trello. 
  6. Chatbots and voice assistants: With the help of Google Apps Script, users can create chatbots and voice assistants that interact with users through messaging platforms or voice-enabled devices like Google Home or Amazon Echo. 

Google Apps Script offers a versatile and potent platform for users to create unique applications and automate activities inside the Google ecosystem. 

Let's Automate with this Example

In my Huggin Instance, I host an agent that listens for earthquake events only in specific regions greater than 4.0 magnitude (humanly detectable). When that threshold has been met, I have it send an email notification immediately to a distribution list with a subject line of “Seismic Event Detected.” The body of the email contains details and links to the USGS website. As defined, additionally, I want to post that specific message into a Discord channel.

GMAIL subject line example

To do this in Google Apps Script, I will need a function that retrieves this email message in my Gmail inbox with the subject “Seismic event detected!”, extracts relevant information such as the sender and date, and earthquake info, and then sends a message to a Discord webhook with the extracted data.

The script must search for the email thread with the specified subject, retrieve the first message, and extract the message body. Then, I want it to use a regular expression to remove any HTML tags from the body of the email, leaving only the text content.

The script needs to check if the message has been seen before by looking up the message ID in a list of previously seen messages stored in Google Apps Script Properties. The function ends without sending another message to Discord if the message has already been seen.

If the message is new, the function should extract the sender and date, format a message to the Discord webhook with the extracted information, and send the message using the UrlFetchApp.fetch() method. Finally, the message ID needs to be added to the list of seen messages in the Google Apps Script Properties so that the function will not send the same message twice.

You may not need to post a Huginn notification to Discord. Still, this message works with posting any email to Discord that matches a specific subject line. Ready? Let’s do it!

Get your Discord Webhook

Log into your Discord server or server to which you have administrative rights. Select or create a channel you would like to generate a webhook for.

Discord Channel Edit GearOn the left-hand side, choose integration and then webhooks from the display. Clicking the “create new webhook” button will generate a webhook with a unique name; you can rename it.

Create Webhook Section in DiscordThen click into your new webhook and select copy webhook. It will not display the URL as it is a secret. You can paste it into a text doc for now or come back for it later. Also, adjust the name in this section if you want or add a profile pic for your “bot.”

webhook details

Configure Google Apps Script

Okay, let’s find where we can use Google Apps Script now. in your browser, navigate to https://script.google.com/home. You should sign in as the Gmail account user of the email you want to use. You should be at a main project screen like the image below; you may not have any projects yet, though!

Google Apps Script Proj ScreenNext, start a new project; it will take you to the function screen where you can delete the contents and paste the following code:

  function posttodiscord() {
  var thread = GmailApp.search('subject:"PUT YOUR SUBJECT LINE YOU WANT TO SEARCH FOR HERE"');
  var message = thread[0].getMessages()[0];
  var body = message.getBody();
  var strippedBody = body.replace(/(<([^>]+)>)/gi, "");
  
  // Check if the message has been seen before
  var last_emails = PropertiesService.getScriptProperties().getProperty('last_emails');
  if (last_emails !== null) {
    last_emails = JSON.parse(last_emails);
    if (last_emails.includes(message.getId())) {
      return;
    }
  } else {
    last_emails = [];
  }

  // Extract relevant information from the email
  var from = message.getFrom();
  var date = message.getDate();
  
  // Format the message to send to Discord
  var payload = {
    "content": "New email from: " + from + " on " + date,
    "embeds": [{
      "description": strippedBody
    }]
  };

  // Send the message to the Discord webhook
  var options = {
    "method": "post",
    "headers": {
      "Content-Type": "application/json"
    },
    "payload": JSON.stringify(payload)
  };
  
  var webhook_url = "YOUR DISCORD WEBHOOK SHOULD BE PASTED HERE";
  UrlFetchApp.fetch(webhook_url, options);

  // Add the message ID to the list of seen messages
  last_emails.push(message.getId());
  PropertiesService.getScriptProperties().setProperty('last_emails', JSON.stringify(last_emails));
}

We need to adjust this to make it yours. Rename your project to something that will represent what you are doing. You will see the function name in the first line of the code; you can replace that with something you would like other than what I have there. Scroll to the area where it has the subject line. Replace this with an expected value for which the app script will search your inbox. Scroll down and replace the placeholder for your Discord webhook with the webhook URL you saved earlier. Save your project.

GoogleAppsScript

So what did this code do?

The code is written in JavaScript. Stepping through the code here is precisely what is occurring:

  • The function sendEmailToDiscord is defined.
  • The Gmail service searches for an email thread with the subject line “Seismic event detected!”. *or whatever you placed here*
  • The first message in the thread is retrieved, and the body is extracted.
  • Any HTML tags in the body are removed.
  • The ID of the current message is checked against a list of previously seen messages to prevent duplicates.
  • The sender and date of the current message are extracted.
  • The content of the message is formatted into a payload object with the sender and date added to the message content and the stripped body added as an embed.
  • An HTTP POST request is made to a Discord webhook URL with the payload object in the request body.
  • The ID of the current message is added to the list of previously seen messages.

Once you have saved your code, you can “run” it. Before you run it, though, email your Gmail account that is being scanned with the subject line you are looking for and add some text in the body to post to Discord. Your first initial run will prompt for authorization review. After you have authorized the app to run in Gmail, it may ask for it a second time after selecting run; that is normal, and confirm it a second time. 

Check Discord

Navigate to your Discord and see if you posted the test event you emailed in Gmail. After validating a successful run, you should have successfully made a post on your Discord channel. If that is successful, you are ready to deploy your project and set up a trigger.

Deploy Version

Deploy your code by selecting the deploy button in the upper right-hand corner of your project’s screen. Select a new deployment and configure your deployment as a web app. Name the deployment and change any defaults you may want for authorization. I keep mine as default. Now click Deploy

New Deployment Config

Assign Triggers

Select the alarm clock or “triggers” icon on the left side of the menu. This will pull up the triggers sheet, and you will want to click the “new trigger” icon at the bottom right of the screen.

Now, you can adjust how you want it to work for your specific needs in the trigger configuration. Select the function; this is the function name in the first line of your code. Then select the deployment. You might have more than one version if you redeployed. You can just select the deployment version you want the trigger to run on. For your frequency, because I want to be notified immediately (or as close to) of a seismic event, I have the trigger process the code every 60 seconds.

Trigger Config

Summary

Though I may be late to the party, I was thrilled to learn about Google Apps Script! Thanks to this fantastic platform, I got around my Huginn problem and posted notifications to a group channel in Discord. The best thing, though? I’m allowed to continue using this workaround.

The functionality of Google apps can be expanded, and repetitive tasks can be automated thanks to the robust scripting language known as Google Apps Script, which is based on JavaScript. You can program processes like email sending to be automated, add new features to Google apps to expand their functionality, and build web applications accessible to anybody with an internet connection.

In my example, I developed a function that pulls pertinent information from earthquake notifications in my Gmail inbox and delivers it with a message to a Discord webhook. Even so, the script will only provide the message once if it has already been posted to Discord.

Try Google Apps Script if you’re having trouble automating or consolidating your notifications. It is a flexible and robust platform that may assist you in developing original applications and automating processes inside the Google ecosystem. Who knows, though? You never know—you might just open up a new universe of opportunities. Good luck automating!

2 thoughts on “Streamlining Discord Notifications with Google Apps Script

  1. Ezzy says:

    I just got into discord and this is pretty cool to know! Thanks for the informative port. I’m looking forward to more posts like this!

    Reply
    1. Sean says:

      You’re welcome! Let me know if you want help with some automation 😉

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.