Sunday, March 17, 2013

Issues With The New Reporting API

Like many of you, I've been trying to sink my teeth into the new reporting functionality that was recently added to the AdWords scripts late last week.  Unfortunately, I've been getting errors even when I use the sample code given in the API. If anyone has been having the same issues, there is a thread on the forums where you can wait for the AdWords Scripts team to resolve the issue.  As soon as it is resolved, I'll start posting some sample code.  I have been working on an auto trafficking of user queries script that is pretty cool.

Thanks,
Russ

Monday, March 11, 2013

Merge Multiple Campaigns Together For Enhanced Campaigns Migration

UPDATE 2013-04-14: Check Merge Labels from Multiple Campaigns for some help on merging labels.

Everyone is getting ready for Enhanced Campaigns and for a lot of people, that means finding an easy way to merge multiple campaigns into a single campaign. You may have a campaign for desktop traffic and one for tablet, or maybe one for each major mobile platform.

Well the beauty and the pain of Enhanced Campaigns is that you can do more with less. I haven't found a great way to easily merge multiple campaigns into one, so I made my own. All you need to do is specify a destination campaign where you want all the keywords, adgroups, and ads to end up and the set of campaigns you want to copy from. This script will pause any keyword and ad it manages to move over so you can see results and make sure everything is set up properly before deleting the old campaigns.

Thanks,
Russ

//-----------------------------------
// Merge Multiple Campaigns Together
// Created By: Russ Savage
// FreeAdWordsScripts.com
//-----------------------------------
function main() {
  var DESTINATION_CAMPAIGN_NAME = "dest_camp_name";
  var ORIGIN_CAMPAIGN_NAMES = ["to_merge_camp_name_1","to_merge_camp_name_2"/*,...*/];
  var DEFAULT_KW_BID = 0.01; //used in case we can't get the origin kw bid
  
  //build a list of adgroups in the original 
  var dest_adgroups = [];
  var ag_iter = AdWordsApp.adGroups()
    .withCondition("CampaignName = '"+DESTINATION_CAMPAIGN_NAME+"'")
    .get();
  
  while(ag_iter.hasNext()) {
    dest_adgroups.push(ag_iter.next());
  }
  
  var dest_camp;
  if(dest_adgroups.length > 0) {
     dest_camp = dest_adgroups[0].getCampaign();
  }
  
  for(var i in ORIGIN_CAMPAIGN_NAMES) {
    var camp_name = ORIGIN_CAMPAIGN_NAMES[i];
    var kw_iter = AdWordsApp.keywords()
      .withCondition("CampaignName = '"+camp_name+"'")
      .get();
    while(kw_iter.hasNext()) {
      var kw = kw_iter.next();
      var dest_adgroup = _find_adgroup(dest_adgroups,kw.getAdGroup());
      if(!dest_adgroup) {
        dest_adgroup = dest_camp.newAdGroupBuilder()
          .withName(kw.getAdGroup().getName())
          .withStatus((kw.getAdGroup().isPaused()) ? "PAUSED" : "ENABLED")
          .withKeywordMaxCpc(kw.getAdGroup().getKeywordMaxCpc())
          .create();
        dest_adgroups.push(dest_adgroup);
        //now we move all the ads over
        var ad_iter = kw.getAdGroup().ads().get();
        while(ad_iter.hasNext()) {
          var ad = ad_iter.next();
          dest_adgroup.createTextAd(
            ad.getHeadline(),
            ad.getDescription1(),
            ad.getDescription2(),
            ad.getDisplayUrl(),
            ad.getDestinationUrl(),
            { isMobilePreferred : ad.isMobilePreferred() }
          );
          ad.pause();
        }
      }
      var max_cpc = kw.getMaxCpc() || DEFAULT_KW_BID;
      var dest_url = kw.getDestinationUrl() || "";
      var kw_text = kw.getText();
      dest_adgroup.createKeyword(kw_text,max_cpc,dest_url);

      kw.pause();
    }
  }

  function _find_adgroup(ag_list,ag) {
    for(var i in ag_list) {
      if(ag_list[i].getName() == ag.getName()) {
        return ag_list[i];
      }
    }
    return null;
  }
}

