Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
2
Indexable
Never
function main() {
  var spreadsheetUrl = 'INSERT_SPREADSHEET_URL_HERE';
  var spreadsheet = SpreadsheetApp.openByUrl(spreadsheetUrl);
  var sheet = spreadsheet.getSheetByName('Sheet2');
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  for (var i = 1; i <= numRows - 1; i++) {
    var row = values[i];
    var customerId = row[0];
    var adGroupId = row[1];
    var adType = row[2];
    var label = row[3];
    var headlines = row.slice(4, 19);
    var descriptions = row.slice(19, 23);
    var path1 = row[23];
    var path2 = row[24];
    var finalUrl = row[25];
    var imageUrl = row[26]; 

    // Check if finalUrl or imageUrl is undefined or empty
    if (!finalUrl || !imageUrl) {
      Logger.log('Row ' + (i + 1) + ': finalUrl or imageUrl is undefined or empty');
      continue; // Skip this row and go to the next one
    }

    // Select the ad group to create the ad in
    var adGroupSelector = AdsApp.adGroups()
        .withIds([adGroupId]);

    var adGroupIterator = adGroupSelector.get();
    if (adGroupIterator.hasNext()) {
      var adGroup = adGroupIterator.next();

      // Prepare the headlines and descriptions
      var responsiveSearchAdHeadlines = headlines.map(function(headline) {
        return {text: headline};
      });

      var responsiveSearchAdDescriptions = descriptions.map(function(description) {
        return {text: description};
      });

      // Create the media file for the image
      var mediaFile = AdsApp.adMedia().newImageBuilder()
          .withName('Image for Ad Group ' + adGroupId)
          .withUrl(imageUrl)
          .build();

      // Create the responsive search ad builder
      var adBuilder = adGroup.newAd().responsiveSearchAdBuilder()
          .withHeadlines(responsiveSearchAdHeadlines)
          .withDescriptions(responsiveSearchAdDescriptions)
          .withFinalUrl(finalUrl)
          .withImage(mediaFile);

      // Add path1 and path2 if they are not empty
      if (path1) {
        adBuilder.withPath1(path1);
      }
      if (path2) {
        adBuilder.withPath2(path2);
      }

      // Build the ad
      adBuilder.build();
    }
  }
}