Teacher Help!

39 views
Skip to first unread message

ethan brook

unread,
Nov 18, 2025, 10:33:47 AM (12 days ago) Nov 18
to Google Apps Script Community
I'm trying to write a script that highlight text boxes in google slides that have sentences without a period.  Here's the code from Chat GPT: 
function onOpen() {
  SlidesApp.getUi().createMenu('Highlight Tool')
    .addItem('Highlight Sentences Missing Period', 'highlightSentencesMissingPeriod')
    .addToUi();
}

function highlightSentencesMissingPeriod() {
  const slideDeck = SlidesApp.getActivePresentation();
  const slides = slideDeck.getSlides();

  // Loop through each slide in the presentation
  slides.forEach(function(slide) {
    // Get all text elements (text boxes) on the slide
    const textElements = slide.getPageElements().filter(function(element) {
      return element.getPageElementType() === SlidesApp.PageElementType.TEXT_BOX;
    });

    // Loop through each text box on the slide
    textElements.forEach(function(textBox) {
      const textRange = textBox.asTextBox().getText();
      const text = textRange.getText().trim();  // Extract the entire text

      // Check if the text ends with a period
      if (text && !text.endsWith('.')) {
        // Apply pink highlight to the entire text box if missing period
        textRange.getTextStyle().setBackgroundColor("#FF69B4");  // Pink color
      }
    });
  });
}

I can't get it to work.  Help!

Michael O'Shaughnessy

unread,
Nov 18, 2025, 7:03:40 PM (11 days ago) Nov 18
to google-apps-sc...@googlegroups.com
DISCLAIMER:  This code I am sharing was created by Claude.AI.  I tested it in one Google Slides presentation and it appeared to work for me.  Your experience may be different.

OK, I am not sure why your code doesn't work. I can only say that it might be the getTextBox() functions that you are trying to use.  I have done work with slides and you really need to look at the "shapes" that are on the slide.

Next, when I run into issues like you have I ask ChatGPT (or whatever AI I am using) to add comments to the code and use logging.  The comments let me know what the code is doing and the logging helps me see where potential errors are happening.

And, I have found that Claude.AI gives me better Google Apps Script code responses than ChatGPT.  Again, let me say that this is MY EXPERIENCE!  If others have better AIs to use please let me know!

So this is the prompt I used with Claude.AI
"You are an expert in Google apps script.  I need you to write code that will look through all the slides of a presentation and highlight sentences that do not end with a period.  Please make sure you use comments and logging so we can see what the code is doing."

And here is the code it gave me:
/**
 * Main function to check all slides for sentences without periods
 * Run this function from the Apps Script editor
 */
function highlightSentencesWithoutPeriods() {
  // Get the active presentation
  const presentation = SlidesApp.getActivePresentation();
  Logger.log('Starting analysis of presentation: ' + presentation.getName());
 
  // Get all slides in the presentation
  const slides = presentation.getSlides();
  Logger.log('Total slides found: ' + slides.length);
 
  let totalIssuesFound = 0;

 
  // Loop through each slide
  slides.forEach((slide, slideIndex) => {
    Logger.log('\n--- Analyzing Slide ' + (slideIndex + 1) + ' ---');
   
    // Get all shapes on the slide (text boxes, shapes with text, etc.)
    const shapes = slide.getShapes();
    Logger.log('Shapes found on slide ' + (slideIndex + 1) + ': ' + shapes.length);
   
    // Loop through each shape
    shapes.forEach((shape, shapeIndex) => {
      // Check if the shape has text
      if (shape.getText()) {
        const textRange = shape.getText();
        const fullText = textRange.asString();
       
        // Skip if the text is empty or just whitespace
        if (fullText.trim().length === 0) {
          return;
        }
       
        Logger.log('  Shape ' + (shapeIndex + 1) + ' text: "' + fullText.substring(0, 50) + '..."');
       
        // Split text into lines to analyze each one
        const lines = fullText.split('\n');
       
        lines.forEach((line, lineIndex) => {
          const trimmedLine = line.trim();
         
          // Skip empty lines
          if (trimmedLine.length === 0) {
            return;
          }
         
          // Check if line ends with a period, or other acceptable punctuation
          const lastChar = trimmedLine.charAt(trimmedLine.length - 1);
          const acceptablePunctuation = ['.', '!', '?', ':', ';'];
         
          // If the line doesn't end with acceptable punctuation, highlight it
          if (!acceptablePunctuation.includes(lastChar)) {
            Logger.log('    ⚠️ Issue found in line ' + (lineIndex + 1) + ': "' + trimmedLine + '"');
            Logger.log('    Last character: "' + lastChar + '"');
           
            // Highlight the text in yellow
            highlightTextInShape(shape, line);
            totalIssuesFound++;
          }
        });
      }
    });
   
    // Also check tables on the slide
    const tables = slide.getTables();
    if (tables.length > 0) {
      Logger.log('Tables found on slide ' + (slideIndex + 1) + ': ' + tables.length);
      checkTablesForPeriods(tables, slideIndex + 1);
    }
  });
 
  // Final summary
  Logger.log('\n========== SUMMARY ==========');
  Logger.log('Total slides analyzed: ' + slides.length);
  Logger.log('Total issues found: ' + totalIssuesFound);
  Logger.log('Analysis complete! Check the slides for yellow highlights.');
}

/**
 * Highlights specific text within a shape by finding and highlighting it
 * @param {Shape} shape - The shape containing the text
 * @param {string} textToHighlight - The text line to highlight
 */
function highlightTextInShape(shape, textToHighlight) {
  try {
    const textRange = shape.getText();
    const fullText = textRange.asString();
   
    // Find the position of the text to highlight
    const startIndex = fullText.indexOf(textToHighlight);
   
    if (startIndex !== -1) {
      // Get the range for just this text
      const range = textRange.getRange(startIndex, startIndex + textToHighlight.length);
     
      // Set yellow background color
      range.getTextStyle().setBackgroundColor('#FFFF00');
     
      Logger.log('    ✓ Highlighted text successfully');
    }
  } catch (error) {
    Logger.log('    ✗ Error highlighting text: ' + error.message);
  }
}

/**
 * Checks tables for sentences without periods
 * @param {Table[]} tables - Array of tables to check
 * @param {number} slideNumber - The slide number for logging
 */
function checkTablesForPeriods(tables, slideNumber) {
  tables.forEach((table, tableIndex) => {
    Logger.log('  Checking table ' + (tableIndex + 1) + ' on slide ' + slideNumber);
   
    const numRows = table.getNumRows();
    const numCols = table.getNumColumns();
   
    // Loop through each cell
    for (let row = 0; row < numRows; row++) {
      for (let col = 0; col < numCols; col++) {
        const cell = table.getCell(row, col);
        const cellText = cell.getText().asString().trim();
       
        if (cellText.length > 0) {
          const lastChar = cellText.charAt(cellText.length - 1);
          const acceptablePunctuation = ['.', '!', '?', ':', ';'];
         
          if (!acceptablePunctuation.includes(lastChar)) {
            Logger.log('    ⚠️ Issue in table cell [' + row + ',' + col + ']: "' + cellText + '"');
           
            // Highlight the cell text
            cell.getText().getTextStyle().setBackgroundColor('#FFFF00');
          }
        }
      }
    }
  });
}

What is interesting is that it included tables... I did not ask it to do that but it did it anyway!

Let me know if you have any questions.

DISCLAIMER:  This code was created by Claude.AI.  I tested it in one Google Slides presentation and it appeared to work for me.


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/6e21a982-8c8c-4e75-bb73-595daf0751fcn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages