-
Notifications
You must be signed in to change notification settings - Fork 472
/
add_shopping_product_listing_group_tree.py
440 lines (386 loc) · 15.7 KB
/
add_shopping_product_listing_group_tree.py
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
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Adds a shopping listing group tree to a shopping ad group.
The example will clear an existing listing group tree and rebuild it include the
following tree structure:
ProductCanonicalCondition NEW $0.20
ProductCanonicalCondition USED $0.10
ProductCanonicalCondition null (everything else)
ProductBrand CoolBrand $0.90
ProductBrand CheapBrand $0.01
ProductBrand null (everything else) $0.50
"""
import argparse
import sys
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
last_criterion_id = 0
def next_id():
"""Returns a decreasing negative number for temporary ad group criteria IDs.
The ad group criteria will get real IDs when created on the server.
Returns -1, -2, -3, etc. on subsequent calls.
Returns:
The string representation of a negative integer.
"""
global last_criterion_id
last_criterion_id -= 1
return str(last_criterion_id)
# [START add_shopping_product_listing_group_tree]
def main(client, customer_id, ad_group_id, replace_existing_tree):
"""Adds a shopping listing group tree to a shopping ad group.
Args:
client: An initialized Google Ads client.
customer_id: The Google Ads customer ID.
ad_group_id: The ad group ID to which the node will be added.
replace_existing_tree: Boolean, whether to replace the existing listing
group tree on the ad group. Defaults to false.
"""
# Get the AdGroupCriterionService client.
ad_group_criterion_service = client.get_service("AdGroupCriterionService")
# Optional: Remove the existing listing group tree, if it already exists
# on the ad group. The example will throw a LISTING_GROUP_ALREADY_EXISTS
# error if a listing group tree already exists and this option is not
# set to true.
if replace_existing_tree:
remove_listing_group_tree(client, customer_id, ad_group_id)
# Create a list of ad group criteria operations.
operations = []
# Construct the listing group tree "root" node.
# Subdivision node: (Root node)
ad_group_criterion_root_operation = create_listing_group_subdivision(
client, customer_id, ad_group_id
)
# Get the resource name that will be used for the root node.
# This resource has not been created yet and will include the temporary
# ID as part of the criterion ID.
ad_group_criterion_root_resource_name = (
ad_group_criterion_root_operation.create.resource_name
)
operations.append(ad_group_criterion_root_operation)
# Construct the listing group unit nodes for NEW, USED, and other.
product_condition_enum = client.enums.ProductConditionEnum
condition_dimension_info = client.get_type("ListingDimensionInfo")
# Biddable Unit node: (Condition NEW node)
# * Product Condition: NEW
# * CPC bid: $0.20
condition_dimension_info.product_condition.condition = (
product_condition_enum.NEW
)
operations.append(
create_listing_group_unit_biddable(
client,
customer_id,
ad_group_id,
ad_group_criterion_root_resource_name,
condition_dimension_info,
200_000,
)
)
# Biddable Unit node: (Condition USED node)
# * Product Condition: USED
# * CPC bid: $0.10
condition_dimension_info.product_condition.condition = (
product_condition_enum.USED
)
operations.append(
create_listing_group_unit_biddable(
client,
customer_id,
ad_group_id,
ad_group_criterion_root_resource_name,
condition_dimension_info,
100_000,
)
)
# Sub-division node: (Condition "other" node)
# * Product Condition: (not specified)
# Note that all sibling nodes must have the same dimension type, even if
# they don't contain a bid.
client.copy_from(
condition_dimension_info.product_condition,
client.get_type("ProductConditionInfo"),
)
ad_group_criterion_other_operation = create_listing_group_subdivision(
client,
customer_id,
ad_group_id,
ad_group_criterion_root_resource_name,
condition_dimension_info,
)
# Get the resource name that will be used for the condition other node.
# This resource has not been created yet and will include the temporary
# ID as part of the criterion ID.
ad_group_criterion_other_resource_name = (
ad_group_criterion_other_operation.create.resource_name
)
operations.append(ad_group_criterion_other_operation)
# Build the listing group nodes for CoolBrand, CheapBrand, and other.
brand_dimension_info = client.get_type("ListingDimensionInfo")
# Biddable Unit node: (Brand CoolBrand node)
# * Brand: CoolBrand
# * CPC bid: $0.90
brand_dimension_info.product_brand.value = "CoolBrand"
operations.append(
create_listing_group_unit_biddable(
client,
customer_id,
ad_group_id,
ad_group_criterion_other_resource_name,
brand_dimension_info,
900_000,
)
)
# Biddable Unit node: (Brand CheapBrand node)
# * Brand: CheapBrand
# * CPC bid: $0.01
brand_dimension_info.product_brand.value = "CheapBrand"
operations.append(
create_listing_group_unit_biddable(
client,
customer_id,
ad_group_id,
ad_group_criterion_other_resource_name,
brand_dimension_info,
10_000,
)
)
# Biddable Unit node: (Brand other node)
# * CPC bid: $0.05
client.copy_from(
brand_dimension_info.product_brand,
client.get_type("ProductBrandInfo"),
)
operations.append(
create_listing_group_unit_biddable(
client,
customer_id,
ad_group_id,
ad_group_criterion_other_resource_name,
brand_dimension_info,
50_000,
)
)
# Add the ad group criteria.
mutate_ad_group_criteria_response = (
ad_group_criterion_service.mutate_ad_group_criteria(
customer_id=customer_id, operations=operations
)
)
# Print the results of the successful mutates.
print(
"Added ad group criteria for the listing group tree with the "
"following resource names:"
)
for result in mutate_ad_group_criteria_response.results:
print(f"\t{result.resource_name}")
print(f"{len(mutate_ad_group_criteria_response.results)} criteria added.")
# [END add_shopping_product_listing_group_tree]
def remove_listing_group_tree(client, customer_id, ad_group_id):
"""Removes ad group criteria for an ad group's existing listing group tree.
Args:
client: An initialized Google Ads client.
customer_id: The Google Ads customer ID.
ad_group_id: The ad group ID from which to remove the listing group
tree.
"""
# Get the GoogleAdsService client.
googleads_service = client.get_service("GoogleAdsService")
print("Removing existing listing group tree...")
# Create a search Google Ads request that will retrieve all listing groups
# where the parent ad group criterion is NULL (and hence the root node in
# the tree) for a given ad group id.
query = f"""
SELECT ad_group_criterion.resource_name
FROM ad_group_criterion
WHERE
ad_group_criterion.type = LISTING_GROUP
AND ad_group_criterion.listing_group.parent_ad_group_criterion IS NULL
AND ad_group.id = {ad_group_id}"""
results = googleads_service.search(customer_id=customer_id, query=query)
ad_group_criterion_operations = []
# Iterate over all rows to find the ad group criteria to remove.
for row in results:
criterion = row.ad_group_criterion
print(
"Found an ad group criterion with resource name: "
f"'{criterion.resource_name}'."
)
ad_group_criterion_operation = client.get_type(
"AdGroupCriterionOperation"
)
ad_group_criterion_operation.remove = criterion.resource_name
ad_group_criterion_operations.append(ad_group_criterion_operation)
if ad_group_criterion_operations:
# Remove the ad group criteria that define the listing group tree.
ad_group_criterion_service = client.get_service(
"AdGroupCriterionService"
)
response = ad_group_criterion_service.mutate_ad_group_criteria(
customer_id=customer_id, operations=ad_group_criterion_operations
)
print(f"Removed {len(response.results)} ad group criteria.")
def create_listing_group_subdivision(
client,
customer_id,
ad_group_id,
parent_ad_group_criterion_resource_name=None,
listing_dimension_info=None,
):
"""Creates a new criterion containing a subdivision listing group node.
If the parent ad group criterion resource name or listing dimension info are
not specified, this method creates a root node.
Args:
client: An initialized Google Ads client.
customer_id: The Google Ads customer ID.
ad_group_id: The ad group ID to which the node will be added.
parent_ad_group_criterion_resource_name: The string resource name of the
parent node to which this listing will be attached.
listing_dimension_info: A ListingDimensionInfo object containing details
for this listing.
Returns:
An AdGroupCriterionOperation containing a populated ad group criterion.
"""
# Create an ad group criterion operation and populate the criterion.
operation = client.get_type("AdGroupCriterionOperation")
ad_group_criterion = operation.create
# The resource name the criterion will be created with. This will define
# the ID for the ad group criterion.
ad_group_criterion.resource_name = client.get_service(
"AdGroupCriterionService"
).ad_group_criterion_path(customer_id, ad_group_id, next_id())
ad_group_criterion.status = client.enums.AdGroupCriterionStatusEnum.ENABLED
listing_group_info = ad_group_criterion.listing_group
# Set the type as a SUBDIVISION, which will allow the node to be the
# parent of another sub-tree.
listing_group_info.type_ = client.enums.ListingGroupTypeEnum.SUBDIVISION
# If parent_ad_group_criterion_resource_name and listing_dimension_info
# are not null, create a non-root division by setting its parent and case
# value.
if (
parent_ad_group_criterion_resource_name
and listing_dimension_info != None
):
# Set the ad group criterion resource name for the parent listing group.
# This can include a temporary ID if the parent criterion is not yet
# created.
listing_group_info.parent_ad_group_criterion = (
parent_ad_group_criterion_resource_name
)
# Case values contain the listing dimension used for the node.
client.copy_from(listing_group_info.case_value, listing_dimension_info)
return operation
def create_listing_group_unit_biddable(
client,
customer_id,
ad_group_id,
parent_ad_group_criterion_resource_name,
listing_dimension_info,
cpc_bid_micros=None,
):
"""Creates a new criterion containing a biddable unit listing group node.
Args:
client: An initialized Google Ads client.
customer_id: The Google Ads customer ID.
ad_group_id: The ad group ID to which the node will be added.
parent_ad_group_criterion_resource_name: The string resource name of the
parent node to which this listing will be attached.
listing_dimension_info: A ListingDimensionInfo object containing details
for this listing.
cpc_bid_micros: The cost-per-click bid for this listing in micros.
Returns:
An AdGroupCriterionOperation with a populated create field.
"""
# Note: There are two approaches for creating new unit nodes:
# (1) Set the ad group resource name on the criterion (no temporary ID
# required).
# (2) Use a temporary ID to construct the criterion resource name and set
# it to the 'resourceName' attribute.
# In both cases you must set the parent ad group criterion's resource name
# on the listing group for non-root nodes.
# This example demonstrates method (1).
operation = client.get_type("AdGroupCriterionOperation")
criterion = operation.create
criterion.ad_group = client.get_service("AdGroupService").ad_group_path(
customer_id, ad_group_id
)
criterion.status = client.enums.AdGroupCriterionStatusEnum.ENABLED
# Set the bid for this listing group unit.
# This will be used as the CPC bid for items that are included in this
# listing group.
if cpc_bid_micros:
criterion.cpc_bid_micros = cpc_bid_micros
listing_group = criterion.listing_group
# Set the type as a UNIT, which will allow the group to be biddable.
listing_group.type_ = client.enums.ListingGroupTypeEnum.UNIT
# Set the ad group criterion resource name for the parent listing group.
# This can have a temporary ID if the parent criterion is not yet created.
listing_group.parent_ad_group_criterion = (
parent_ad_group_criterion_resource_name
)
# Case values contain the listing dimension used for the node.
if listing_dimension_info != None:
client.copy_from(listing_group.case_value, listing_dimension_info)
return operation
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Add shopping product listing group tree to a shopping ad "
"group."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Google Ads customer ID.",
)
parser.add_argument(
"-a",
"--ad_group_id",
type=str,
required=True,
help="The ID of the ad group that will receive the listing group tree.",
)
parser.add_argument(
"-r",
"--replace_existing_tree",
action="store_true",
required=False,
default=False,
help="Optional, whether to replace the existing listing group tree on "
"the ad group if one already exists. Defaults to false.",
)
args = parser.parse_args()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v16")
try:
main(
googleads_client,
args.customer_id,
args.ad_group_id,
args.replace_existing_tree,
)
except GoogleAdsException as ex:
print(
f"Request with ID '{ex.request_id}' failed with status "
f"'{ex.error.code().name}' and includes the following errors:"
)
for error in ex.failure.errors:
print(f"\tError with message '{error.message}'.")
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)