Skip to content

Instantly share code, notes, and snippets.

@kaugesaar
Created October 3, 2017 11:35
Show Gist options
  • Save kaugesaar/4bac66c455aa553405f53425fe015125 to your computer and use it in GitHub Desktop.
Save kaugesaar/4bac66c455aa553405f53425fe015125 to your computer and use it in GitHub Desktop.

Control your campaign budgets with labels

Have this script run hourly and it will check the all-time cost of a campaign and pause those which exceed your set limit. To set a limit to campaign, apply a label which start with budget:: followed by the amount which it can spend in total.

Example, budget::2500 – and the script will pause the campaign as soon as* it has spent 2500.

*it's still limited by adwords scripts only being able to run hourly, which theoraticly could make a campaign spend more than the limit you set.

function main() {
var labels = getAllBudgetLabels();
parseCampaignBudgets(labels,'videoCampaigns')
parseCampaignBudgets(labels,'campaigns')
parseCampaignBudgets(labels,'shoppingCampaigns')
}
function getMaxSpendFromLabel(label) {
return parseInt(label.getName().replace('budget::',''));
}
function getAllBudgetLabels() {
var labels = [];
var labelsIterator = AdWordsApp.labels()
.withCondition('Name STARTS_WITH "budget::"')
.get();
while(labelsIterator.hasNext()) {
labels.push(labelsIterator.next().getName());
}
return labels;
}
function parseCampaignBudgets(labelNames, functionName) {
var campaignsIterator = AdWordsApp[functionName]()
.withCondition("LabelNames CONTAINS_ANY ['"+ labelNames.join("','") +"']")
.withCondition('Status = ENABLED')
.get();
while(campaignsIterator.hasNext()) {
var campaign = campaignsIterator.next();
var campaignCost = campaign.getStatsFor('ALL_TIME').getCost();
var campaignBudget = getMaxSpendFromLabel(campaign.labels()
.withCondition('Name STARTS_WITH "budget::"')
.get().next());
if(campaignCost >= campaignBudget) {
Logger.log('%s: has spent %s and have a total budget of %s, pausing campaign!',
campaign.getName(), campaignCost, campaignBudget)
campaign.pause();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment