Skip to content

Instantly share code, notes, and snippets.

@BrainlabsDigital
Created March 20, 2017 14:47
Show Gist options
  • Save BrainlabsDigital/6a65129be987acea71f2aac28737cc4c to your computer and use it in GitHub Desktop.
Save BrainlabsDigital/6a65129be987acea71f2aac28737cc4c to your computer and use it in GitHub Desktop.
Adds negatives for any search query that doesn't actually *exactly* match an exact match keyword.
/**
*
* Make Exact Match Exact
*
* Adds negatives for any search query that doesn't actually exactly match an exact
* match keyword.
*
* Version: 2.0
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Options
var campaignNameDoesNotContain = [];
// Use this if you want to exclude some campaigns. Case insensitive.
// For example ["Brand"] would ignore any campaigns with 'brand' in the name,
// while ["Brand","Competitor"] would ignore any campaigns with 'brand' or
// 'competitor' in the name.
// Leave as [] to not exclude any campaigns.
var campaignNameContains = [];
// Use this if you only want to look at some campaigns. Case insensitive.
// For example ["Brand"] would only look at campaigns with 'brand' in the name,
// while ["Brand","Generic"] would only look at campaigns with 'brand' or 'generic'
// in the name.
// Leave as [] to include all campaigns.
//Choose whether the negatives are created, or if you just get an email to review
var makeChanges = true;
// These addresses will be emailed when the tool is run, eg "[email protected]"
// If there are multiple addresses then separate them with commas, eg "[email protected], [email protected]"
// Leave as "" to not send any emails
var emailAddresses = "";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var campaigns = {};
var adGroups = {};
var exactKeywords = [];
var exactGroupIds = {};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Pull a list of all exact match keywords in the account
var campaignIds = getCampaignIds();
var report = AdWordsApp.report(
"SELECT AdGroupId, Id, Criteria " +
"FROM KEYWORDS_PERFORMANCE_REPORT " +
"WHERE Impressions > 0 AND KeywordMatchType = EXACT " +
"AND CampaignId IN [" + campaignIds.join(",") + "] " +
"AND AdGroupStatus IN [ENABLED, PAUSED] " +
"AND Status IN [ENABLED, PAUSED] " +
"DURING LAST_30_DAYS");
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var keywordId = row['Id'];
var adGroupId = row['AdGroupId'];
exactKeywords.push(adGroupId + "#" + keywordId);
exactGroupIds[adGroupId] = true;
if(!adGroups.hasOwnProperty(adGroupId)){
adGroups[adGroupId] = [[], [], []];
}
adGroups[adGroupId][2].push(row['Criteria'].toLowerCase().trim());
}
exactGroupIds = Object.keys(exactGroupIds);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Remove ad groups with non-exact keywords
var nonExactGroupIds = {};
for (var i=0; i<exactGroupIds.length; i+=10000) {
var exactGroupIdsChunk = exactGroupIds.slice(i, i+10000);
var report = AdWordsApp.report(
"SELECT AdGroupId, Id " +
"FROM KEYWORDS_PERFORMANCE_REPORT " +
"WHERE KeywordMatchType != EXACT AND IsNegative = FALSE " +
"AND AdGroupId IN [" + exactGroupIdsChunk.join(",") + "] " +
"AND Status IN [ENABLED, PAUSED] " +
"DURING LAST_30_DAYS");
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var adGroupId = row['AdGroupId'];
nonExactGroupIds[adGroupId] = true;
}
}
var onlyExactGroupIds = [];
for (var i=0; i<exactGroupIds.length; i++) {
if (nonExactGroupIds[exactGroupIds[i]] == undefined) {
onlyExactGroupIds.push(exactGroupIds[i]);
}
}
Logger.log(onlyExactGroupIds.length + " ad groups (with only exact keywords) were found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Pull a list of all exact (close variant) search queries
for (var i=0; i<onlyExactGroupIds.length; i+=10000) {
var onlyExactGroupIdsChunk = onlyExactGroupIds.slice(i, i+10000);
var report = AdWordsApp.report(
"SELECT Query, AdGroupId, CampaignId, KeywordId, KeywordTextMatchingQuery, Impressions, QueryMatchTypeWithVariant, AdGroupName " +
"FROM SEARCH_QUERY_PERFORMANCE_REPORT " +
"WHERE AdGroupId IN [" + onlyExactGroupIdsChunk.join(",") + "] " +
"DURING LAST_30_DAYS");
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var adGroupId = parseInt(row['AdGroupId']);
var campaignId = parseInt(row['CampaignId']);
var keywordId = parseInt(row['KeywordId']);
var searchQuery = row['Query'].toLowerCase().trim();
var keyword = row['KeywordTextMatchingQuery'].toLowerCase().trim();
var matchType = row['QueryMatchTypeWithVariant'].toLowerCase().trim();
if(keyword !== searchQuery && matchType.indexOf("exact (close variant)") !== -1){
if (adGroups[adGroupId][2].indexOf(searchQuery) > -1) {
// This query is a positive keyword in the ad group
// so we don't want to add is as a negative
continue;
}
if(!campaigns.hasOwnProperty(campaignId)){
campaigns[campaignId] = [[], []];
}
campaigns[campaignId][0].push(searchQuery);
campaigns[campaignId][1].push(adGroupId + "#" + keywordId);
if(!adGroups.hasOwnProperty(adGroupId)){
adGroups[adGroupId] = [[], []];
}
adGroups[adGroupId][0].push(searchQuery);
adGroups[adGroupId][1].push(adGroupId + "#" + keywordId);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Parse data correctly
var adGroupIds = [];
var adGroupNegatives = [];
for(var x in adGroups){
adGroupIds.push(parseInt(x));
adGroupNegatives.push([]);
for(var y = 0; y < adGroups[x][0].length; y++){
var keywordId = adGroups[x][1][y];
var keywordText = adGroups[x][0][y];
if(exactKeywords.indexOf(keywordId) !== -1){
adGroupNegatives[adGroupIds.indexOf(parseInt(x))].push(keywordText);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Create the new negative exact keywords
var results = [];
for (var i=0; i<adGroupIds.length; i+=10000) {
var adGroupIdsChunk = adGroupIds.slice(i, i+10000);
var adGroupIterator = AdWordsApp.adGroups()
.withIds(adGroupIdsChunk)
.get();
while(adGroupIterator.hasNext()){
var adGroup = adGroupIterator.next();
var adGroupId = adGroup.getId();
var adGroupName = adGroup.getName();
var adGroupIndex = adGroupIds.indexOf(adGroupId);
var campaignName = adGroup.getCampaign().getName();
for(var j=0; j < adGroupNegatives[adGroupIndex].length; j++){
if (makeChanges) {
adGroup.createNegativeKeyword("[" + adGroupNegatives[adGroupIndex][j] + "]");
}
results.push([campaignName, adGroupName, adGroupNegatives[adGroupIndex][j]]);
}
}
}
if (!makeChanges || AdWordsApp.getExecutionInfo().isPreview()) {
Logger.log(results.length + " new negatives were found.");
} else {
Logger.log(results.length + " new negatives were created.");
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Email the results
if (emailAddresses == "") {
Logger.log("No email addresses given - not sending email.");
} else if(results.length == 0) {
Logger.log("No changes to email.");
} else {
var attachments = [];
var headers = ["Campaign", "Ad Group", "Negative"];
attachments.push(createEscapedCsv([headers].concat(results), "Ad-Group-Negatives.csv"));
if (!makeChanges || AdWordsApp.getExecutionInfo().isPreview()) {
var verb = "would be";
} else {
var verb = "were";
}
var subject = AdWordsApp.currentAccount().getName() + " - Making Exact Match Exact - " + Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
var body = "Please find attached a list of the " + results.length + " negative keywords that " + verb + " added to your account.";
var options = {attachments: attachments};
MailApp.sendEmail(emailAddresses, subject, body, options);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Prepare an array to be made into a CSV
function createEscapedCsv(array, csvName) {
var cells = [];
for (var i=0; i<array.length; i++) {
var row = [];
for (var j=0; j<array[i].length; j++) {
row.push(array[i][j].replace(/"/g,'""'));
}
cells.push('"' + row.join('","') + '"');
}
return Utilities.newBlob("\ufeff" + cells.join("\n"), 'text/csv', csvName);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the IDs of campaigns which match the given options
function getCampaignIds() {
var whereStatement = "";
var whereStatementsArray = [];
var campaignIds = [];
for (var i=0; i<campaignNameDoesNotContain.length; i++) {
whereStatement += "AND CampaignName DOES_NOT_CONTAIN_IGNORE_CASE '" + campaignNameDoesNotContain[i].replace(/"/g,'\\\"') + "' ";
}
if (campaignNameContains.length == 0) {
whereStatementsArray = [whereStatement];
} else {
for (var i=0; i<campaignNameContains.length; i++) {
whereStatementsArray.push(whereStatement + 'AND CampaignName CONTAINS_IGNORE_CASE "' + campaignNameContains[i].replace(/"/g,'\\\"') + '" ');
}
}
for (var i=0; i<whereStatementsArray.length; i++) {
var campaignReport = AdWordsApp.report(
"SELECT CampaignId " +
"FROM CAMPAIGN_PERFORMANCE_REPORT " +
"WHERE CampaignStatus = ENABLED " +
whereStatementsArray[i] +
"DURING LAST_30_DAYS");
var rows = campaignReport.rows();
while (rows.hasNext()) {
var row = rows.next();
campaignIds.push(row['CampaignId']);
}
}
if (campaignIds.length == 0) {
throw("No campaigns found with the given settings.");
}
Logger.log(campaignIds.length + " campaigns were found.");
return campaignIds;
}
@rpmcoding
Copy link

rpmcoding commented Apr 1, 2025

I got several errors running this script, presumably as it was written in 2017. Please find working version below.

/**
*

  • Make Exact Match Exact
  • Adds negatives for any search query that doesn't actually exactly match an exact
  • match keyword. Only runs on ad groups that contain only exact match keywords.
  • Version: 2.4 (Fixed type mismatch for adGroup.getId() vs indexOf check)
  • Google AdWords Script maintained on brainlabsdigital.com

**/

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Options

