Search Term Alert - Free Script

Search Term Watchdog: Free Google Ads Script

Someone in the community wrote to me to tell me about a mistake they made that cost them dearly.

They added what seemed like a smart negative keyword list. Broad match negatives that would clean up their search terms report. Except it blocked their brand terms. Yeah, ouch.

And their best converting search terms. Double ouch.

Performance tanked.

They called their client, admitted the mistake, and then asked me: "Do you know of a watchdog script that can check top search terms and alert if there's a fall historically?"

That question became this script.

How It Started

The first version was simple. A Google Ads Script that:

- Grabs your top N search terms by cost

- Compares the last 7 days to a 13-week baseline

- Flags any drops with yellow (50% decline) or red (80% decline) alerts

- Emails you when something's wrong

- Exports everything to a sheet

Useful. But it was just the beginning.

The Adjacent Possible

Each working version unlocked the next improvement. Once the core was stable, I could simplify the fetch logic. Once that worked, I could add smarter thresholds so low-volume terms didn't trigger false alarms. Once that was reliable, I could add campaign-level monitoring instead of just account-wide.

The progression looked like this:

- Working script -> fix critical GAQL bug

- Stable fetch -> simplify batching

- Simple alerts -> smarter thresholds for low-volume terms

- Account-wide -> campaign-level insights

