This document provides an overview of Google Apps Script, including its capabilities, use cases, and coding examples. Some key points:
- Google Apps Script is a JavaScript runtime that allows automation of G Suite applications and integration with other Google and external services.
- It can be used to extend functionality within G Suite editors like Sheets, Docs and Slides through add-ons, or to build standalone web apps and microservices.
- Examples demonstrate how to access APIs to integrate with services like Google Maps, Gmail, Calendar and Natural Language, as well as build bots for Hangouts Chat.
- The document also shows how Apps Script can be used to "glue" together Google Cloud Platform
Automate Tasks & Extend G Suite with Google Apps Script
1. Making the most of G Suite
with Google Apps Script
Automate Laborious Tasks in Google Cloud
(G Suite & GCP)
Wesley Chun
Developer Advocate, Google Cloud
Adjunct CS Faculty, Foothill College
G Suite Dev Show
goo.gl/JpBQ40
About the speaker
Developer Advocate, Google Cloud
● Mission: enable current and future
developers everywhere to be
successful using Google Cloud and
other Google developer tools & APIs
● Videos: host of the G Suite Dev Show
on YouTube
● Blogs: developers.googleblog.com &
gsuite-developers.googleblog.com
● Twitters: @wescpy, @GoogleDevs,
@GSuiteDevs
Previous experience / background
● Software engineer & architect for 20+ years
● One of the original Yahoo!Mail engineers
● Author of bestselling "Core Python" books
(corepython.com)
● Technical trainer, teacher, instructor since
1983 (Computer Science, C, Linux, Python)
● Fellow of the Python Software Foundation
● AB (Math/CS) & CMP (Music/Piano), UC
Berkeley and MSCS, UC Santa Barbara
● Adjunct Computer Science Faculty, Foothill
College (Silicon Valley)
2. Confidential & Proprietary
Outline
● Cloud computing overview
● Google Cloud serverless
● Intro to Google Apps Script
● Coding with Apps Script
● All of Cloud (inspiration)
● BONUS, resources and summary
01
Cloud computing
overview
All you need to know about the cloud
3. What is cloud computing?
spar
Google Compute Engine, Google Cloud Storage
AWS EC2 & S3; Rackspace; Joyent
Cloud service levels/"pillars"
SaaS
Software as a Service
PaaS
Platform as a Service
IaaS
Infrastructure as a Service
Google BigQuery, Cloud SQL,
Cloud Datastore, NL, Vision, Pub/Sub
AWS Kinesis, RDS; Windows Azure SQL, Docker
Google Apps Script, App Maker
Salesforce1/force.com
G Suite (Google Apps)
Yahoo!Mail, Hotmail, Salesforce, Netsuite
Google App Engine, Cloud Functions
Heroku, Cloud Foundry, Engine Yard, AWS Lambda
4. Summary of responsibility
SaaS
Software as a Service
Applications
Data
Runtime
Middleware
OS
Virtualization
Servers
Storage
Networking
Applications
Data
Runtime
Middleware
OS
Virtualization
Servers
Storage
Networking
IaaS
Infrastructure as a Service
Applications
Data
Runtime
Middleware
OS
Virtualization
Servers
Storage
Networking
PaaS
Platform as a Service
Managed by YOU Managed by cloud vendor
Applications
Data
Runtime
Middleware
OS
Virtualization
Servers
Storage
Networking
on-prem
all you, no cloud
02
Google Cloud
serverless
GCP & G Suite
5. >
Google Compute Engine
Google Cloud
Storage
cloud
cloud
Yeah, we got VMs & big disk… but why*?
Serverless: what & why
● What is serverless?
○ Misnomer
○ "No worries"
○ Developers focus on writing code & solving business problems*
● Why serverless?
○ Fastest growing segment of cloud... per analyst research*:
■ $1.9B (2016) and $4.25B (2018) ⇒ $7.7B (2021) and $14.93B (2023)
○ What if you go viral? Autoscaling: your new best friend
○ What if you don't? Code not running? You're not paying.
* in USD; source:Forbes (May 2018), MarketsandMarkets™ & CB Insights (Aug 2018)
6. G Suite APIs
Top-level documentation and comprehensive developers
overview video at developers.google.com/gsuite
7. 2008 2009 2016 2019 ???
serverless timeline
Google
App Engine
(2008; 2011)
Google
Cloud Functions
(2016; 2017; 2018)
Google
Apps Script
(2009; 2009)
Google
App Maker
(2016; 2018)
Google
Cloud Run
(2019; TBD)
Google Compute Engine, Google Cloud Storage
AWS EC2 & S3; Rackspace; Joyent
SaaS
Software as a Service
PaaS
Platform as a Service
IaaS
Infrastructure as a Service
G Suite (Google Apps)
Yahoo!Mail, Hotmail, Salesforce, Netsuite
Google App Engine, Cloud Functions
Heroku, Cloud Foundry, Engine Yard, AWS Lambda
Google BigQuery, Cloud SQL,
Cloud Datastore, NL, Vision, Pub/Sub
AWS Kinesis, RDS; Windows Azure SQL, Docker
Serverless: PaaS-y compute/processing
Google Apps Script, App Maker
Salesforce1/force.com
8. 03
Intro to
Google Apps Script
Automate & extend G Suite
+JavaScript
-API “flavor”
+built-in
“flavor”
-OAuth2 (you)
!=
10. Google Apps Script is a serverless
JavaScript runtime for automation, and
extension & integration with G Suite,
Google, or other external services.
What can you do with Apps Script?
Simple, < 10 lines Complex, > 1000 lines
Sheets
function
Web app that sends email,
creates calendar invites, &
sends out customized
docs
Anything in between
16. “Our online diagram
application makes it easy
to sketch and share
professional flowchart
diagrams.
That’s why millions of
users choose Lucidchart.”
Lucidchart Website
www.lucidchart.com
Diagram & drawing tool
04
Coding with
Apps Script
Ecosystem tour
23. Accessing maps from
spreadsheets?!?
goo.gl/oAzBN9
This… with help from Google Maps & Gmail
function sendMap() {
var sheet = SpreadsheetApp.getActiveSheet();
var address = sheet.getRange("A2").getValue();
var map = Maps.newStaticMap().addMarker(address);
GmailApp.sendEmail('friend@example.com', 'Map',
'See below.', {attachments:[map]});
}
JS
24. ● Extend functionality of G Suite editors
● Embed your app within ours!
● 2014: Google Docs, Sheets, Forms
● 2017 Q3: Google Slides
● 2017 Q4: Gmail
● 2018 Q1: Hangouts Chat bots
● Apps Script also powers App Maker,
Google Data Studio community
connectors, and Google Ads scripts
Apps Script powers add-ons… and more!
Expense
reports...
● Expense reports
● Can't we do them
without leaving Gmail?
● On Web AND mobile?
25. ● At your desk or on the road
● One place to complete
your expense report
● One code base
Gmail Add-ons
Expediting expense
reports
goo.gl/KUVCDu
Simple sentiment & classification analysis
● Analyze sentiment in
Google Docs
● Use simple API call to
Natual Language API
● Call with Apps Script
UrlFetch service
● Build this app yourself at
g.co/codelabs/nlp-docs
26. [simple API/API key sample]
Simple sentiment & classification analysis
// Create API payload
var nlOptions = {
method: 'POST',
contentType: 'application/json',
payload: JSON.stringify(nlData)
};
// Make API call via UrlFetch (when no object available)
var response = UrlFetchApp.fetch(apiEndpoint, nlOptions);
var data = JSON.parse(response);
var sentiment = 0.0;
if (data && data.documentSentiment && data.documentSentiment.score) {
sentiment = data.documentSentiment.score;
}
return sentiment;
}
● Not just for conversations
● Create microservice utilities
● Build chat bots to...
○ Automate workflows
○ Query for information
○ Other heavy-lifting
● Plain text or rich UI "cards"
● Very flexible ("any")
development environment
○ POST to HTTP port
Hangouts Chat bots
(bot framework & API)
27. “I got to work deploying a
light-weight Flask app server…
and in less than an hour had a
working chatbot.”
Greg Meyers, Motorola Solutions CIO
goo.gl/1QeG51
Build bots for anyone, your org or your team… FAST
"Hello World" (echo bot)
JavaScript: Google Apps Script
function onMessage(m) {
return {
'text': 'Hi ' + m.sender.displayName + '. You sent: ' + m.text,
'thread': {'name': m.thread.name}
};
}
Hangouts Chat bots
goo.gl/jt3FqK
28. function onMessage(e) {
return createMessage(e.user.displayName, 0);
}
function onCardClick(e) {
// Create a new vote card when 'NEW' button is clicked.
if (e.action.actionMethodName === 'newvote') {
return createMessage(e.user.displayName, 0);
}
// Updates the card in-place when '+1' or '-1' button is clicked.
var voteCount = +e.action.parameters[0].value;
e.action.actionMethodName === 'upvote' ? ++voteCount : --voteCount;
return createMessage(e.user.displayName, voteCount, true);
}
Simple vote bot
JavaScript: Google Apps Script
Hangouts Chat bots
goo.gl/jt3FqK
● Command-line interface
● Intergrate with git plus
your local IDE/dev env.
● Actions
○ Create
○ Pull
○ Push
○ Clone
○ Deploy
○ View logs
● Built on Apps Script API
● Launched early 2018
Professional workflow with clasp tool
29. 05
All of Cloud
(inspiration)
Build powerful solutions
with both GCP and G Suite
Big data analysis to slide presentation
Access GCP tools from G Suite
33. Supercharge G Suite with GCP
G Suite GCP
BigQuery
Apps Script
Slides Sheets
Application
request
Big data
analytics
App summary
● Leverage GCP and build the "final mile" with G Suite
● Driven by Google Apps Script
● Google BigQuery for data analysis
● Google Sheets for visualization
● Google Slides for presentable results
● "Glued" together w/G Suite serverless
● Build this app (codelab)
● g.co/codelabs/bigquery-sheets-slides
● Video and blog post
● bit.ly/2OcptaG
● Application source code
● github.com/googlecodelabs/bigquery-sheets-slides
● Presented at Google Cloud NEXT (Jul 2018 [DEV229] & Apr 2019 [DEV212])
● cloud.withgoogle.com/next18/sf/sessions/session/156878
● cloud.withgoogle.com/next/sf/sessions?session=DEV212
35. Sheets
Cloud
SQL
Lightweight inventory management system
Cloud
Functions
Cloud
Vision
G Suite GCP
Export
data
Cloud
Functions
Apps Script
Analyze
image
Get
inventory
CRUD
inventory
App summary
● Motivation
● Help sales floor staff with store inventory information
● GCP helps Sheets scale and provide machine learning capabilities
● Web interface for scale and convenience
● Use G Suite and GCP APIs to:
● Build friendly web interface (mobile or computer)
● Export Sheets data into Cloud SQL
● Allow users to make information requests
● Add intelligence to data and enahance user experience
● Cloud Functions microservices leveraging Sheets as "glue tool" for user experience
● Application source code: github.com/asrivas/Next2019
● Presented at Google Cloud NEXT '19
● cloud.withgoogle.com/next/sf/sessions?session=SVR105
36. 06
BONUS, resources
and summary
BONUS: alternative to Apps Script
● HTTP-based REST APIs
○ Lower-level, higher-flexibility
○ Code in your own development environment
○ Introductory G Suite APIs codelab
■ g.co/codelabs/gsuite-apis-intro
37. List (first 100) files/folders in Google Drive
from __future__ import print_function
from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
files = DRIVE.files().list().execute().get('files', [])
for f in files:
print(f['name'], f['mimeType'])
Listing your files
goo.gl/ZIgf8k
Migrate SQL data to a Sheet
# read SQL data then create new spreadsheet & add rows into it
FIELDS = ('ID', 'Customer Name', 'Product Code',
'Units Ordered', 'Unit Price', 'Status')
cxn = sqlite3.connect('db.sqlite')
cur = cxn.cursor()
rows = cur.execute('SELECT * FROM orders').fetchall()
cxn.close()
rows.insert(0, FIELDS)
DATA = {'properties': {'title': 'Customer orders'}}
SHEET_ID = SHEETS.spreadsheets().create(body=DATA,
fields='spreadsheetId').execute().get('spreadsheetId')
SHEETS.spreadsheets().values().update(spreadsheetId=SHEET_ID, range='A1',
body={'values': rows}, valueInputOption='RAW').execute()
Migrate SQL data
to Sheets
goo.gl/N1RPwC
38. Creating events in Calendar
# define event data, then create event
TIMEZONE = 'America/Los_Angeles'
EVENT = {
'summary': 'Dinner with friends',
'start': {'dateTime': '2017-06-14T19:00:00', 'timeZone': TIMEZONE},
'end': {'dateTime': '2017-06-14T22:00:00', 'timeZone': TIMEZONE},
'attendees': [
{'email': 'friend1@example.com'},
{'email': 'friend2@example.com'},
],
}
GCAL.events().insert(calendarId='primary', body=EVENT,
sendNotifications=True, fields='').execute()
Modifying and
recurring events
goo.gl/J2XkXc
Creating events
goo.gl/KuYMiq
BigQuery: querying Shakespeare words
from random import choice
from google.cloud import bigquery
TITLE = "The most common words in all of Shakespeare's works"
QUERY = '''
SELECT LOWER(word) AS word, sum(word_count) AS count
FROM `bigquery-public-data.samples.shakespeare`
GROUP BY word ORDER BY count DESC LIMIT 10
'''
rsp = bigquery.Client().query(QUERY).result()
print('n*** Results for %r:n' % TITLE)
print('t'.join(col.name.upper() for col in rsp.schema)) # HEADERS
print('n'.join('t'.join(str(x) for x in row.values()) for row in rsp)) # DATA
39. Top 10 most common Shakespeare words
$ python bq_shake.py
*** Results for "The most common words in all of Shakespeare's works":
WORD COUNT
the 29801
and 27529
i 21029
to 20957
of 18514
a 15370
you 14010
my 12936
in 11722
that 11519
Apps Script summary
● It’s just JavaScript
● Access to Google plus other online resources
● No API complexity… use authenticated, built-in
services
● Serverless… no setup nor deployment required
● Variety of use cases
● Execution as scripts or add-ons
● No longer Google's best kept secret?!?
40. Apps Script references + next steps
● Introductory Apps Script codelab
○ g.co/codelabs/apps-script-intro
● Developer videos, guides, and tutorials
○ developers.google.com/apps-script/guides/videos
● Documentation
○ developers.google.com/apps-script
● Alternative: G Suite REST APIs
○ developers.google.com/gsuite
Session Summary
● G Suite isn't just a set of productivity apps
○ You can code these apps too!
○ Create tools to automate workflows
○ Leverage different data in your G Suite domain
● How can you code G Suite?
○ Your environment: G Suite REST APIs
○ Our environment: Google Apps Script or Google App Maker
■ Go serverless and focus on logic not app-hosting
○ Interesting possibilities using both platforms (GCP + G Suite)
41. Other Google APIs & platforms
● GCP (cloud-based compute, storage, networking, AI/ML, data analysis tools!)
○ cloud.google.com
● Firebase (mobile development platform + RT DB)
○ firebase.google.com
● Google Data Studio (data visualization, dashboards, etc.)
○ marketingplatform.google.com/about/data-studio
● Actions on Google/Assistant/DialogFlow (voice apps)
○ developers.google.com/actions
● YouTube (Data, Analytics, and Livestreaming APIs)
○ developers.google.com/youtube
● Google Maps (Maps, Routes, and Places APIs)
○ developers.google.com/maps
● Flutter (native apps [Android, iOS, web] w/1 code base[!])
○ flutter.dev
Get started today w/G Suite "codelabs"
● Self-paced, hands-on tutorials, always free, Google/Gmail/G Suite acct req'd
● Directory: codelabs.developers.google.com/?cat=Apps
● Catalog:
REST APIs
Intro to G Suite APIs g.co/codelabs/gsuite-apis-intro
Sheets API g.co/codelabs/sheets
Slides + BigQuery APIs g.co/codelabs/slides
Google App Maker
Build a database web app g.co/codelabs/appmaker
Google Apps Script
Intro to Apps Script g.co/codelabs/apps-script-intro
Gmail Add-ons g.co/codelabs/gmail-add-ons
clasp g.co/codelabs/clasp
Docs Add-on+GCP NL API g.co/codelabs/nlp-docs
Hangouts Chat g.co/codelabs/chat-apps-script
BigQuery-Sheets-Slides g.co/codelabs/bigquery-sheets-slides
42. Learning resources
● Codelabs: self-paced, hands-on tutorials
○ Google codelabs: need a Gmail account, always free
■ g.co/codelabs/cloud
○ Qwiklabs codelabs: don't need a Gmail acct; typically not free
■ google.qwiklabs.com
■ Request free credits ("tokens") at cloud.google.com/edu
● GCP documentation
○ cloud.google.com/gcp/getting-started
○ Recommended: Getting Started, Cloud Console, Cloud Shell, Cloud SDK, Community
● YouTube developer video series:
○ GCP: youtube.com/GoogleCloudPlatform
○ G Suite: goo.gl/JpBQ40
○
Resources for Higher Education
● Education grant program
○ Teaching grants (per-course basis)
■ $50USD for students & $100USD for faculty & TAs
■ Must exceed "Always Free" daily/monthly quota to incur billing
■ Students will barely use it… average utilization: <25%
■ KEY: not giving Google your personal credit card
○ Research grants
■ Larger amounts; consider as seed funding
■ Over a longer period of time (more than a single term)
○ Apply at cloud.google.com/edu
○ Turnaround time: "within a few business days"
○ Redeem at console.cloud.google.com/edu
43. Invite me (or my team) to
your campus... it's our job!
● Faculty & grad students
● Researchers
● Undergrads
● University IT staff/CIO/CTO
● University entrepreneurship
centers/capstone project leads
Thank you! Questions?
Wesley Chun
@wescpy
Progress bars: goo.gl/69EJVw