var campaignNameDoesNotContain = [];
// Use this if you want to exclude some campaigns. Case insensitive.
// For example ["Brand"] would ignore any campaigns with 'brand' in the name,
// while ["Brand","Competitor"] would ignore any campaigns with 'brand' or
// 'competitor' in the name.
// Leave as [] to not exclude any campaigns.

var campaignNameContains = []; // <--- Example: Set back to empty or your desired filter
// Use this if you only want to look at some campaigns. Case insensitive.
// For example ["Brand"] would only look at campaigns with 'brand' in the name,
// while ["Brand","Generic"] would only look at campaigns with 'brand' or 'generic'
// in the name.
// Leave as [] to include all campaigns.

//Choose whether the negatives are created, or if you just get an email to review
var makeChanges = true; // Set to false for a dry run initially after changes

// These addresses will be emailed when the tool is run, eg "[email protected]"
// If there are multiple addresses then separate them with commas, eg "[email protected], [email protected]"
// Leave as "" to not send any emails
var emailAddresses = ""; // Add your email address(es) here

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {

// adGroups stores: adGroupId(string) -> [ potentialNegativeInfos[], triggeringKeywordIds[] (unused), positiveKeywordTexts[] ]
// potentialNegativeInfos is array of { query: "text", trigger: "text" }
var adGroups = {};
var exactKeywords = []; // Stores "adGroupId#keywordId" strings for all exact keywords (used for reference/debugging maybe, not core logic now)
var exactGroupIds = {}; // Stores adGroupIds that contain at least one exact keyword (initially)

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Pull a list of all exact match keywords in the account
var campaignIds = getCampaignIds(); // Returns STRING IDs
if (campaignIds.length === 0) {
Logger.log("No campaigns matched the filters. Exiting.");
return;
}

Logger.log("Fetching exact match keywords for " + campaignIds.length + " campaigns...");
var report = AdWordsApp.report(
"SELECT AdGroupId, Id, Criteria, CampaignId, AdGroupName " +
"FROM KEYWORDS_PERFORMANCE_REPORT " +
"WHERE Impressions > 0 AND KeywordMatchType = EXACT " +
"AND CampaignId IN [" + campaignIds.join(",") + "] " + // Use STRING IDs here
"AND AdGroupStatus IN [ENABLED, PAUSED] " +
"AND Status IN [ENABLED, PAUSED] " +
"DURING LAST_30_DAYS");

var rows = report.rows();
var exactKeywordCount = 0;
while (rows.hasNext()) {
var row = rows.next();
var keywordId = row['Id'];
var adGroupId = row['AdGroupId']; // String ID from report
var keywordText = row['Criteria'].toLowerCase().trim();

exactKeywords.push(adGroupId + "#" + keywordId); // Keep for reference if needed
exactGroupIds[adGroupId] = true; // Mark ad group as having an exact keyword (using STRING ID as key)

if(!adGroups.hasOwnProperty(adGroupId)){
  // Initialize: [potentialNegativeInfos], [triggeringKeywordIds(unused)], [positiveKeywordsTexts]
  adGroups[adGroupId] = [[], [], []];
}
// Store the text of the positive exact match keyword
if (adGroups[adGroupId][2].indexOf(keywordText) === -1) { // Avoid duplicates if keyword appears twice
   adGroups[adGroupId][2].push(keywordText);
}
exactKeywordCount++;

}
Logger.log("Found " + exactKeywordCount + " exact match keywords across " + Object.keys(exactGroupIds).length + " ad groups (initially).");

// Get list of ad group IDs that have exact keywords
var adGroupIdsWithExact = Object.keys(exactGroupIds); // Array of STRING IDs
if (adGroupIdsWithExact.length === 0) {
Logger.log("No ad groups with active exact match keywords found in the specified campaigns. Exiting.");
return;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Identify and remove ad groups that also contain non-exact keywords

Logger.log("Checking " + adGroupIdsWithExact.length + " ad groups for non-exact keywords...");
var nonExactGroupIds = {};
for (var i = 0; i < adGroupIdsWithExact.length; i += 10000) {
var adGroupIdsChunk = adGroupIdsWithExact.slice(i, i + 10000); // Chunk of STRING IDs
var reportNonExact = AdWordsApp.report(
"SELECT AdGroupId " +
"FROM KEYWORDS_PERFORMANCE_REPORT " +
"WHERE KeywordMatchType != EXACT AND IsNegative = FALSE " +
"AND AdGroupId IN [" + adGroupIdsChunk.join(",") + "] " + // Use STRING IDs here
"AND Status IN [ENABLED, PAUSED] " +
"DURING LAST_30_DAYS");

var rowsNonExact = reportNonExact.rows();
while (rowsNonExact.hasNext()) {
  var row = rowsNonExact.next();
  var adGroupId = row['AdGroupId']; // String ID
  nonExactGroupIds[adGroupId] = true; // Use STRING ID as key
}

}

// Filter down to only the ad groups that contain exclusively exact match keywords
var onlyExactGroupIds = []; // Array of STRING IDs
for (var i = 0; i < adGroupIdsWithExact.length; i++) {
var currentAdGroupId = adGroupIdsWithExact[i]; // String
if (nonExactGroupIds[currentAdGroupId] === undefined) {
onlyExactGroupIds.push(currentAdGroupId);
} else {
// Clean up the main adGroups object - remove groups we won't process
delete adGroups[currentAdGroupId];
// Logger.log("Ad Group ID " + currentAdGroupId + " removed because it contains non-exact keywords.");
}
}
Logger.log(onlyExactGroupIds.length + " ad groups contain only exact match keywords.");

if (onlyExactGroupIds.length === 0) {
Logger.log("No ad groups found containing exclusively exact match keywords. No negatives needed based on script logic. Exiting.");
return;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Pull the Search Query Report for the "Exact Only" Ad Groups

Logger.log("Fetching Search Query Report for " + onlyExactGroupIds.length + " ad groups...");
var sqrCloseVariantCount = 0;
for (var i = 0; i < onlyExactGroupIds.length; i += 10000) {
var onlyExactGroupIdsChunk = onlyExactGroupIds.slice(i, i + 10000); // Chunk of STRING IDs
var reportSQR = AdWordsApp.report(
"SELECT Query, AdGroupId, CampaignId, KeywordId, KeywordTextMatchingQuery, QueryMatchTypeWithVariant " +
"FROM SEARCH_QUERY_PERFORMANCE_REPORT " +
"WHERE AdGroupId IN [" + onlyExactGroupIdsChunk.join(",") + "] " + // Use STRING IDs here
"DURING LAST_30_DAYS");

var rowsSQR = reportSQR.rows();
while (rowsSQR.hasNext()) {
  var row = rowsSQR.next();
  var adGroupId = row['AdGroupId']; // String ID from the report
  var searchQuery = row['Query'].toLowerCase().trim();
  var keywordTriggered = row['KeywordTextMatchingQuery'].toLowerCase().trim();
  var matchType = row['QueryMatchTypeWithVariant'].toLowerCase().trim();

  // Check if it's a close variant AND the query doesn't match the keyword text
  if (searchQuery !== keywordTriggered && matchType.indexOf("exact (close variant)") !== -1) {

    // Ensure the ad group exists in our tracked list (using string ID)
    if (!adGroups.hasOwnProperty(adGroupId)) {
        Logger.log("Warning: SQR returned AdGroupId " + adGroupId + " which was not in the final 'onlyExactGroupIds' list or adGroups map. Skipping query: " + searchQuery);
        continue;
    }

    // Check if this search query already exists as a *positive* keyword in the ad group
    if (adGroups[adGroupId][2] && adGroups[adGroupId][2].indexOf(searchQuery) > -1) {
      continue;
    }

    // Store the potential negative query AND the text of the keyword that triggered it
    adGroups[adGroupId][0].push({ query: searchQuery, trigger: keywordTriggered });
    sqrCloseVariantCount++;

  }
}

}
Logger.log("Found " + sqrCloseVariantCount + " potential close variant queries to check against positive keywords.");

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Parse data correctly - Build lists for adding negatives

Logger.log("Parsing data and preparing negatives...");
var adGroupIdsToAddNegativesTo = []; // Will hold NUMERIC AdGroup IDs that need negatives
var negativesToAddByAdGroup = []; // Will hold arrays of negative strings, parallel to adGroupIdsToAddNegativesTo

// Iterate using the STRING keys from the adGroups object
for (var adGroupIdString in adGroups) {
if (!adGroups.hasOwnProperty(adGroupIdString) || onlyExactGroupIds.indexOf(adGroupIdString) === -1 || !adGroups[adGroupIdString][0] || adGroups[adGroupIdString][0].length === 0 ) {
continue;
}

  var currentAdGroupIdNum = parseInt(adGroupIdString, 10); // Convert to NUMBER for the final list
  var potentialNegativeInfos = adGroups[adGroupIdString][0]; // Array of {query, trigger} objects
  var actualNegativesToAdd = [];
  var uniqueNegativesCheck = {};

  var positiveKeywordsInGroup = adGroups[adGroupIdString][2] || [];
  if (positiveKeywordsInGroup.length === 0) {
      Logger.log("Warning: No positive keywords found stored for AdGroup ID " + adGroupIdString + ". Cannot verify triggers. Skipping negative parsing for this group.");
      continue;
  }

  for (var k = 0; k < potentialNegativeInfos.length; k++) {
       var potentialNegativeInfo = potentialNegativeInfos[k];
       var queryText = potentialNegativeInfo.query;
       var triggeringKeywordText = potentialNegativeInfo.trigger;

       // Check if the TEXT reported by SQR as the trigger exists in our list of positive keywords for this group
       if (positiveKeywordsInGroup.indexOf(triggeringKeywordText) !== -1) {
           if (!uniqueNegativesCheck[queryText]) {
               actualNegativesToAdd.push(queryText);
               uniqueNegativesCheck[queryText] = true;
           }
       }
   }

  if (actualNegativesToAdd.length > 0) {
      adGroupIdsToAddNegativesTo.push(currentAdGroupIdNum); // Add NUMERIC ID
      negativesToAddByAdGroup.push(actualNegativesToAdd);
  }

}

Logger.log("Prepared to process " + adGroupIdsToAddNegativesTo.length + " ad groups for negative keyword additions.");
// Logger.log("Data check - adGroupIdsToAddNegativesTo (Numeric): " + JSON.stringify(adGroupIdsToAddNegativesTo)); // Optional debug

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Create the new negative exact keywords

var results = []; // To store [CampaignName, AdGroupName, NegativeKeyword] for reporting
var negativesCreatedCount = 0;
var negativesFailedCount = 0;

if (adGroupIdsToAddNegativesTo.length === 0) {
Logger.log("No ad groups with qualifying close variant queries were found after checking trigger text. No negatives will be added.");
} else {
Logger.log("Starting negative keyword creation process...");
var adGroupIdsToProcess = adGroupIdsToAddNegativesTo.slice(); // List of NUMERIC IDs

  for (var i = 0; i < adGroupIdsToProcess.length; i += 10000) {
      var adGroupIdsChunk = adGroupIdsToProcess.slice(i, i + 10000); // Chunk of NUMERIC IDs
      Logger.log("Processing chunk of " + adGroupIdsChunk.length + " ad groups (IDs starting with: " + adGroupIdsChunk[0] + ")...");

      try {
          // Get iterator using NUMERIC IDs
          var adGroupIterator = AdWordsApp.adGroups()
              .withIds(adGroupIdsChunk)
              .get();

          while (adGroupIterator.hasNext()) {
              var adGroup = adGroupIterator.next();
              var adGroupIdFromIterator = adGroup.getId(); // Get the ID (might be string)
              var adGroupIdNum = parseInt(adGroupIdFromIterator, 10); // <<< Convert to Number immediately
              var adGroupName = adGroup.getName();
              var campaignName = adGroup.getCampaign().getName();
              // Log both original and converted ID for clarity
              // Logger.log("Iterator returned adGroupId: " + adGroupIdFromIterator + " (Type: " + typeof adGroupIdFromIterator + "), Converted to Number: " + adGroupIdNum + ", Name: '" + adGroupName + "'");


              // Find the index in the original list (which contains NUMBERS) using the converted NUMBER
              // Logger.log("Searching for numeric ID " + adGroupIdNum + " in adGroupIdsToAddNegativesTo: " + JSON.stringify(adGroupIdsToAddNegativesTo));
              var adGroupIndex = adGroupIdsToAddNegativesTo.indexOf(adGroupIdNum); // <<< Number vs Number search
              // Logger.log("Result of indexOf: " + adGroupIndex);


              // --- Defensive Check 1: Was the ID found in our list? ---
              if (adGroupIndex === -1) {
                  Logger.log("Error: Ad Group Numeric ID " + adGroupIdNum + " (from Iterator ID " + adGroupIdFromIterator + ") was returned by iterator but could not be found in the processed list 'adGroupIdsToAddNegativesTo'. This indicates an internal script logic error. Skipping.");
                  continue;
              }

              // --- Defensive Check 2: Does the negatives array exist at this index? ---
              var negativesForThisGroup = negativesToAddByAdGroup[adGroupIndex];
              if (negativesForThisGroup === undefined || negativesForThisGroup === null) {
                   Logger.log("Error: No negatives list found (undefined/null) for Ad Group Numeric ID " + adGroupIdNum + " (Name: '" + adGroupName + "') at index " + adGroupIndex + ". Internal script error. Skipping.");
                   continue;
              }

               // --- Defensive Check 3: Is it actually an array? ---
              if (!Array.isArray(negativesForThisGroup)) {
                   Logger.log("Error: Expected an array of negatives for Ad Group Numeric ID " + adGroupIdNum + " (Name: '" + adGroupName + "') at index " + adGroupIndex + ", but found type " + typeof negativesForThisGroup + ". Internal script error. Skipping.");
                   continue;
              }

              // --- Loop through negatives and add them ---
              for (var j = 0; j < negativesForThisGroup.length; j++) {
                  var negativeText = negativesForThisGroup[j];
                  var negativeKeywordText = "[" + negativeText + "]";
                  results.push([campaignName, adGroupName, negativeText]);

                  if (makeChanges && !AdWordsApp.getExecutionInfo().isPreview()) {
                      try {
                          adGroup.createNegativeKeyword(negativeKeywordText);
                          negativesCreatedCount++;
                      } catch (e) {
                          negativesFailedCount++;
                          Logger.log("Error adding negative " + negativeKeywordText + " to Ad Group '" + adGroupName + "' (ID: " + adGroupIdNum + "): " + e);
                          if (e.toString().indexOf("NegativeKeywordConflictError.DUPLICATE_NEGATIVE_KEYWORD") > -1) {
                              Logger.log("--> Note: Negative keyword likely already exists.");
                          }
                      }
                  } else {
                     // Logger.log("Preview/Dry Run: Would add negative " + negativeKeywordText + " to Ad Group '" + adGroupName + "'");
                  }
              } // End loop through negatives
          } // End while adGroupIterator
      } catch (e) {
          Logger.log("Error retrieving or processing ad group chunk (starting index " + i + "): " + e);
      }
  } // End loop through chunks

} // End else block

// Report final counts
if (!makeChanges || AdWordsApp.getExecutionInfo().isPreview()) {
Logger.log(results.length + " new negatives identified based on SQR trigger text matching positive keyword text (Dry Run / Preview Mode - No changes made).");
} else {
Logger.log(negativesCreatedCount + " new negatives were successfully created.");
if (negativesFailedCount > 0) {
Logger.log(negativesFailedCount + " negatives failed to be created (see logs for details).");
}
var expectedProcessed = negativesCreatedCount + negativesFailedCount;
if (makeChanges && !AdWordsApp.getExecutionInfo().isPreview() && results.length !== expectedProcessed) {
Logger.log("Warning: Discrepancy between identified negatives (" + results.length + ") and processed negatives (" + expectedProcessed + ").");
}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Email the results

if (!emailAddresses || emailAddresses.trim() === "") {
Logger.log("No email addresses provided - skipping email report.");
} else if (results.length === 0) {
Logger.log("No negatives were identified or added - skipping email report.");
} else {
Logger.log("Preparing email report...");
var attachments = [];
var headers = ["Campaign", "Ad Group", "Negative Keyword Added (Exact Match)"];
attachments.push(createEscapedCsv([headers].concat(results), "Make-Exact-Match-Exact-Negatives.csv"));

var statusVerb = "";
var changeStatus = "";
if (!makeChanges || AdWordsApp.getExecutionInfo().isPreview()) {
  statusVerb = "were identified";
  changeStatus = "(Preview/Dry Run)";
} else {
  statusVerb = "were processed";
  changeStatus = "(Live Run)";
}
var subjectPrefix = AdWordsApp.currentAccount().getName() + " [" + AdWordsApp.currentAccount().getCustomerId() + "]";
var subject = subjectPrefix + " - Make Exact Match Exact Report " + changeStatus + " - " + Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "yyyy-MM-dd");

var body = "The Make Exact Match Exact script has finished running for account: " + AdWordsApp.currentAccount().getName() + " (" + AdWordsApp.currentAccount().getCustomerId() + ").\n\n";
body += results.length + " close variant search queries " + statusVerb + " to be added as exact match negative keywords.\n";
body += "(These queries triggered ads in 'exact match only' ad groups via close variants, did not match the positive keyword text directly, and the triggering keyword text reported by the SQR matched a known positive keyword in the ad group).\n\n"

if (makeChanges && !AdWordsApp.getExecutionInfo().isPreview()) {
     body += negativesCreatedCount + " negatives were successfully created.\n";
     if (negativesFailedCount > 0) {
         body += negativesFailedCount + " negatives failed creation (check script logs for errors).\n";
     }
} else {
     body += "No changes were made to the account (Dry Run or Preview mode).\n";
}
body += "\nPlease find the detailed list attached.\n\n";
body += "Filters applied:\n";
body += "- Campaign Name Contains: " + (campaignNameContains.length > 0 ? JSON.stringify(campaignNameContains) : "Any") + "\n";
body += "- Campaign Name Does Not Contain: " + (campaignNameDoesNotContain.length > 0 ? JSON.stringify(campaignNameDoesNotContain) : "None") + "\n";

var options = { attachments: attachments };
MailApp.sendEmail(emailAddresses, subject, body, options);
Logger.log("Email report sent to: " + emailAddresses);

}

Logger.log("Script finished.");
} // End main function

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Helper function to prepare an array for CSV export, handling quotes correctly
function createEscapedCsv(data, fileName) {
if (!Array.isArray(data) || data.length === 0) {
return Utilities.newBlob("", 'text/csv', fileName);
}
var csvContent = '';
data.forEach(function(row, index) {
var rowArray = [];
if (Array.isArray(row)) {
row.forEach(function(cell) {
var cellString = String(cell == null ? "" : cell); // Handle null/undefined
if (cellString.includes('"') || cellString.includes(',') || cellString.includes('\n')) {
cellString = '"' + cellString.replace(/"/g, '""') + '"';
}
rowArray.push(cellString);
});
}
csvContent += rowArray.join(',');
if (index < data.length - 1) {
csvContent += '\n';
}
});
return Utilities.newBlob("\ufeff" + csvContent, 'text/csv', fileName);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Helper function to get the IDs of campaigns matching the include/exclude filters
function getCampaignIds() {
var campaignIds = []; // Stores STRING IDs
var whereClauses = ["CampaignStatus = ENABLED"];

campaignNameDoesNotContain.forEach(function(exclude) {
whereClauses.push("CampaignName DOES_NOT_CONTAIN_IGNORE_CASE '" + exclude.replace(/"/g, '\"') + "'");
});

var finalWhereStatements = [];
var baseWhere = whereClauses.join(" AND ");

if (campaignNameContains.length === 0) {
finalWhereStatements.push(baseWhere);
} else {
campaignNameContains.forEach(function(include) {
finalWhereStatements.push(baseWhere + " AND CampaignName CONTAINS_IGNORE_CASE '" + include.replace(/"/g, '\"') + "'");
});
}

Logger.log("Running " + finalWhereStatements.length + " query(ies) to find matching campaigns...");
var uniqueCampaignIds = {};
finalWhereStatements.forEach(function(whereStatement) {
try {
var campaignReport = AdWordsApp.report(
"SELECT CampaignId " +
"FROM CAMPAIGN_PERFORMANCE_REPORT " +
"WHERE " + whereStatement + " " +
"DURING LAST_30_DAYS");

      var rows = campaignReport.rows();
      while (rows.hasNext()) {
          var row = rows.next();
          uniqueCampaignIds[row['CampaignId']] = true; // Store string ID as key
      }
  } catch (e) {
      Logger.log("Error fetching campaigns with WHERE clause: " + whereStatement + " - Error: " + e);
  }

});

campaignIds = Object.keys(uniqueCampaignIds); // Get array of STRING IDs

if (campaignIds.length === 0) {
Logger.log("Warning: No campaigns found matching the specified criteria.");
} else {
Logger.log(campaignIds.length + " unique campaigns found matching the criteria.");
}

// Return array of STRING IDs consistent with report outputs
return campaignIds;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment