🚀 Apps Script + Gemini Mastery — Issue #1
“Your First AI-Powered Script: Build a Smart Document Analyzer”
A newsletter series for experienced Google Apps Script developers who want to level up with AI-powered automation, real-world exercises, and fully working code.
⭐ Welcome to the Series
This series will teach you how to:
- Use Gemini inside Apps Script
- Build AI-powered tools (text analysis, data transformation, doc generation, automation)
- Add custom UIs and integrate Gemini into Docs, Sheets, Slides & Gmail
- Create deployable add-ons
- Learn through hands-on exercises, full code, and clear setup steps
Each issue includes:
✔ A complete lesson
✔ A real project
✔ Full Apps Script source code
✔ A downloadable menu/UI
✔ Testing instructions
✔ “What you learned” section
📘 Lesson 1 — Build an AI Document Analyzer for Google Docs
This lesson teaches you how to build your first Gemini-powered automation:
Select text → Run “Analyze Text with Gemini” → Receive insights, summary, rewrite suggestions, sentiment analysis, and more.
Perfect for Docs users—and a strong start to the series.
🧠 What You Will Build
A custom Apps Script menu:
AI Tools
→ Analyze Selected Text
→ Summarize the Document
→ Rewrite for Clarity
Each option sends your text to Gemini and displays structured results in a sidebar.
🛠️ What You Will Learn
By the end of Issue #1, you’ll know how to:
- Connect to the Gemini API through Apps Script
- Create a custom menu (with submenus)
- Build a sidebar UI
- Extract selected text from Google Docs
- Send requests to Gemini and handle responses
- Output results cleanly back into the Doc
This is foundational for more advanced lessons (RAG, embeddings, agents, Sheets automation, Gmail AI tools, etc.)
🧩 EXERCISE — Build the AI Document Analyzer
STEP 1 — Set up the Script
Open any Google Doc → Extensions → Apps Script → Paste this code:
📄 Code: DocsMenu.gs
function onOpen() {
DocumentApp.getUi()
.createMenu("AI Tools")
.addItem("Analyze Selected Text", "showAnalyzeSidebar")
.addItem("Summarize Document", "summarizeDocument")
.addItem("Rewrite for Clarity", "rewriteForClarity")
.addToUi();
}
STEP 2 — Add Gemini Helper
Replace "YOUR_API_KEY" with your Gemini API Key:
📄 Code: GeminiHelpers.gs
const GEMINI_API_KEY = "YOUR_API_KEY";
const GEMINI_MODEL= 'gemini-2.0-flash';
function callGemini(prompt, text) {
const url = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=${GEMINI_API_KEY}`;
const payload = {
contents: [{
parts: [{
text: `${prompt}\n\n---\n\n${text}`
}]
}]
};
const res = UrlFetchApp.fetch(url, {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload),
muteHttpExceptions: true
});
const json = JSON.parse(res.getContentText());
return json.candidates?.[0]?.content?.parts?.[0]?.text || "No response from Gemini.";
}
STEP 3 — Build the Sidebar UI
📄 Code: Sidemenu.gs
function showAnalyzeSidebar() {
const html = HtmlService.createHtmlOutputFromFile("Sidebar")
.setTitle("AI Text Analyzer");
DocumentApp.getUi().showSidebar(html);
}
function analyzeSelectedText() {
const doc = DocumentApp.getActiveDocument();
const selection = doc.getSelection();
if (!selection) return "No text selected.";
let text = "";
selection.getRangeElements().forEach(el => {
if (el.getElement().editAsText) {
text += el.getElement().asText().getText() + "\n";
}
});
const prompt = `
Analyze the following text. Provide:
1. Key insights
2. Summary (3–5 bullet points)
3. Suggested improvements
4. Overall sentiment
5. Rewrite for clarity
`;
return callGemini(prompt, text);
}
function summarizeDocument() {
const bodyText = DocumentApp.getActiveDocument().getBody().getText();
return callGemini("Summarize the following document:", bodyText);
}
function rewriteForClarity() {
const bodyText = DocumentApp.getActiveDocument().getBody().getText();
return callGemini("Rewrite the document for clarity and simplicity:", bodyText);
}
STEP 4 — Create the Sidebar HTML
📄 File: Sidebar.html
<div style="font-family: Arial; padding: 10px;">
<h2>AI Document Analyzer</h2>
<button onclick="run('analyzeSelectedText')">Analyze Selected Text</button>
<button onclick="run('summarizeDocument')">Summarize Document</button>
<button onclick="run('rewriteForClarity')">Rewrite for Clarity</button>
<pre id="output" style="white-space: pre-wrap; margin-top: 20px;"></pre>
<script>
function run(fn) {
google.script.run.withSuccessHandler(function(result) {
document.getElementById("output").textContent = result;
})[fn]();
}
</script>
</div>
🧪 Testing Instructions
- Open a Google Doc
- Highlight any text
- Go to AI Tools → Analyze Selected Text
- Watch results appear in the sidebar
- Try the other menu items
If everything works, congratulations — you’ve built your first Gemini-powered Google Doc add-on!
🎓 What You Learned
- Creating custom UI menus
- Adding a sidebar
- Extracting text
- Structuring Gemini prompts
- Handling API responses
- Building reusable AI helpers
This foundation will support all advanced lessons to come:
Coming next in Issue #2:
🔥 AI-Powered Content Generator for Docs
Generate blog posts, lesson plans, and formatted documents using structured prompts + Gemini.
Here’s a setup Apps Script that will create the lesson content + sample text directly in the current Google Doc.
1. Add this function to your Apps Script project
Create a new file (e.g. SetupLessonDoc.gs) and paste:
function setupLessonDoc() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
// Start with a clean slate
body.clear();
// Title
body.appendParagraph("Apps Script + Gemini Mastery — Issue #1")
.setHeading(DocumentApp.ParagraphHeading.HEADING1);
body.appendParagraph("Your First AI-Powered Script: Build a Smart Document Analyzer")
.setHeading(DocumentApp.ParagraphHeading.HEADING2);
body.appendParagraph(
"This document was generated by the setup script. " +
"Use it as your working file to test the AI Tools menu connected to Gemini."
);
body.appendParagraph("");
// Section: What You Will Build
body.appendParagraph("What You Will Build")
.setHeading(DocumentApp.ParagraphHeading.HEADING2);
body.appendParagraph(
"In this lesson, you will build an AI-powered Document Analyzer for Google Docs. " +
"You will be able to select text and then run AI Tools → Analyze Selected Text " +
"to get insights, summaries, and rewrite suggestions from Gemini."
);
// Section: Instructions
body.appendParagraph("How to Use This Doc with the AI Tools Menu")
.setHeading(DocumentApp.ParagraphHeading.HEADING2);
body.appendListItem("Select any paragraph or section of text below.")
.setGlyphType(DocumentApp.GlyphType.BULLET);
body.appendListItem("Open the menu: AI Tools → Analyze Selected Text.")
.setGlyphType(DocumentApp.GlyphType.BULLET);
body.appendListItem("Review the output in the sidebar (insights, summary, rewrite).")
.setGlyphType(DocumentApp.GlyphType.BULLET);
body.appendListItem("Experiment with Summarize Document and Rewrite for Clarity.")
.setGlyphType(DocumentApp.GlyphType.BULLET);
body.appendParagraph("");
// Section: Sample Content to Analyze
body.appendParagraph("Sample Article for AI Analysis")
.setHeading(DocumentApp.ParagraphHeading.HEADING2);
const sampleParagraphs = [
"Most teams struggle to turn raw information into clear, usable knowledge. " +
"Documents grow longer, feedback gets buried in email threads, and important " +
"decisions are scattered across chats and comments.",
"AI-powered tools like Gemini can help by quickly summarizing long documents, " +
"highlighting key decisions, and suggesting better ways to express ideas. " +
"Instead of manually rewriting paragraphs, you can focus on thinking and " +
"strategy while the AI handles structure and phrasing.",
"However, AI only becomes truly powerful when it is integrated into your existing workflow. " +
"That is why Google Apps Script is such a valuable layer: it lets you bring Gemini " +
"directly into Docs, Sheets, Slides, and Gmail, automating the tasks you already do " +
"every day.",
"In this lesson, you will experiment with an AI Document Analyzer that you can customize. " +
"Try selecting different sections of this article and see how the AI changes its " +
"summary, insights, and suggestions based on what you highlight."
];
sampleParagraphs.forEach(text => body.appendParagraph(text));
body.appendParagraph("");
// Extra block of text for testing summaries
body.appendParagraph("Longer Sample Section")
.setHeading(DocumentApp.ParagraphHeading.HEADING3);
body.appendParagraph(
"Imagine you are responsible for reviewing weekly project reports from multiple " +
"teams. Each report is several pages long, combining metrics, narrative updates, " +
"risks, and next steps. Reading every word is unrealistic, but skipping sections " +
"means missing important context. With an embedded AI assistant, you can highlight " +
"a section and instantly ask for a concise summary, a list of risks, or a clearer " +
"rewrite that you can paste into your own executive update."
);
body.appendParagraph(
"This is the type of workflow enhancement that Apps Script + Gemini makes possible. " +
"As you test the AI Tools menu on this document, think about the documents you " +
"work with every day: course outlines, project charters, meeting notes, or client " +
"proposals. Any place where you read, summarize, and rewrite text is an opportunity " +
"to add intelligence with just a few lines of code."
);
body.appendParagraph("");
body.appendParagraph("✅ Setup complete. You can now experiment with the AI Tools menu on this content.");
}
2. (Optional) Add a menu item to run the setup from Docs
If you want this available as a one-click option in the Doc UI, update your existing onOpen() like this:
function onOpen() {
DocumentApp.getUi()
.createMenu("AI Tools")
.addItem("Analyze Selected Text", "showAnalyzeSidebar")
.addItem("Summarize Document", "summarizeDocument")
.addItem("Rewrite for Clarity", "rewriteForClarity")
.addSeparator()
.addItem("Setup Lesson Doc", "setupLessonDoc")
.addToUi();
}
3. How to use it
- Open your target Google Doc.
- In Apps Script, run
setupLessonDoconce (or use the menu item if you added it). - The document will be populated with:
- Title + subtitle for Issue #1
- Short explanation of the tool
- Instructions for using the AI menu
- Several paragraphs of realistic sample content to analyze
Then just use your Gemini-powered AI Tools menu on the generated text.