- Name filters -> robust ID filtering (campaign renames don't break it)

- On/off switch -> email triggers & summary reporting

- Hardcoded values -> configurable alert sensitivity

Nine iterations. Each one building on what was already working.

What the Script Does Now

- Monitors your top search terms (configurable, default 100)

- Works with Search, Shopping, or both campaign types

- Can aggregate at account level or per-campaign

- Compares recent performance to a rolling 13-week baseline

- Smart alerts that ignore low-volume noise

- Configurable sensitivity thresholds

- Email notifications with multiple trigger options

- Full results exported to a Google Sheet

You configure it once, schedule it to run daily, and it watches your back.

Why This Matters

Scripts like this are your first step toward AI automation in Google Ads. They're accessible - you can copy, paste, and customize without a CS degree. They catch problems before your client does. And they free you up to do the strategic work that actually moves accounts forward.

This is the kind of practical automation that separates reactive account managers from proactive ones.

Get the Script

The full script and detailed evolution story are available below, or here:

https://github.com/mikerhodesideas/free/blob/main/search-term-alert

Copy it, run it.

Feel free to customize it (and if you break something, that's how you learn! Use AI to fix it again).

Questions? Drop them in #Ask Questions & Help Others section.


/**
 * Search Term Watchdog Script
 *
 * Monitors your top search terms for drops in conversions,
 * either across the whole account or per search/shopping campaign.
 *
 * Instructions:
 *  - (Optional) Fill in SHEET_URL; leave blank to auto-create a sheet
 *  - Adjust TOP_N to monitor a different number of terms
 *  - Enter your EMAIL_ADDRESS
 *  - Set CAMP_TYPE to 'SEARCH', 'SHOPPING', or 'BOTH'
 *  - Set TESTING_MODE to false once you're ready for live alerts
 *  - Switch AGGREGATION to 'ACCOUNT' or 'CAMPAIGN'
 *  - Set email trigger option (see below)
 *  - Adjust MIN_AVG_CONV_FOR_ALERT if needed (min avg conversions to trigger alert checks)
 *  - Adjust PERCENT_THRESHOLD if needed (percentage threshold for yellow alerts)
 * 
 * EMAIL_ALERT_TRIGGER options:
 *  - 'ALWAYS_REPORT': Sends an email every time the script runs.
 *  - 'YELLOW_OR_RED': Sends an email if there are yellow or red alerts.
 *  - 'RED_ONLY': Sends an email if there are red alerts only.
 * 
 * To read how this script came about, please visit 
 * https://github.com/mikerhodesideas/free/blob/main/search-term-alert-evolution
 * 
 */



// ——— Configuration ———

const SHEET_URL              = '';           // Optional: Fill in to use an existing sheet, or leave blank to auto-create.

const TOP_N                  = 100;          // Number of top items to monitor by cost

const EMAIL_ADDRESS          = '';           // *** IMPORTANT: Fill in your email address here ***

const CAMP_TYPE              = 'BOTH';       // Options: 'SEARCH', 'SHOPPING', or 'BOTH'

const TESTING_MODE           = true;         // When true, sends test emails on every run regardless of alerts.
                                             // Set to false for production use, where emails are sent only
                                             // according to EMAIL_ALERT_TRIGGER settings.

const AGGREGATION            = 'ACCOUNT';    // 'ACCOUNT' or 'CAMPAIGN'

const EMAIL_ALERT_TRIGGER    = 'RED_ONLY';   // Options: 'ALWAYS_REPORT', 'YELLOW_OR_RED', 'RED_ONLY'

const MIN_AVG_CONV_FOR_ALERT = 2;            // Minimum average baseline conversions to consider for alerts

const PERCENT_THRESHOLD      = 20;           // Percentage threshold for yellow alerts




// ——— Main ——— Please do not edit code below this line ———

function main() {
    // Check if email address is provided
    if (!EMAIL_ADDRESS || EMAIL_ADDRESS.trim() === '') {
        Logger.log('⚠️ ERROR: No email address provided! ⚠️');
        Logger.log('You must set the EMAIL_ADDRESS constant at the top of the script.');
        Logger.log('Without an email address, no alerts will be sent.');
        Logger.log('Please edit the script, add your email, and run it again.');
        return; // Exit early if no email address
    }

    // Validate CAMP_TYPE
    if (!['SEARCH', 'SHOPPING', 'BOTH'].includes(CAMP_TYPE)) {
        Logger.log('⚠️ ERROR: Invalid CAMP_TYPE! Must be "SEARCH", "SHOPPING", or "BOTH".');
        return;
    }

    const timezone = AdsApp.currentAccount().getTimeZone();
    const ss = getSpreadsheet();
    const sheet = ss.getActiveSheet();
    sheet.clear();

    // 1) Get top terms (with optional campaign)
    const topItems = getTopItems(TOP_N);

    if (!topItems.length) {
        Logger.log('No data found for the specified campaign type(s).');
        return;
    }

    // 2) Build date ranges
    const now = new Date();
    const fmt = d => Utilities.formatDate(d, timezone, 'yyyyMMdd');

    const endCurr = new Date(now); // Create a new Date object based on 'now'
    endCurr.setDate(now.getDate() - 1); // Yesterday

    const startCurr = new Date(now); // Create a new Date object based on 'now'
    startCurr.setDate(now.getDate() - 8); // 8 days ago

    const endBase = new Date(startCurr); // Create a new Date object based on 'startCurr'
    endBase.setDate(startCurr.getDate() - 1); // 1 day before startCurr

    const startBase = new Date(endBase); // Create a new Date object based on 'endBase'
    startBase.setDate(endBase.getDate() - (13 * 7)); // 13 weeks (91 days) before endBase

    const currRange = `WHERE segments.date BETWEEN "${fmt(startCurr)}" AND "${fmt(endCurr)}"`;
    const baseRange = `WHERE segments.date BETWEEN "${fmt(startBase)}" AND "${fmt(endBase)}"`;
    Logger.log(`Date ranges: ${currRange} and ${baseRange}`);

    // 3) Fetch current & baseline metrics
    const currData = fetchMetrics(topItems, currRange);
    const baseData = fetchMetrics(topItems, baseRange);

    // 4) Combine & determine alerts
    // …inside main(), after fetching currData & baseData…

    const output = [];
    let hasAlert = false;
    let analyzedCount = 0;
    let okCount = 0;
    let yellowAlertCount = 0;
    let redAlertCount = 0;

    topItems.forEach(item => {
        analyzedCount++;
        const key = makeKey(item);
        const currConv = (currData[key]?.conversions) || 0;
        const avgBaseConv = ((baseData[key]?.conversions) || 0) / 13;

        let alert = 'OK';

        if (avgBaseConv > MIN_AVG_CONV_FOR_ALERT) {
            if (currConv === 0) {
                alert = 'RED';
                redAlertCount++;
            } else if ((currConv / avgBaseConv) <= (PERCENT_THRESHOLD / 100)) {
                alert = 'YELLOW';
                yellowAlertCount++;
            }
        }
        if (alert === 'OK') {
            okCount++;
        }
        if (alert !== 'OK') hasAlert = true;

        // build row (with or without campaign col and campaign type)
        let row;
        if (AGGREGATION === 'CAMPAIGN') {
            row = CAMP_TYPE === 'BOTH'
                ? [item.campaignName, item.campaignType, item.term, currConv.toFixed(1), avgBaseConv.toFixed(1),
                avgBaseConv > 0 ? (currConv / avgBaseConv * 100).toFixed(0) + '%' : 'N/A', alert]
                : [item.campaignName, item.term, currConv.toFixed(1), avgBaseConv.toFixed(1),
                avgBaseConv > 0 ? (currConv / avgBaseConv * 100).toFixed(0) + '%' : 'N/A', alert];
        } else {
            row = CAMP_TYPE === 'BOTH'
                ? [item.term, item.campaignType, currConv.toFixed(1), avgBaseConv.toFixed(1),
                avgBaseConv > 0 ? (currConv / avgBaseConv * 100).toFixed(0) + '%' : 'N/A', alert]
                : [item.term, currConv.toFixed(1), avgBaseConv.toFixed(1),
                avgBaseConv > 0 ? (currConv / avgBaseConv * 100).toFixed(0) + '%' : 'N/A', alert];
        }

        output.push(row);
    });

    // Sort the output by 'Avg Conv (7d)' descending
    // Adjust sort index based on whether we have the campaign type column
    const avgConvSortIndex = AGGREGATION === 'CAMPAIGN'
        ? (CAMP_TYPE === 'BOTH' ? 4 : 3)
        : (CAMP_TYPE === 'BOTH' ? 3 : 2);

    output.sort((a, b) => {
        // Values in these columns are strings like "123.4" due to toFixed(1)
        const valA = parseFloat(a[avgConvSortIndex]);
        const valB = parseFloat(b[avgConvSortIndex]);
        return valB - valA; // for descending order
    });

    // 5) Write headers + data
    let headers;
    if (AGGREGATION === 'CAMPAIGN') {
        headers = CAMP_TYPE === 'BOTH'
            ? ['Campaign', 'Type', 'Search Term', 'Conv (7d)', 'Avg Conv (7d)', 'Δ Conv', 'Alert']
            : ['Campaign', 'Search Term', 'Conv (7d)', 'Avg Conv (7d)', 'Δ Conv', 'Alert'];
    } else {
        headers = CAMP_TYPE === 'BOTH'
            ? ['Search Term', 'Type', 'Conv (7d)', 'Avg Conv (7d)', 'Δ Conv', 'Alert']
            : ['Search Term', 'Conv (7d)', 'Avg Conv (7d)', 'Δ Conv', 'Alert'];
    }

    sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
    sheet.getRange(2, 1, output.length, headers.length).setValues(output);

    // 6) Send email if in testing mode or if any alerts based on EMAIL_ALERT_TRIGGER
    let emailSent = false;
    const redAlerts = output.filter(row => row[row.length - 1] === 'RED').length;
    const yellowAlerts = output.filter(row => row[row.length - 1] === 'YELLOW').length;

    let shouldSendEmail = TESTING_MODE;
    if (!TESTING_MODE) {
        if (EMAIL_ALERT_TRIGGER === 'ALWAYS_REPORT') {
            shouldSendEmail = true;
        } else if (EMAIL_ALERT_TRIGGER === 'YELLOW_OR_RED' && (yellowAlerts > 0 || redAlerts > 0)) {
            shouldSendEmail = true;
        } else if (EMAIL_ALERT_TRIGGER === 'RED_ONLY' && redAlerts > 0) {
            shouldSendEmail = true;
        }
    }

    try {
        if (shouldSendEmail) {
            const subject = TESTING_MODE ? '[TEST] Watchdog Report' : 'Search Term Watchdog Alerts';
            const body = [
                `Sheet URL: ${ss.getUrl()}`,
                '',
                `Campaign type analyzed: ${CAMP_TYPE}`,
                '',
                'Top items and their conv changes:',
                // ... rest of the body construction
            ];
            
            // Add more logging for debugging
            Logger.log('Attempting to send email to: ' + EMAIL_ADDRESS);
            Logger.log('Email subject: ' + subject);
            
            // Actually send the email
            MailApp.sendEmail(EMAIL_ADDRESS, subject, body.join('\n'));
            
            // If we get here without an error, the email was sent
            emailSent = true;
            Logger.log('Email sent successfully.');
        } else {
            Logger.log('Not sending email based on current settings (shouldSendEmail: ' + shouldSendEmail + ')');
        }
    } catch (e) {
        // More detailed error logging
        Logger.log('⚠️ ERROR: Failed to send email: ' + e.message);
        Logger.log('Error details: ' + e.stack);
        Logger.log('Please ensure you have the necessary permissions to send emails from scripts.');
        Logger.log('Email address attempted: ' + EMAIL_ADDRESS);
    }

    // Print summary to logs regardless of email status
    Logger.log('\n📊 SEARCH TERM ANALYSIS SUMMARY:');
    Logger.log('- Campaign type analyzed: ' + CAMP_TYPE);
    Logger.log('- Total terms analyzed: ' + analyzedCount);
    Logger.log('- Terms OK: ' + okCount);
    Logger.log('- Yellow Alerts: ' + yellowAlertCount);
    Logger.log('- Red Alerts: ' + redAlertCount);
    Logger.log('\nResults have been saved to: ' + ss.getUrl());

    if (emailSent) {
        Logger.log('✅ Email sent to: ' + EMAIL_ADDRESS);
    } else if (!EMAIL_ADDRESS || EMAIL_ADDRESS.trim() === '') {
        Logger.log('\n⚠️ IMPORTANT: No email address configured. Email alerts were NOT sent.');
        Logger.log('To receive email alerts, please edit the script and set the EMAIL_ADDRESS constant.');
    } else {
        Logger.log('ℹ️ No email sent based on current alert trigger (' + EMAIL_ALERT_TRIGGER + ') and alert status.');
    }

    Logger.log('Done.');
}

// ——— Helpers ———

function getSpreadsheet() {
    if (SHEET_URL && SHEET_URL.trim()) {
        return SpreadsheetApp.openByUrl(SHEET_URL);
    }
    const ss = SpreadsheetApp.create('Search Term Watchdog');
    Logger.log('Created new spreadsheet: ' + ss.getUrl());
    return ss;
}

function makeKey(item) {
    return AGGREGATION === 'CAMPAIGN'
        ? `${item.campaignId}||${item.term}`
        : item.term;
}

function getTopItems(limit) {
    // Determine the channel type filter based on CAMP_TYPE
    let channelTypeFilter;

    if (CAMP_TYPE === 'BOTH') {
        // Avoid parentheses in the query
        channelTypeFilter = ""; // No filter, we'll accept all types and filter later
    } else {
        channelTypeFilter = `AND campaign.advertising_channel_type = '${CAMP_TYPE}'`;
    }

    if (AGGREGATION === 'CAMPAIGN') {
        const selectCampaign = 'campaign.id, campaign.name, campaign.advertising_channel_type, search_term_view.search_term, metrics.cost_micros';
        const queryCampaign = `
          SELECT ${selectCampaign}
          FROM search_term_view
          WHERE segments.date DURING LAST_30_DAYS
            ${channelTypeFilter}
          ORDER BY metrics.cost_micros DESC
          LIMIT ${limit}
        `;
        const itCampaign = AdsApp.search(queryCampaign);
        const campaignItems = [];
        while (itCampaign.hasNext()) {
            const row = itCampaign.next();
            campaignItems.push({
                campaignId: row.campaign.id,
                campaignName: row.campaign.name,
                campaignType: row.campaign.advertisingChannelType,
                term: row.searchTermView.searchTerm
            });
        }
        return campaignItems;
    } else { // ACCOUNT mode
        // Different approach for account level - we need to get unique terms,
        // but also track campaign type if CAMP_TYPE is 'BOTH'
        const selectAccount = 'search_term_view.search_term, campaign.advertising_channel_type, metrics.cost_micros';
        // Fetch more than 'limit' to ensure we can find 'limit' unique terms.
        const queryAccountLimit = limit * 3;
        const queryAccount = `
          SELECT ${selectAccount}
          FROM search_term_view
          WHERE segments.date DURING LAST_30_DAYS
            ${channelTypeFilter}
          ORDER BY metrics.cost_micros DESC
          LIMIT ${queryAccountLimit}
        `;
        const itAccount = AdsApp.search(queryAccount);
        const accountItems = [];
        const seenTerms = new Set();
        while (itAccount.hasNext()) {
            if (accountItems.length >= limit) {
                break; // We have found enough unique terms
            }
            const row = itAccount.next();
            const term = row.searchTermView.searchTerm;

            if (CAMP_TYPE === 'BOTH') {
                // For 'BOTH', we need to handle terms that appear in both campaign types
                // We'll take the first appearance of a term, but track its campaign type
                if (!seenTerms.has(term)) {
                    accountItems.push({
                        term: term,
                        campaignType: row.campaign.advertisingChannelType
                    });
                    seenTerms.add(term);
                }
            } else {
                // For single campaign type, we just need unique terms
                if (!seenTerms.has(term)) {
                    accountItems.push({ term: term });
                    seenTerms.add(term);
                }
            }
        }
        return accountItems;
    }
}


function fetchMetrics(items, dateRange) {
    const result = {};
    if (!items.length) return result;

    // Determine the channel type filter based on CAMP_TYPE
    let channelTypeFilter;

    if (CAMP_TYPE === 'BOTH') {
        channelTypeFilter = "";
    } else {
        channelTypeFilter = `AND campaign.advertising_channel_type = '${CAMP_TYPE}'`;
    }

    if (AGGREGATION === 'ACCOUNT') {
        // single IN() clause on terms only
        const escaped = items
            .map(it => `"${it.term.replace(/"/g, '\\"')}"`)
            .join(',');
        const query = `
        SELECT
          search_term_view.search_term,
          campaign.advertising_channel_type,
          metrics.conversions
        FROM search_term_view
        ${dateRange}
          AND search_term_view.search_term IN (${escaped})
          ${channelTypeFilter}
      `;
        const it = AdsApp.search(query);
        while (it.hasNext()) {
            const row = it.next();
            const term = row.searchTermView.searchTerm;
            const campaignType = row.campaign.advertisingChannelType;
            const conv = Number(row.metrics.conversions) || 0;

            // For 'BOTH' mode, we need to aggregate across campaign types
            result[term] = (result[term] || 0) + conv;

            // Also store the campaign type if needed for display
            if (CAMP_TYPE === 'BOTH' && items.find(item => item.term === term)) {
                const item = items.find(item => item.term === term);
                if (item && !item.hasOwnProperty('campaignType')) {
                    item.campaignType = campaignType;
                }
            }
        }
    } else {
        // CAMPAIGN mode: query per campaignId/term
        items.forEach(item => {
            const key = `${item.campaignId}||${item.term}`;
            const termEsc = `"${item.term.replace(/"/g, '\\"')}"`;

            const query = `
          SELECT
            campaign.id,
            search_term_view.search_term,
            metrics.conversions
          FROM search_term_view
          ${dateRange}
            AND campaign.id = ${item.campaignId}
            AND search_term_view.search_term = ${termEsc}
            ${channelTypeFilter}
        `;
            const it = AdsApp.search(query);
            let total = 0;
            while (it.hasNext()) {
                total += Number(it.next().metrics.conversions) || 0;
            }
            result[key] = total;
        });
    }

    // Normalize into { conversions } objects with extra properties
    const normalized = {};
    items.forEach(item => {
        const key = AGGREGATION === 'CAMPAIGN'
            ? `${item.campaignId}||${item.term}`
            : item.term;

        normalized[key] = {
            conversions: (AGGREGATION === 'CAMPAIGN' ? result[key] : result[item.term]) || 0,
            campaignName: item.campaignName,           // undefined in ACCOUNT mode
            campaignType: item.campaignType || CAMP_TYPE // Use the item's campaign type or the global setting
        };
    });
    return normalized;
}

// Thanks for using this script
// For more free scripts, head to https://8020agent.com/4cs

// PS You're awesome!