DEV Community

Stu Finn
Stu Finn

Posted on

Write your first Google Apps Script with just a few Lines of JavaScript

A few weeks ago I wrote my first Google Apps script.

Liquid error: internal

It took me longer than I'm willing to admit (mostly because I had no idea how to go about it at first) but by using the official docs as a guide combined with a bit of help from google/stack overflow, I was able to write a simple program that automates a menial task for me.

Google Apps Scripts allows us to programmatically create and customize Google services, from Calendars to Gmail to Spreadsheets and almost everything in-between. My small foray into the world of Google Apps Scripts has shown me just how powerful it can be, and I have barely scratched the surface so far.

Today I want to create a new script and I’m going to bring you along for the ride so you can see just how straightforward Google Apps Script writing can be with just a little knowledge of JavaScript.

The goal

I'd like become more consistent about writing daily notes re: what I’ve accomplished, what I’ve learned, and what has tripped me up. Credit to my dev coach, Gregory Brown for encouraging me in this practice and for his helpful article, “An Efficient Approach to Continuous Documentation”.

What we'll do

The script we are going to write together will:

A) Automatically update a “Daily Notes” survey in Google forms to reflect the current date, and

B) Email it to us at the end of each work day as a reminder to fill it in.

Nothing too crazy, right?

Step 1: Manually create a survey in Google Forms

While it is entirely possible to programmatically create a new survey, for our purposes we are going to set up our survey manually. Our script will then modify it each day.

My survey has the following five questions:

  1. What did you accomplish today?
  2. What did you learn today?
  3. What did you get stuck on today?
  4. How did you feel today? (scale of 1-5)
  5. Additional notes/thoughts

Survey preview

Each day at around 4:00pm I want the title of the survey to be updated to reflect the current date, and then I want it sent to my inbox.

Step 2: Fire up the the Google Apps Script Editor

With our survey open and editable, click the drop down menu and select the Script Editor.

Click the drop down menu

You will now be taken to a blank script page. Rename it to something like “Modify Daily Survey”.

Google Apps Scripts allows us to create standalone scripts, as well as scripts that are tied to specific files from the start. Because we created the script from within our Google Form, it is already connected to the survey we just created. More on that later!

Step 3: Start slinging code

For reference, you can find the docs for scripts for Forms here, and scripts for Gmail here.

Let's create three functions. The first will be the main “app” that will get things initialized. The second function will modify the title of the survey and the third function will send the survey to a specified email address.

The first function will stay as myFunction for simplicity’s sake. Now we need assign a variable to the active google form. We can do that with:

var dailySurvey = FormApp.getActiveForm();

Now let’s grab today’s date and assign it to a variable:

var currentDate = new Date();

You may have noticed that I used var instead of const or let. As far as I understand, Google Apps Scripts uses ES5 and thus it doesn't include all of the cutting-edge ES6 features you may be familiar with. Keep that in mind as we proceed!

If you are used to using console.log() to check your work in the browser, that won’t work here. What you can use instead is Logger.log(). After you run a script you can view the log from the View menu (Cmd + Enter on a Mac).

Here's what we've got so far:

function myFunction() {
    // get the active Form that's associated with this script
    var dailySurvey = FormApp.getActiveForm();

    // assign today's date to currentDate
    var currentDate = new Date();

    // convert the date object into a string, 
    //and assign the first 15 characters to a variable (to use in our survey's title)
    var dateString = currentDate.toString().slice(0,15);

}
Enter fullscreen mode Exit fullscreen mode

The first time you run a script you may get an “authorization required” pop-up. Follow the instructions to authorize your script (PSA: The script will be granted access to your google account, so use this with caution if you aren’t the only author of the script!).

Now that we have access to the survey through dailySurvey and we have the date as a string in dateString, let’s modify the title of the survey to reflect today’s date. We will do this in a separate function, changeDate().

function changeDate(survey, date) {

    // Assign text that we'll use in the title with the current date to a variable
    var titleText = "Daily Survey for " + date;

    // Set the title of the survey!
    survey.setTitle(titleText);
}
Enter fullscreen mode Exit fullscreen mode

Boom! We are now able to modify the survey title on command! Next up, we want to email the updated survey to ourselves. Let’s create the sendSurvey() function.

function sendSurvey(survey, dateString) {
    // grab the URL where the survey is published
    var surveyUrl = survey.getPublishedUrl();

    // the content of our email
    var emailBody = "<p>Stu, it's time to take <em>just a few moments</em> to reflect on your day.</p>
                "<p>Here's the link: " + surveyUrl + "</p>;

    // the subject line content
    var subject =  "Daily Survey for " + dateString;

    // send the email! Note that we can use html in the body of the email using the {htmlBody: emailBody} syntax below.
    GmailApp.sendEmail("[destination email address goes here]", subject,'',{
        htmlBody: emailBody});
}
Enter fullscreen mode Exit fullscreen mode

Note that you will once again be asked to verify the app when it tries to send you an email. You may also get a warning that the app isn’t verified. Again use an appropriate amount of caution but if you have created it yourself and you know exactly what the script does, by all means proceed.

And here is the full app in all of it’s 39 lines (including blank space & comments!) of glory:

function myFunction() {
  // assign the active form (Daily Survey) to daily Survey
  var dailySurvey = FormApp.getActiveForm();
  var currentDate = new Date();

  // convert the date object into a string, and assihn the first 15 characters to a variable
  var dateString = currentDate.toString().slice(0,15);

  //call the updateDate() function
  changeDate(dailySurvey, dateString);

  // call the sendSurvey() function
  sendSurvey(dailySurvey, dateString);

}

function changeDate(survey, date) {

  // Set the text that we'll use in the title with the current date
  var titleText = "Daily Survey for " + date;
  Logger.log(titleText);
  survey.setTitle(titleText);

}

function sendSurvey(survey, date) {

  // grab the URL where the survey is published
    var surveyUrl = survey.getPublishedUrl();

    // the content of our email
  var emailBody = "<p>Stu, it's time to take <em>just a few moments</em> to reflect on your day.</p><p>Here's the link: " + surveyUrl + "</p>";

    // the subject line content
    var subject =  "Daily Survey for " + date;

    // send the email! Note that we can use html in the body of the email useing the syntax below
    GmailApp.sendEmail('[destination email address goes here]', subject,'',{
        htmlBody: emailBody});

}
Enter fullscreen mode Exit fullscreen mode

Magic! Now when you run the script myFunction() you should get an up-to-date survey in your inbox!

Step 4: Schedule the app to run each day

I have avoided saying any of this is “easy” since what is easy for me today seemed impossibly complicated just a few months ago but I'm not going to lie, this next step is legit easy.

To schedule the app to run at a specified interval simply go to “Edit/Current Project’s Triggers” and add a custom trigger. That’s it!

Step 5: Celebrate!

You have now created your first Google Apps Script! Let me know in the comments how it goes for you, and what wondrous things you create with your new superpowers.

Top comments (2)

Collapse
 
practicingdev profile image
Practicing Developer

Hi Stu,

This is a nice, practical walkthrough of a real problem.

Thanks for posting it!

(And for the shout-out, that caught me by surprise! 😀)

Collapse
 
stu profile image
Stu Finn

Thanks for saying so!