-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPauseKeywordsByKPIs
463 lines (359 loc) · 15.5 KB
/
PauseKeywordsByKPIs
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/**
* This script pause keywords that matches with some KPIs and Labels conditions for the chosen period of time
*
* KPIs available for Keywords filtering:
*
* Keyword Match Types (Broad, Phrase and Exact)
* Minimum Quality Score | Maximum Quality Score | Keywords with NULL Quality Score
* Minimum Impressions | Maximum Impressions
* Minimum Clicks | Maximum Clicks
* Minimum Conversions | Maximum Conversions
* Minimum Cost | Maximum Cost
* Minimum Cost per Conversion | Maximum Cost per Conversion
* Minimum Average Position | Maximum Average Position
* Minimum Conversion rate | Maximum Conversion rate
* Minimum CTR | Maximum CTR
*
* Filtering Labels available:
*
* mccLabelText | Accounts filtering by this Label text
* campaignLabelText | Campaigns filtering by this Label text
* adGroupLabelText | adGroups filtering by this Label text
* keywordLabelText | keywords filtering by this Label text
*
* You can receive script execution results by email putting your email at RECIPIENT_EMAIL variable
*
* This script can be executed at MCC level and Account level also changing the value of mccLevelScript variable
*
* Last version available in: https://github.com/AlbertoEstevesC/AdWords-Scripts/blob/master/PauseKeywordsByKPIs
*
* SPANISH explanation: https://www.albertoestevescorreia.com/adwords-script-pausar-keywords-en-funcion-de-kpis/
*
* @Author: Alberto Esteves Correia
* www.albertoestevescorreia.com
**/
// ---------------- GLOBAL VARIABLES ---------------------------
var mccLevelScript = true; // "true" value for MCC level script execution // "false" value for account level script execution
var RECIPIENT_EMAIL = "INSERT_YOUR_EMAIL_HERE"; // Enter an email if you want to receive script changes notifications
var timePeriod = 'ALL_TIME'; // Period of time to analyze. You can choose another value according to https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_keywordselector#forDateRange_1
// Maximun and Minimum filtering KPIs values // DON'T change KPIs values if you don't want to filter by them
var keywordMatchTypes = ' [BROAD, PHRASE, EXACT] '; // Keyword Matches. Keep ONLY the matches you want to filter
var qualityScoreNull = false; // "true" value for including keywords without QS // "false" value for excluding them
// Integer values // NO decimals
var qualityScoreMin = null;
var qualityScoreMax = null;
var impressionsMin = null;
var impressionsMax = null;
var clicksMin = null;
var clicksMax = null;
var conversionsMin = null;
var conversionsMax = null;
var costMin = null;
var costMax = null;
// Number values with decimals allowed (if you want)
var cpaMin = null;
var cpaMax = null;
var avgPositionMin = null;
var avgPositionMax = null;
// Percentage values // 0% = 0.00, 1% = 0.01, 4,5% = 0.045, 10% = 0.10, 100% = 1.00, etc.
var conversionRateMin = null;
var conversionRateMax = null;
var ctrMin = null;
var ctrMax = null;
// FILTERING LABELS // If you don't want to filter by any label, DON'T make any change in its text // 'no label' = NO filtering
var mccLabelText = 'no label'; // Filter AdWords accounts which have this MCC Account label
var campaignLabelText = 'no label'; // Filter AdWords campaigns which have this campaign label
var adGroupLabelText = 'no label'; // Filter AdWords adGroups which have this adGroup label
var keywordLabelText = 'no label'; // Filter AdWords keywords which have this keyword label
// Auxiliary Variables
var queryQs = "";
var query = 'KeywordMatchType IN '+keywordMatchTypes;
var scriptLabel = "botScript did it"; // Script will add this label to the keywords paused by it // If label doesn't exist, the script will create it
var campaignLabelId, adGroupLabelId, keywordLabelId;
var subject = "Results from Pause Keywords Script execution";
var body = "RESULTS from Pause Keywords Script execution: \n";
var subject_error = "ERROR during Script execution";
// ------------------------------------------------------------------------------------------------------------
function run (){
// ---------------------------- Getting labels IDs -----------------------------
var labels = AdWordsApp.labels().get();
var labelAux, labelNameAux;
var accountName = AdWordsApp.currentAccount().getName();
//Logger.log("Cuenta: " + accountName);
body = body + "NAME: " + accountName + "\n\n";
campaignLabelId = null;
adGroupLabelId = null;
keywordLabelId = null;
while (labels.hasNext()){
labelAux = labels.next();
labelNameAux = labelAux.getName();
if (labelNameAux == campaignLabelText) {
campaignLabelId = labelAux.getId();
}
if (labelNameAux == adGroupLabelText) {
adGroupLabelId = labelAux.getId();
}
if (labelNameAux == keywordLabelText) {
keywordLabelId = labelAux.getId();
}
}
if ((campaignLabelId == null) && (campaignLabelText != 'no label')) {
body = body + "campaignLabelText Label doesn't exist in the account: " + accountName + "\n";
body = body + "Paused Keywords: 0 \n";
return false;
}
if ((adGroupLabelId == null) && (adGroupLabelText != 'no label')) {
body = body + "adGroupLabelText Label doesn't exist in the account: " + accountName + "\n";
body = body + "Paused Keywords: 0 \n";
return false;
}
if ((keywordLabelId == null) && (keywordLabelText != 'no label')) {
body = body + "keywordLabelText Label doesn't exist in the account: " + accountName + "\n";
body = body + "Paused Keywords: 0 \n";
return false;
}
// ------------------------------- Getting filtered campaigns -------------------------------------
var campaignIterator;
var campaignIds = [];
var campaignId;
if (campaignLabelId != null) {
campaignIterator = AdWordsApp.campaigns()
.withCondition("LabelIds CONTAINS_ANY ["+campaignLabelId+"] ")
.orderBy('CampaignId')
.get();
if (!campaignIterator.hasNext()){
body = body + "campaignLabelText exists but is not applied to any campaign for this account \n";
body = body + "Paused Keywords: 0 \n";
return false;
}
} else { // no campaignLabel filtering
campaignIterator = AdWordsApp.campaigns()
.orderBy('CampaignId')
.get();
}
while (campaignIterator.hasNext()){
campaignId = campaignIterator.next().getId();
campaignIds.push(campaignId);
}
// ------------------------------- Getting filtered adGroups -------------------------------------
var adGroupIterator;
var adGroupIds = [];
var adGroupId;
if (adGroupLabelId != null) {
adGroupIterator = AdWordsApp.adGroups().withCondition("LabelIds CONTAINS_ANY [" + adGroupLabelId +"]")
.withCondition("CampaignId IN [" + campaignIds + "]")
.orderBy('AdGroupId')
.get();
if (!adGroupIterator.hasNext()) {
body = body + "adGroupLabelText exists but is not applied to any adGroup for this account \n";
body = body + "Paused Keywords: 0 \n";
return false;
}
} else { // no adGroupLabel filtering
adGroupIterator = AdWordsApp.adGroups().withCondition("CampaignId IN [" + campaignIds + "]")
.orderBy('AdGroupId')
.get();
}
while (adGroupIterator.hasNext()){
adGroupId = adGroupIterator.next().getId();
adGroupIds.push(adGroupId);
}
// ------------------------------- Getting filtered keywords -------------------------------------
var keywordIterator, keywordIteratorAux;
var keywordIds = [];
var keywordId;
var adGroupId;
if (keywordLabelId != null) {
keywordIterator = AdWordsApp.keywords()
.withCondition("LabelIds CONTAINS_ANY [" + keywordLabelId + "] ")
.withCondition("AdGroupId IN [" + adGroupIds + "]")
.withCondition(query + queryQs)
.forDateRange(timePeriod)
.orderBy('Id')
.get();
if (qualityScoreNull) {
keywordIteratorAux = AdWordsApp.keywords()
.withCondition("LabelIds CONTAINS_ANY [" + keywordLabelId + "] ")
.withCondition("AdGroupId IN [" + adGroupIds + "]")
.withCondition(query + " AND HasQualityScore = 'FALSE' ")
.forDateRange(timePeriod)
.orderBy('Id')
.get();
}
if ((!keywordIterator.hasNext()) && (!qualityScoreNull || !keywordIteratorAux.hasNext())) {
body = body + "keywordLabelText exists but is not applied to any filtered keyword for this account \n";
body = body + "Paused Keywords: 0 \n";
return false;
}
} else { // no keywordLabel filtering
keywordIterator = AdWordsApp.keywords()
.withCondition("AdGroupId IN [" + adGroupIds + "] ")
.withCondition(query + queryQs)
.forDateRange(timePeriod)
.orderBy('Id')
.get();
if (qualityScoreNull) {
keywordIteratorAux = AdWordsApp.keywords()
.withCondition("LabelIds CONTAINS_ANY [" + keywordLabelId + "] ")
.withCondition("AdGroupId IN [" + adGroupIds + "]")
.withCondition(query + " AND HasQualityScore = 'FALSE' ")
.forDateRange(timePeriod)
.orderBy('Id')
.get();
}
}
// ------------------------------- Checking script label -------------------------------------
var label = AdWordsApp.labels().withCondition("LabelName = '"+ scriptLabel +"'").get();
if (!label.hasNext()) {
AdWordsApp.createLabel(scriptLabel, "Label created by botScript", "#FF3300");
body = body + "Script Label '" + scriptLabel + "' didn't exist and was created in account: " + accountName + "\n";
} else {
body = body + "Script Label '" + scriptLabel + "' was already created in account: " + accountName + "\n";
}
// ------------------------------- Pausing filtered keywords -------------------------------------
var keyword;
var i = 0;
while (keywordIterator.hasNext()) {
keyword = keywordIterator.next();
// Logger.log("Keyword: " + keyword.getText());
keyword.pause();
keyword.applyLabel(scriptLabel);
i++;
}
if (qualityScoreNull) {
while (keywordIteratorAux.hasNext()) {
keyword = keywordIteratorAux.next();
// Logger.log("Keyword: " + keyword.getText());
keyword.pause();
keyword.applyLabel(scriptLabel);
i++;
}
}
body = body + "Paused Keywords: " + i + "\n";
return true;
} // End of run function
function buildQuery (){
if (impressionsMin != null){
query = query + ' AND Impressions >= ' + impressionsMin;
}
if (impressionsMax != null){
query = query + ' AND Impressions <= ' + impressionsMax;
}
if (clicksMin != null){
query = query + ' AND Clicks >= ' + clicksMin;
}
if (clicksMax != null){
query = query + ' AND Clicks <= ' + clicksMax;
}
if (conversionsMin != null){
conversionsMin--;
query = query + ' AND Conversions > ' + conversionsMin;
}
if (conversionsMax != null){
conversionsMax++;
query = query + ' AND Conversions < ' + conversionsMax;
}
if (conversionRateMin != null){
conversionRateMin = conversionRateMin - 0.01;
query = query + ' AND ConversionRate > ' + conversionRateMin;
}
if (conversionRateMax != null){
conversionRateMax = conversionRateMax + 0.01;
query = query + ' AND ConversionRate < ' + conversionRateMax;
}
if (ctrMin != null){
ctrMin = ctrMin - 0.01;
query = query + ' AND Ctr > ' + ctrMin;
}
if (ctrMax != null){
ctrMax = ctrMax + 0.01;
query = query + ' AND Ctr < ' + ctrMax;
}
if (avgPositionMin != null){
avgPositionMin = avgPositionMin - 0.01;
query = query + ' AND AveragePosition > ' + avgPositionMin;
}
if (avgPositionMax != null){
avgPositionMax = avgPositionMax + 0.01;
query = query + ' AND AveragePosition < ' + avgPositionMax;
}
if (cpaMin != null){
cpaMin = cpaMin*1000000;
query = query + ' AND CostPerConversion > ' + cpaMin;
}
if (cpaMax != null){
cpaMax = cpaMax*1000000;
query = query + ' AND CostPerConversion < ' + cpaMax;
}
if (costMin != null){
query = query + ' AND Cost >= ' + costMin;
} else if (cpaMin != null) {
var cpaMinAux = cpaMin/1000000;
query = query + ' AND Cost >= ' + cpaMinAux;
}
if (costMax != null){
query = query + ' AND Cost <= ' + costMax;
}
if (qualityScoreMin != null){
queryQs = queryQs + ' AND QualityScore >= ' + qualityScoreMin;
}
if (qualityScoreMax != null){
queryQs = queryQs + ' AND QualityScore <= ' + qualityScoreMax;
}
} // End of buildQuery function
function emailNotification (s, b, email){
if (RECIPIENT_EMAIL != ""){
MailApp.sendEmail(email, s, b);
}
} // End of emailNotification function
// ----------------------------------------------------------------
function getFilteredMccAccounts (){
var accountIterator;
var accountIds = [];
var accountId;
if (mccLabelText != "no label") { // Filter accounts by MCC label
accountIterator = MccApp.accounts().withCondition("LabelNames CONTAINS '" + mccLabelText +"'").orderBy('Name').get();
} else { // Execute script for all accounts
accountIterator = MccApp.accounts().orderBy('Name').get();
}
while (accountIterator.hasNext()) {
accountId = accountIterator.next().getCustomerId();
accountIds.push(accountId);
}
return accountIds;
} // End of getFilteredMccAccounts function
function executeInSequence (sequentialIds, executeSequentiallyFunc) {
//Logger.log('Executing in sequence : ' + sequentialIds);
sequentialIds.forEach(function (accountId) {
body = body + "\nACCOUNT ID: " + accountId + "\n";
//Logger.log("\nACCOUNT ID: " + accountId + "\n" + " \n");
var account = MccApp.accounts().withIds([accountId]).get().next();
MccApp.select(account);
var res = executeSequentiallyFunc();
});
} // End of executeInSequence function
function main () {
try {
buildQuery(); // query building
// Logger.log("Query = " + query);
if (mccLevelScript){
var accountIds = getFilteredMccAccounts();
// Logger.log(accountIds);
var sequentialIds = accountIds.slice(0);
if (accountIds.length > 0) {
executeInSequence(sequentialIds, run);
} else {
body = body + "No Accounts after filtering by mccLabelText '" + mccLabelText + "' \n";
}
} else {
var aux = run();
}
// ------------------------------- Send notification by email -------------------------------------
emailNotification(subject, body, RECIPIENT_EMAIL);
} catch (exception) {
// Logger.log("Error: "+Logger.getLog());
// Logger.getLog();
body = body + subject_error + Logger.getLog();
emailNotification(subject_error, body, RECIPIENT_EMAIL);
}
} // End of Script