-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathadsScriptsScript.js
346 lines (331 loc) · 9.49 KB
/
adsScriptsScript.js
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
const SPREADSHEET_URL =
"https://docs.google.com/spreadsheets/d/1Dxfbnw2fV_1I9869AtrODBK99Zg4Z9kJg0SRZcdNP-8/edit";
// Sheet names
const AD_GROUP_SHEET_NAME = "AdGroups";
const CONFIG_SHEET_NAME = "Base Config";
const STATUS_SHEET_NAME = "Status";
// Get data from sheets
const SPREADSHEET = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
const AD_GROUP_SHEET = SPREADSHEET.getSheetByName(AD_GROUP_SHEET_NAME);
const CONFIG_SHEET = SPREADSHEET.getSheetByName(CONFIG_SHEET_NAME);
const STATUS_SHEET = SPREADSHEET.getSheetByName(STATUS_SHEET_NAME);
const CAMPAIGN_NAME = CONFIG_SHEET.getRange(
"googleAds_campaignName"
).getValue();
const AD_GROUPS = getAdGroupsFromSheet();
/**
* Gets a campaign (object) given its name.
* @param string name
* @returns
*/
function getCampaignByName(name) {
const campaignIterator = AdsApp.videoCampaigns()
.withCondition(`Name = "${name}"`)
.get();
if (campaignIterator.hasNext()) {
return campaignIterator.next();
}
return null;
}
/**
* Gets information on ad groups from the PVA spreadsheet.
* @returns object
*/
function getAdGroupsFromSheet() {
const values = AD_GROUP_SHEET.getDataRange()
.getValues()
.slice(1)
.filter((row) => row[0] !== "");
return Object.fromEntries(
values.map((row) => [
row[0],
{
type: row[2],
url: row[5],
callToAction: row[6],
targetLocation: row[3], // TODO: implement
audienceName: row[4], // TODO: implement
headline: row[7],
longHeadline: row[8],
description1: row[9],
description2: row[10],
},
])
);
}
/**
* Determins whether the provided status equates to "enabled".
* @param string expectedStatus
* @returns boolean
*/
function shouldEnable(expectedStatus) {
return expectedStatus.toLowerCase().trim() === "enabled";
}
/**
* Gets information on the video-related status of the desired ad groups.
* @returns object[]
*/
function getStatusFromSheet() {
const values = STATUS_SHEET.getDataRange()
.getValues()
.map((row, index) => [index + 1, ...row])
.slice(1);
return values.map((row) => ({
rowNumber: row[0],
adGroupName: row[1],
videoId: row[2],
shouldUpdate: row[4] === "",
shouldEnable: shouldEnable(row[5]),
}));
}
/**
* Writes the current data/time to the status sheet.
* @param string[] row
*/
function writeAdsUpdateTime(row) {
STATUS_SHEET.getRange(row.rowNumber, 4, 1, 1).setValue(
new Date().toISOString()
);
}
/**
* Obtains ad-group object, if needed by creating the ad group.
* @param object campaign
* @param object adGroupInfo
* @param object item
* @returns object
*/
function getOrCreateAdGroup(campaign, adGroupInfo, item) {
const adGroupIterator = campaign
.videoAdGroups()
.withCondition(`Name = "${item.adGroupName}"`)
.get();
if (adGroupIterator.hasNext()) {
return adGroupIterator.next();
}
const adGroupCreationOperation = campaign
.newVideoAdGroupBuilder()
.withAdGroupType(adGroupInfo.type)
.withName(item.adGroupName)
.withStatus(item.shouldEnable ? "ENABLED" : "PAUSED")
.build();
return getOperationResult(
adGroupCreationOperation,
"Ad Group",
item.adGroupName
);
}
/**
* Pauses the ads in the given ad group.
* @param object adGroup
*/
function pauseExistingAds(adGroup) {
const adGroupAdIterator = adGroup
.videoAds()
.withCondition("Status = ENABLED")
.get();
while (adGroupAdIterator.hasNext()) {
adGroupAdIterator.next().pause();
}
}
/**
* Identifies the result of the given operation.
* @param object operation
* @param string entityName
* @param string entityId
* @returns object
*/
function getOperationResult(operation, entityName, entityId) {
if (!operation.isSuccessful()) {
throw new Error(
`${entityName} ${entityId} creation failed: ${operation.getErrors()}`
);
}
return operation.getResult();
}
/**
* Creates an ad in the given ad group.
* @param object adGroup
* @param object adGroupInfo
* @param object item
* @returns object
*/
function createAd(adGroup, adGroupInfo, item) {
const videoCreationOperation = AdsApp.adAssets()
.newYouTubeVideoAssetBuilder()
.withName(`${item.adGroupName} - ${item.videoId}`)
.withYouTubeVideoId(item.videoId)
.build();
const video = getOperationResult(
videoCreationOperation,
"Video",
item.videoId
);
switch (adGroupInfo.type) {
case "VIDEO_TRUE_VIEW_IN_STREAM":
let inStreamAdCreationOperation = adGroup
.newVideoAd()
.inStreamAdBuilder()
.withAdName(item.adGroupName)
.withDisplayUrl(adGroupInfo.url)
.withFinalUrl(adGroupInfo.url)
.withVideo(video);
if (adGroupInfo.callToAction !== "") {
inStreamAdCreationOperation =
inStreamAdCreationOperation.withCallToAction(
adGroupInfo.callToAction
);
if (adGroupInfo.headline !== "") {
inStreamAdCreationOperation =
inStreamAdCreationOperation.withActionHeadline(
adGroupInfo.headline
);
}
}
inStreamAdCreationOperation = inStreamAdCreationOperation.build();
return getOperationResult(
inStreamAdCreationOperation,
"Video Ad",
item.videoId
);
case "VIDEO_NON_SKIPPABLE_IN_STREAM":
let nonSkippableAdCreationOperation = adGroup
.newVideoAd()
.nonSkippableAdBuilder()
.withAdName(item.adGroupName)
.withDisplayUrl(adGroupInfo.url)
.withFinalUrl(adGroupInfo.url)
.withVideo(video)
.build();
return getOperationResult(
nonSkippableAdCreationOperation,
"Video Ad",
item.videoId
);
case "VIDEO_TRUE_VIEW_IN_DISPLAY":
let displayAdCreationOperation = adGroup
.newVideoAd()
.inFeedAdBuilder()
.withAdName(item.adGroupName)
.withHeadline(adGroupInfo.headline)
.withDescription1(adGroupInfo.description1)
.withDescription2(adGroupInfo.description2)
.withThumbnail("DEFAULT_THUMBNAIL")
.withVideo(video)
.build();
return getOperationResult(
displayAdCreationOperation,
"Video Ad",
item.videoId
);
case "VIDEO_BUMPER":
let bumperAdCreationOperation = adGroup
.newVideoAd()
.bumperAdBuilder()
.withAdName(item.adGroupName)
.withDisplayUrl(adGroupInfo.url)
.withMobileFinalUrl(adGroupInfo.url)
.withFinalUrl(adGroupInfo.url)
.withVideo(video)
.build();
return getOperationResult(
bumperAdCreationOperation,
"Video Ad",
item.videoId
);
case "VIDEO_RESPONSIVE":
let responsiveAdCreationOperation = adGroup
.newVideoAd()
.responsiveVideoAdBuilder()
.withAdName(item.adGroupName)
.withLongHeadline(adGroupInfo.longHeadline)
.withDescription(adGroupInfo.description1)
.withFinalUrl(adGroupInfo.url)
.withVideo(video);
if (adGroupInfo.callToAction !== "") {
responsiveAdCreationOperation =
responsiveAdCreationOperation.withCallToAction(
adGroupInfo.callToAction
);
if (adGroupInfo.headline !== "") {
responsiveAdCreationOperation =
responsiveAdCreationOperation.withHeadline(adGroupInfo.headline);
}
}
responsiveAdCreationOperation = responsiveAdCreationOperation.build();
return getOperationResult(
responsiveAdCreationOperation,
"Video Ad",
item.videoId
);
default:
throw new Error(`${adGroupInfo.type} not implemented`);
}
}
/**
* Pauses all given ad groups.
* @param object adGroupIterator
*/
function pauseAdGroups(adGroupIterator) {
while (adGroupIterator.hasNext()) {
adGroupIterator.next().pause();
}
}
/**
* Logs an error message and writes it to the status sheet.
* @param object error
* @param number rowNumber
*/
function handleError(error, rowNumber) {
Logger.log(`[ERROR] ${error.message}`);
STATUS_SHEET.getRange(rowNumber, 6, 1, 1).setValue(error.message);
}
/**
* Deletes the error output in the status sheet's given row number.
* @param number rowNumber
*/
function clearError(rowNumber) {
STATUS_SHEET.getRange(rowNumber, 6, 1, 1).clearContent();
}
/**
* Updates ad groups based on the information provided in the PVA spreadsheet.
*/
function main() {
const campaign = getCampaignByName(CAMPAIGN_NAME);
if (!campaign) {
Logger.log("Campaign does not exist. Please create it.");
return;
}
pauseAdGroups(campaign.videoAdGroups().get()); // TODO: filter out Ad Groups which would be enabled later
const adGroupsToProcess = getStatusFromSheet();
adGroupsToProcess.forEach((item) => {
try {
const adGroupInfo = AD_GROUPS[item.adGroupName];
if (!adGroupInfo) {
throw new Error(
`Ad Group ${item.adGroupName} not defined in the 'AdGroups' sheet. Skipping...`
);
}
if (!item.shouldEnable) {
return;
}
if (!item.videoId) {
throw new Error(
`Ad Group ${item.adGroupName} does not have a defined 'Output Video ID'. Skipping...`
);
}
const adGroup = getOrCreateAdGroup(campaign, adGroupInfo, item);
if (item.shouldEnable) {
adGroup.enable();
}
if (!item.shouldUpdate) {
return;
}
pauseExistingAds(adGroup);
createAd(adGroup, adGroupInfo, item);
writeAdsUpdateTime(item);
clearError(item.rowNumber);
} catch (error) {
handleError(error, item.rowNumber);
}
});
}