Sunday, March 10, 2013

Manage Ads Based on Airport Delays

There are tons of APIs out on the internet today. Any of these can be incorporated into your AdWords scripts to automate some of your account management.

The script below uses the Airport Status Service from FAA.gov to enable and pause ads when there is a delay at a major airport. This would be useful for any business that is near an airport that may benefit from delays such as restaurants, bars, or hotels. Your ads could say things like:



You can add or remove airport codes from the list at the top. All you need to do is tag your ads with the label [airport_code]_delay ("ORD_delay","ATL_delay").

What other dynamic data could you use to optimize your ads? Movie times? Sports games? Let me know in the comments below and I'll see what I can come up with.

Thanks,
Russ

/*********************************************
* Pause/Enable Ads Based On Airport Delays
* Version 1.1
* ChangeLog v1.1 
*  - Added ability to completely pause non-delay ads
* Created By: Russ Savage
* FreeAdWordsScripts.com
*********************************************/
// For this to work, you need to add a label to all
// the ads for each airport.  For example, PIT_normal
// or SFO_normal
var PAUSE_NORMAL_ADS_DURING_DELAY = false;
var DELAY_SUFFIX = '_delay'; //the suffix on the label for delayed ads
var NORMAL_SUFFIX = '_normal'; //the suffix on the label for normal ads

var AIR_CODES = ["ATL","ANC","AUS","BWI","BOS","CLT","MDW","ORD","CVG","CLE",
                 "CMH","DFW","DEN","DTW","FLL","RSW","BDL","HNL","IAH","HOU",
                 "IND","MCI","LAS","LAX","MEM","MIA","MSP","BNA","MSY","JFK",
                 "LGA","EWR","OAK","ONT","MCO","PHL","PHX","PIT","PDX","RDU",
                 "SMF","SLC","SAT","SAN","SFO","SJC","SNA","SEA","STL","TPA",
                 "IAD","DCA"];

function main() {
  var faaUrl = "http://services.faa.gov/airport/status/";
  var args = "?format=application/json";
  for(var i in AIR_CODES) {
    try{
      var resp = UrlFetchApp.fetch(faaUrl + AIR_CODES[i] + args);
      if( resp.getResponseCode() == 200 ) {
        var json = Utilities.jsonParse(resp.getContentText());
        if(json.delay == "false") {
          Logger.log("No delays at "+json.IATA+". Pausing delay ads if any are running.");
          turnOffDelayAds(json.IATA);
          if(PAUSE_NORMAL_ADS_DURING_DELAY) {
            turnOnNonDelayAds(json.IATA);
          }
        } else {
          Logger.log("Delays in "+json.IATA+" Reason: "+json.status.reason);
          Logger.log("Turning on delay ads if there are any.");
          turnOnDelayAds(json.IATA);
          if(PAUSE_NORMAL_ADS_DURING_DELAY) {
            turnOffNonDelayAds(json.IATA);
          }
        }
      }
    }
    catch(e) {
      Logger.log("Error: " + e.message);
    }
  }
}

function turnOffDelayAds(airportCode) {
  var labelName = airportCode + DELAY_SUFFIX;
  var adIter = AdWordsApp.ads()
    .withCondition("LabelNames CONTAINS_ANY ['"+labelName+"']")
    .withCondition("CampaignStatus = ENABLED")
    .withCondition("AdGroupStatus = ENABLED")
    .withCondition("Status = ENABLED")
    .get();
  while(adIter.hasNext()) {
    adIter.next().pause();
  }
}

function turnOffNonDelayAds(airportCode) {
  var labelName = airportCode + NORMAL_SUFFIX;
  var adIter = AdWordsApp.ads()
    .withCondition("LabelNames CONTAINS_ANY ['"+labelName+"']")
    .withCondition("CampaignStatus = ENABLED")
    .withCondition("AdGroupStatus = ENABLED")
    .withCondition("Status = ENABLED")
    .get();
  while(adIter.hasNext()) {
    adIter.next().pause();
  }
}

