-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduplicate-ad-detector.js
More file actions
310 lines (252 loc) · 9.67 KB
/
duplicate-ad-detector.js
File metadata and controls
310 lines (252 loc) · 9.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// ID: df4b721f0e7a3713d6f9fa5165e9a4ad
/**
*
* Duplicate Ad Detector
* This script will find ads with identical text and URLs, and label
* one to keep and the rest to pause according to performance.
*
* Version: 1.0
* Google AdWords Script maintained by brainlabsdigital.com
*
*/
var metric = 'Ctr';
// Select the metric which will determine which duplicate ad will be kept.
// Choose from "Ctr", "Clicks", "Impressions", "Cost", "Conversions", "AverageCpc"
var campaignNameDoesNotContain = [];
// Use this if you want to exclude some campaigns.
// For example ["Display"] would ignore any campaigns with 'Display' in the name,
// while ["Display","Shopping"] would ignore any campaigns with 'Display' or
// 'Shopping' in the name.
// Leave as [] to not exclude any campaigns.
var campaignNameContains = [];
// Use this if you only want to look at some campaigns.
// 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.
var ignorePausedCampaigns = true;
// Set this to true to only look at currently active campaigns.
// Set to false to also include campaigns that are currently paused.
var checkUrl = true;
// Set this to true to include the URL as part of the ad text - ads are only
// treated as duplicates if they have the same ad copy and final URL.
// Set this to false to treat ads as duplicates if they have the same copy
// but different landing pages.
var caseSensitive = false;
// If this is set to true, then only ads with the same capitalisation will
// count as duplicates.
// If this is false, ad text comparison will be case insensitive.
var keepLabel = 'Duplicate Ad: Enable';
// Label one ad from each duplicate group
var pauseLabel = 'Duplicate Ad: Pause';
// Label all ads which don't have the best statistic from selected
function main() {
var campaignIds = getCampaignIds();
// Create labels
var keepLabelId = getOrCreateLabelId(keepLabel);
var pauseLabelId = getOrCreateLabelId(pauseLabel);
// Metric validation
var allowedMetrics = ['Ctr', 'Clicks', 'Impressions', 'Cost', 'Conversions', 'AverageCpc'];
metric = validateMetricName(metric, allowedMetrics);
// Record the ads
var adsByAdGroup = getAds(campaignIds, keepLabelId, pauseLabelId, metric);
// Find and label the duplicates
findDuplicates(adsByAdGroup, keepLabel, pauseLabel);
Logger.log('Finished.');
}
// Get the IDs of campaigns which match the given options
function getCampaignIds() {
var whereStatement = 'WHERE ';
var whereStatementsArray = [];
var campaignIds = [];
if (ignorePausedCampaigns) {
whereStatement += 'CampaignStatus = ENABLED ';
} else {
whereStatement += "CampaignStatus IN ['ENABLED','PAUSED'] ";
}
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 '
+ 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 found');
return campaignIds;
}
// Create the label if it doesn't exist, and return its ID.
// (Returns a dummy ID if the label does not exist and this is a preview run,
// because we can't create or apply the label)
function getOrCreateLabelId(labelName) {
var labels = AdWordsApp.labels().withCondition("Name = '" + labelName + "'").get();
if (!labels.hasNext()) {
AdWordsApp.createLabel(labelName);
labels = AdWordsApp.labels().withCondition("Name = '" + labelName + "'").get();
}
if (AdWordsApp.getExecutionInfo().isPreview() && !labels.hasNext()) {
var labelId = 0;
} else {
var labelId = labels.next().getId();
}
return labelId;
}
// Verify that a metric name is valid, and return it with the correct capitalisation.
function validateMetricName(metric, allowedMetrics) {
var allowedMetrics_lowerCase = allowedMetrics.map(function (str) {
return str.toLowerCase();
});
var metricIndex = allowedMetrics_lowerCase.indexOf(metric.toLowerCase().replace(' ', '').trim());
if (metricIndex === -1) {
throw "Metric '" + metric + "' not recognised, please set to one from '" + allowedMetrics.join("', '") + "'.";
}
return allowedMetrics[metricIndex];
}
// Get the text and the relevant stat for all text ads and ETAs
// in the given campaigns.
// Returns the ads, grouped by their ad group ID.
function getAds(campaignIds, keepLabelId, pauseLabelId, metric) {
// Construct AWQL report query and generate report
var query = 'SELECT Id, AdGroupId, Headline, Description1, Description2, DisplayUrl, CreativeFinalUrls, HeadlinePart1, HeadlinePart2, Description, Path1, Path2, ' + metric + ' '
+ 'FROM AD_PERFORMANCE_REPORT '
+ 'WHERE AdType IN [TEXT_AD, EXPANDED_TEXT_AD] '
+ 'AND Status = ENABLED '
+ 'AND Labels CONTAINS_NONE [' + keepLabelId + ',' + pauseLabelId + '] '
+ 'AND CampaignId IN [' + campaignIds.join(',') + '] '
+ 'DURING LAST_30_DAYS';
var report = AdWordsApp.report(query);
// Poll report rows
var adsByAdGroup = {};
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var metricStat = parseFloat(row[metric].replace(/,/g, ''));
if (metric.toLowerCase() === 'AverageCpc'.toLowerCase()) {
if (metricStat > 0) {
metricStat = 1 / metricStat;
}
}
var stats = {
metric: metricStat
};
var groupId = row.AdGroupId;
if (typeof (adsByAdGroup[groupId]) === 'undefined') {
adsByAdGroup[groupId] = [];
}
var ad = {};
if (checkUrl) {
var finalUrl = row.CreativeFinalUrls.toLowerCase();
} else {
var finalUrl = '';
}
if (row.AdType == 'Text ad') {
ad.Text = row.Headline + '#' + row.Description1 + '#' + row.Description2 + '#' + row.DisplayUrl + '#' + finalUrl;
} else {
ad.Text = row.HeadlinePart1 + '#' + row.HeadlinePart2 + '#' + row.Description + '#' + row.Path1 + '#' + row.Path2 + '#' + finalUrl;
}
if (!caseSensitive) {
ad.Text = ad.Text.toLowerCase();
}
ad.AdId = row.Id;
ad.AdGroupId = row.AdGroupId;
ad.Id = [row.AdGroupId, row.Id];
ad.Stats = stats;
adsByAdGroup[groupId].push(ad);
}
return adsByAdGroup;
}
// Finds duplicate ads
function findDuplicates(adsByAdGroup, keepLabel, pauseLabel) {
var ids = Object.keys(adsByAdGroup);
Logger.log('Found ads in ' + ids.length + ' ad groups');
for (var i = 0; i < ids.length; i += 1000) {
if ((i + 1) % 10000 == 0) {
Logger.log('Checking ad group ' + (i + 1) + ' of ' + ids.length);
}
var duplicateAds = {};
for (var j = i; j < i + 100 && j < ids.length; j++) {
var id = ids[j];
var currentGroupsAds = adsByAdGroup[id];
var adArray = [];
for (var ad in currentGroupsAds) {
adArray.push(currentGroupsAds[ad].Text);
}
for (var ad in currentGroupsAds) {
var adText = currentGroupsAds[ad].Text;
var firstIndex = adArray.indexOf(adText);
var lastIndex = adArray.lastIndexOf(adText);
// push the dupes into dupe groups
if (firstIndex !== lastIndex) {
if (typeof (duplicateAds[id]) === 'undefined') {
duplicateAds[id] = {};
}
if (typeof (duplicateAds[id][adText]) === 'undefined') {
duplicateAds[id][adText] = [];
}
duplicateAds[id][adText].push(currentGroupsAds[ad]);
}
}
}
pickBestAdAndLabel(duplicateAds, keepLabel, pauseLabel);
}
}
// Finds the best ad, according to the user defined metric
// then labels accordingly
function pickBestAdAndLabel(duplicateAds, keepLabel, pauseLabel) {
var idsForPauseLabel = [];
var idsForKeepLabel = [];
for (var id in duplicateAds) {
for (var adText in duplicateAds[id]) {
// cycle through each group to pick best of the bunch
var maxmetric = -1;
var bestAd = [];
for (var ad in duplicateAds[id][adText]) {
if (parseFloat(duplicateAds[id][adText][ad].Stats.metric) > maxmetric) {
maxmetric = duplicateAds[id][adText][ad].Stats.metric;
bestAd[0] = duplicateAds[id][adText][ad];
}
}
var indexOfBest = duplicateAds[id][adText].indexOf(bestAd[0]);
duplicateAds[id][adText].splice(indexOfBest, 1);
idsForKeepLabel.push(bestAd[0].Id);
for (ad in duplicateAds[id][adText]) {
idsForPauseLabel.push(duplicateAds[id][adText][ad].Id);
}
}
}
// label all groups with pause/unpause labels
if (idsForKeepLabel.length + idsForPauseLabel.length > 0) {
applyLabelsToAds(idsForKeepLabel, keepLabel);
applyLabelsToAds(idsForPauseLabel, pauseLabel);
}
}
// Applies a label to all ads with the given ids
function applyLabelsToAds(ids, labelName) {
for (var i = 0; i < ids.length; i += 5000) {
var iterator = AdWordsApp.ads()
.withIds(ids.slice(i, i + 5000))
.get();
while (iterator.hasNext()) {
var ad = iterator.next();
ad.applyLabel(labelName);
}
}
}