function turnOnDelayAds(airportCode) {
  var labelName = airportCode + DELAY_SUFFIX;
  var adIter = AdWordsApp.ads()
    .withCondition("LabelNames CONTAINS_ANY ['"+labelName+"']")
    .withCondition("CampaignStatus = ENABLED")
    .withCondition("AdGroupStatus = ENABLED")
    .withCondition("Status = PAUSED")
    .get();
  while(adIter.hasNext()) {
    adIter.next().enable();
  }
}

function turnOnNonDelayAds(airportCode) {
  var labelName = airportCode + NORMAL_SUFFIX;
  var adIter = AdWordsApp.ads()
    .withCondition("LabelNames CONTAINS_ANY ['"+labelName+"']")
    .withCondition("CampaignStatus = ENABLED")
    .withCondition("AdGroupStatus = ENABLED")
    .withCondition("Status = PAUSED")
    .get();
  while(adIter.hasNext()) {
    adIter.next().enable();
  }
}

Monday, March 4, 2013

Fixing Capitalization Errors in Your Ads

One of the issues that marketers face when they have systems for automatically building creatives from feeds is quality control. I recently ran into an issue where I created around 1,000 new ads where the city name was IN ALL CAPS. Google of course doesn't like that much and I didn't like the idea of having to manually update 1,000 ads, so I put together the following script.

The script runs through your account for all of the disapproved ads and tries to find ones with words in ALL CAPS. I'm not sure what Google's limit on caps is, but in the script below, it looks for anything with 3 or more capital letters in a row. Then it replaces them, creates a new ad, and if it was successful, deletes the old ad.

I ran into some trouble trying to identify the reasons the ads were disapproved. It is not yet available in the API, but it has been requested. The other issue was that sometimes, the new ad you create will fail, which will cause you to delete the old one and not create a new one. I solved that one by counting the ads in the adgroup before and after I created the new ad in order to make sure my ad had been created. Again, I posted the feature request in the adwords scripting forums.

Thanks,
Russ

//-----------------------------------
// Fix Ads with EXCESSIVE CAPITALIZATION
// Created By: Russ Savage
// FreeAdWordsScripts.com
//-----------------------------------
function main() {
  var find_caps = /[A-Z]{3,}/g;
  var SEP = '~~@~~'; // this needs to be something you would never put in your ads.
  var ad_iter = AdWordsApp.ads().withCondition("ApprovalStatus = 'DISAPPROVED'").get();
  
  while(ad_iter.hasNext()) {
    var ad = ad_iter.next();
    var old_ad_cnt = get_ad_count(ad.getAdGroup());
    var old_ad_str = [ad.getHeadline(),ad.getDescription1(),ad.getDescription2(),ad.getDisplayUrl()].join(SEP);
    var new_ad_str = old_ad_str;
    Logger.log("Before:"+old_ad_str);
    var m = "";
    while((m = find_caps.exec(new_ad_str)) != null) {
      new_ad_str = replace_all(new_ad_str,m[0],init_cap(m[0]),false);
    }
    Logger.log("After:"+new_ad_str);
    if(old_ad_str != new_ad_str) {
      var [new_headline,new_desc1,new_desc2,new_disp_url] = new_ad_str.split(SEP);
      ad.getAdGroup().createTextAd(new_headline, new_desc1, new_desc2, new_disp_url, ad.getDestinationUrl());
      var new_ad_cnt = get_ad_count(ad.getAdGroup());
      if(new_ad_cnt == (old_ad_cnt+1)) {
        ad.remove();
      }
    } else {
      Logger.log("Skipping because no changes were made."); 
    }
  }
  
  function init_cap(s) {
    return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
  }
  
  // This function was adapted from: http://dumpsite.com/forum/index.php?topic=4.msg8#msg8 
  function replace_all(original,str1, str2, ignore) {
    return original.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
  }
  
  function get_ad_count(ad_group) {
    var ad_iter = ad_group.ads().get();
    var new_ad_cnt = 0;
    while(ad_iter.hasNext()) {
      ad_iter.next();
      new_ad_cnt++;
    }
    return new_ad_cnt;
  }
}