-
Notifications
You must be signed in to change notification settings - Fork 499
/
Copy pathadd_performance_max_campaign.py
842 lines (725 loc) · 31.7 KB
/
add_performance_max_campaign.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
#!/usr/bin/env python
# Copyright 2021 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.
"""This example shows how to create a Performance Max campaign.
For more information about Performance Max campaigns, see
https://developers.google.com/google-ads/api/docs/performance-max/overview
Prerequisites:
- You must have at least one conversion action in the account. For
more about conversion actions, see
https://developers.google.com/google-ads/api/docs/conversions/overview#conversion_actions
This example uses the default customer conversion goals. For an example
of setting campaign-specific conversion goals, see
shopping_ads/add_performance_max_retail_campaign.py
"""
import argparse
from datetime import datetime, timedelta
import sys
from uuid import uuid4
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
from google.ads.googleads.util import convert_snake_case_to_upper_case
import requests
# We specify temporary IDs that are specific to a single mutate request.
# Temporary IDs are always negative and unique within one mutate request.
#
# See https://developers.google.com/google-ads/api/docs/mutating/best-practices
# for further details.
#
# These temporary IDs are fixed because they are used in multiple places.
_BUDGET_TEMPORARY_ID = "-1"
_PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID = "-2"
_ASSET_GROUP_TEMPORARY_ID = "-3"
# There are also entities that will be created in the same request but do not
# need to be fixed temporary IDs because they are referenced only once.
next_temp_id = int(_ASSET_GROUP_TEMPORARY_ID) - 1
# [START add_performance_max_campaign]
def main(client, customer_id, audience_id, brand_guidelines_enabled):
"""The main method that creates all necessary entities for the example.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
audience_id: an optional audience ID.
brand_guidelines_enabled: a boolean value indicating if the campaign is
enabled for brand guidelines.
"""
# [START add_performance_max_campaign_1]
googleads_service = client.get_service("GoogleAdsService")
# Performance Max campaigns require that repeated assets such as headlines
# and descriptions be created before the campaign.
# For the list of required assets for a Performance Max campaign, see
# https://developers.google.com/google-ads/api/docs/performance-max/assets
#
# Create the headlines.
headline_asset_resource_names = create_multiple_text_assets(
client,
customer_id,
[
"Travel",
"Travel Reviews",
"Book travel",
],
)
# Create the descriptions.
description_asset_resource_names = create_multiple_text_assets(
client,
customer_id,
[
"Take to the air!",
"Fly to the sky!",
],
)
# The below methods create and return MutateOperations that we later
# provide to the GoogleAdsService.Mutate method in order to create the
# entities in a single request. Since the entities for a Performance Max
# campaign are closely tied to one-another, it's considered a best practice
# to create them in a single Mutate request so they all complete
# successfully or fail entirely, leaving no orphaned entities. See:
# https://developers.google.com/google-ads/api/docs/mutating/overview
campaign_budget_operation = create_campaign_budget_operation(
client,
customer_id,
)
performance_max_campaign_operation = create_performance_max_campaign_operation(
client,
customer_id,
brand_guidelines_enabled,
)
campaign_criterion_operations = create_campaign_criterion_operations(
client,
customer_id,
)
asset_group_operations = create_asset_group_operation(
client,
customer_id,
headline_asset_resource_names,
description_asset_resource_names,
brand_guidelines_enabled,
)
asset_group_signal_operations = create_asset_group_signal_operations(
client, customer_id, audience_id
)
mutate_operations = [
# It's important to create these entities in this order because
# they depend on each other.
campaign_budget_operation,
performance_max_campaign_operation,
# Expand the list of multiple operations into the list of
# other mutate operations
*campaign_criterion_operations,
*asset_group_operations,
*asset_group_signal_operations,
]
# Send the operations in a single Mutate request.
response = googleads_service.mutate(
customer_id=customer_id, mutate_operations=mutate_operations
)
print_response_details(response)
# [END add_performance_max_campaign_1]
# [START add_performance_max_campaign_2]
def create_campaign_budget_operation(
client,
customer_id,
):
"""Creates a MutateOperation that creates a new CampaignBudget.
A temporary ID will be assigned to this campaign budget so that it can be
referenced by other objects being created in the same Mutate request.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
Returns:
a MutateOperation that creates a CampaignBudget.
"""
mutate_operation = client.get_type("MutateOperation")
campaign_budget_operation = mutate_operation.campaign_budget_operation
campaign_budget = campaign_budget_operation.create
campaign_budget.name = f"Performance Max campaign budget #{uuid4()}"
# The budget period already defaults to DAILY.
campaign_budget.amount_micros = 50000000
campaign_budget.delivery_method = client.enums.BudgetDeliveryMethodEnum.STANDARD
# A Performance Max campaign cannot use a shared campaign budget.
campaign_budget.explicitly_shared = False
# Set a temporary ID in the budget's resource name so it can be referenced
# by the campaign in later steps.
campaign_budget.resource_name = client.get_service(
"CampaignBudgetService"
).campaign_budget_path(customer_id, _BUDGET_TEMPORARY_ID)
return mutate_operation
# [END add_performance_max_campaign_2]
# [START add_performance_max_campaign_3]
def create_performance_max_campaign_operation(
client,
customer_id,
brand_guidelines_enabled,
):
"""Creates a MutateOperation that creates a new Performance Max campaign.
A temporary ID will be assigned to this campaign so that it can
be referenced by other objects being created in the same Mutate request.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
brand_guidelines_enabled: a boolean value indicating if the campaign is
enabled for brand guidelines.
Returns:
a MutateOperation that creates a campaign.
"""
mutate_operation = client.get_type("MutateOperation")
campaign = mutate_operation.campaign_operation.create
campaign.name = f"Performance Max campaign #{uuid4()}"
# Set the campaign status as PAUSED. The campaign is the only entity in
# the mutate request that should have its status set.
campaign.status = client.enums.CampaignStatusEnum.PAUSED
# All Performance Max campaigns have an advertising_channel_type of
# PERFORMANCE_MAX. The advertising_channel_sub_type should not be set.
campaign.advertising_channel_type = (
client.enums.AdvertisingChannelTypeEnum.PERFORMANCE_MAX
)
# Bidding strategy must be set directly on the campaign.
# Setting a portfolio bidding strategy by resource name is not supported.
# Max Conversion and Maximize Conversion Value are the only strategies
# supported for Performance Max campaigns.
# An optional ROAS (Return on Advertising Spend) can be set for
# maximize_conversion_value. The ROAS value must be specified as a ratio in
# the API. It is calculated by dividing "total value" by "total spend".
# For more information on Maximize Conversion Value, see the support
# article: http://support.google.com/google-ads/answer/7684216.
# A target_roas of 3.5 corresponds to a 350% return on ad spend.
campaign.bidding_strategy_type = (
client.enums.BiddingStrategyTypeEnum.MAXIMIZE_CONVERSION_VALUE
)
campaign.maximize_conversion_value.target_roas = 3.5
# Set the Final URL expansion opt out. This flag is specific to
# Performance Max campaigns. If opted out (True), only the final URLs in
# the asset group or URLs specified in the advertiser's Google Merchant
# Center or business data feeds are targeted.
# If opted in (False), the entire domain will be targeted. For best
# results, set this value to false to opt in and allow URL expansions. You
# can optionally add exclusions to limit traffic to parts of your website.
campaign.url_expansion_opt_out = False
# Set if the campaign is enabled for brand guidelines. For more information
# on brand guidelines, see https://support.google.com/google-ads/answer/14934472.
campaign.brand_guidelines_enabled = brand_guidelines_enabled
# Assign the resource name with a temporary ID.
campaign_service = client.get_service("CampaignService")
campaign.resource_name = campaign_service.campaign_path(
customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID
)
# Set the budget using the given budget resource name.
campaign.campaign_budget = campaign_service.campaign_budget_path(
customer_id, _BUDGET_TEMPORARY_ID
)
# Optional fields
campaign.start_date = (datetime.now() + timedelta(1)).strftime("%Y%m%d")
campaign.end_date = (datetime.now() + timedelta(365)).strftime("%Y%m%d")
return mutate_operation
# [END add_performance_max_campaign_3]
# [START add_performance_max_campaign_4]
def create_campaign_criterion_operations(
client,
customer_id,
):
"""Creates a list of MutateOperations that create new campaign criteria.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
Returns:
a list of MutateOperations that create new campaign criteria.
"""
campaign_service = client.get_service("CampaignService")
geo_target_constant_service = client.get_service("GeoTargetConstantService")
googleads_service = client.get_service("GoogleAdsService")
operations = []
# Set the LOCATION campaign criteria.
# Target all of New York City except Brooklyn.
# Location IDs are listed here:
# https://developers.google.com/google-ads/api/reference/data/geotargets
# and they can also be retrieved using the GeoTargetConstantService as shown
# here: https://developers.google.com/google-ads/api/docs/targeting/location-targeting
#
# We will add one positive location target for New York City (ID=1023191)
# and one negative location target for Brooklyn (ID=1022762).
# First, add the positive (negative = False) for New York City.
mutate_operation = client.get_type("MutateOperation")
campaign_criterion = mutate_operation.campaign_criterion_operation.create
campaign_criterion.campaign = campaign_service.campaign_path(
customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID
)
campaign_criterion.location.geo_target_constant = (
geo_target_constant_service.geo_target_constant_path("1023191")
)
campaign_criterion.negative = False
operations.append(mutate_operation)
# Next add the negative target for Brooklyn.
mutate_operation = client.get_type("MutateOperation")
campaign_criterion = mutate_operation.campaign_criterion_operation.create
campaign_criterion.campaign = campaign_service.campaign_path(
customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID
)
campaign_criterion.location.geo_target_constant = (
geo_target_constant_service.geo_target_constant_path("1022762")
)
campaign_criterion.negative = True
operations.append(mutate_operation)
# Set the LANGUAGE campaign criterion.
mutate_operation = client.get_type("MutateOperation")
campaign_criterion = mutate_operation.campaign_criterion_operation.create
campaign_criterion.campaign = campaign_service.campaign_path(
customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID
)
# Set the language.
# For a list of all language codes, see:
# https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-7
campaign_criterion.language.language_constant = (
googleads_service.language_constant_path("1000")
) # English
operations.append(mutate_operation)
return operations
# [END add_performance_max_campaign_4]
# [START add_performance_max_campaign_5]
def create_multiple_text_assets(client, customer_id, texts):
"""Creates multiple text assets and returns the list of resource names.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
texts: a list of strings, each of which will be used to create a text
asset.
Returns:
asset_resource_names: a list of asset resource names.
"""
# Here again we use the GoogleAdService to create multiple text
# assets in a single request.
googleads_service = client.get_service("GoogleAdsService")
operations = []
for text in texts:
mutate_operation = client.get_type("MutateOperation")
asset = mutate_operation.asset_operation.create
asset.text_asset.text = text
operations.append(mutate_operation)
# Send the operations in a single Mutate request.
response = googleads_service.mutate(
customer_id=customer_id,
mutate_operations=operations,
)
asset_resource_names = []
for result in response.mutate_operation_responses:
if result._pb.HasField("asset_result"):
asset_resource_names.append(result.asset_result.resource_name)
print_response_details(response)
return asset_resource_names
# [END add_performance_max_campaign_5]
# [START add_performance_max_campaign_6]
def create_asset_group_operation(
client,
customer_id,
headline_asset_resource_names,
description_asset_resource_names,
brand_guidelines_enabled,
):
"""Creates a list of MutateOperations that create a new asset_group.
A temporary ID will be assigned to this asset group so that it can
be referenced by other objects being created in the same Mutate request.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
headline_asset_resource_names: a list of headline resource names.
description_asset_resource_names: a list of description resource names.
brand_guidelines_enabled: a boolean value indicating if the campaign is
enabled for brand guidelines.
Returns:
MutateOperations that create a new asset group and related assets.
"""
asset_group_service = client.get_service("AssetGroupService")
campaign_service = client.get_service("CampaignService")
operations = []
# Create the AssetGroup
mutate_operation = client.get_type("MutateOperation")
asset_group = mutate_operation.asset_group_operation.create
asset_group.name = f"Performance Max asset group #{uuid4()}"
asset_group.campaign = campaign_service.campaign_path(
customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID
)
asset_group.final_urls.append("http://www.example.com")
asset_group.final_mobile_urls.append("http://www.example.com")
asset_group.status = client.enums.AssetGroupStatusEnum.PAUSED
asset_group.resource_name = asset_group_service.asset_group_path(
customer_id,
_ASSET_GROUP_TEMPORARY_ID,
)
operations.append(mutate_operation)
# For the list of required assets for a Performance Max campaign, see
# https://developers.google.com/google-ads/api/docs/performance-max/assets
# An AssetGroup is linked to an Asset by creating a new AssetGroupAsset
# and providing:
# the resource name of the AssetGroup
# the resource name of the Asset
# the field_type of the Asset in this AssetGroup.
#
# To learn more about AssetGroups, see
# https://developers.google.com/google-ads/api/docs/performance-max/asset-groups
# Link the previously created multiple text assets.
# Link the headline assets.
for resource_name in headline_asset_resource_names:
mutate_operation = client.get_type("MutateOperation")
asset_group_asset = mutate_operation.asset_group_asset_operation.create
asset_group_asset.field_type = client.enums.AssetFieldTypeEnum.HEADLINE
asset_group_asset.asset_group = asset_group_service.asset_group_path(
customer_id,
_ASSET_GROUP_TEMPORARY_ID,
)
asset_group_asset.asset = resource_name
operations.append(mutate_operation)
# Link the description assets.
for resource_name in description_asset_resource_names:
mutate_operation = client.get_type("MutateOperation")
asset_group_asset = mutate_operation.asset_group_asset_operation.create
asset_group_asset.field_type = client.enums.AssetFieldTypeEnum.DESCRIPTION
asset_group_asset.asset_group = asset_group_service.asset_group_path(
customer_id,
_ASSET_GROUP_TEMPORARY_ID,
)
asset_group_asset.asset = resource_name
operations.append(mutate_operation)
# Create and link the long headline text asset.
mutate_operations = create_and_link_text_asset(
client,
customer_id,
"Travel the World",
client.enums.AssetFieldTypeEnum.LONG_HEADLINE,
)
operations.extend(mutate_operations)
# Create and link the business name and logo asset.
mutate_operations = create_and_link_brand_assets(
client,
customer_id,
brand_guidelines_enabled,
"Interplanetary Cruises",
"https://gaagl.page.link/bjYi",
"Marketing Logo",
)
operations.extend(mutate_operations)
# Create and link the image assets.
# Create and link the Marketing Image Asset.
mutate_operations = create_and_link_image_asset(
client,
customer_id,
"https://gaagl.page.link/Eit5",
client.enums.AssetFieldTypeEnum.MARKETING_IMAGE,
"Marketing Image",
)
operations.extend(mutate_operations)
# Create and link the Square Marketing Image Asset.
mutate_operations = create_and_link_image_asset(
client,
customer_id,
"https://gaagl.page.link/bjYi",
client.enums.AssetFieldTypeEnum.SQUARE_MARKETING_IMAGE,
"Square Marketing Image",
)
operations.extend(mutate_operations)
return operations
# [END add_performance_max_campaign_6]
# [START add_performance_max_campaign_7]
def create_and_link_text_asset(client, customer_id, text, field_type):
"""Creates a list of MutateOperations that create a new linked text asset.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
text: the text of the asset to be created.
field_type: the field_type of the new asset in the AssetGroupAsset.
Returns:
MutateOperations that create a new linked text asset.
"""
global next_temp_id
operations = []
asset_service = client.get_service("AssetService")
asset_group_service = client.get_service("AssetGroupService")
# Create the Text Asset.
mutate_operation = client.get_type("MutateOperation")
asset = mutate_operation.asset_operation.create
asset.resource_name = asset_service.asset_path(customer_id, next_temp_id)
asset.text_asset.text = text
operations.append(mutate_operation)
# Create an AssetGroupAsset to link the Asset to the AssetGroup.
mutate_operation = client.get_type("MutateOperation")
asset_group_asset = mutate_operation.asset_group_asset_operation.create
asset_group_asset.field_type = field_type
asset_group_asset.asset_group = asset_group_service.asset_group_path(
customer_id,
_ASSET_GROUP_TEMPORARY_ID,
)
asset_group_asset.asset = asset_service.asset_path(customer_id, next_temp_id)
operations.append(mutate_operation)
next_temp_id -= 1
return operations
# [END add_performance_max_campaign_7]
# [START add_performance_max_campaign_8]
def create_and_link_image_asset(client, customer_id, url, field_type, asset_name):
"""Creates a list of MutateOperations that create a new linked image asset.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
url: the url of the image to be retrieved and put into an asset.
field_type: the field_type of the new asset in the AssetGroupAsset.
asset_name: the asset name.
Returns:
MutateOperations that create a new linked image asset.
"""
global next_temp_id
operations = []
asset_service = client.get_service("AssetService")
asset_group_service = client.get_service("AssetGroupService")
# Create the Image Asset.
mutate_operation = client.get_type("MutateOperation")
asset = mutate_operation.asset_operation.create
asset.resource_name = asset_service.asset_path(customer_id, next_temp_id)
# Provide a unique friendly name to identify your asset.
# When there is an existing image asset with the same content but a different
# name, the new name will be dropped silently.
asset.name = asset_name
asset.type_ = client.enums.AssetTypeEnum.IMAGE
asset.image_asset.data = get_image_bytes(url)
operations.append(mutate_operation)
# Create an AssetGroupAsset to link the Asset to the AssetGroup.
mutate_operation = client.get_type("MutateOperation")
asset_group_asset = mutate_operation.asset_group_asset_operation.create
asset_group_asset.field_type = field_type
asset_group_asset.asset_group = asset_group_service.asset_group_path(
customer_id,
_ASSET_GROUP_TEMPORARY_ID,
)
asset_group_asset.asset = asset_service.asset_path(customer_id, next_temp_id)
operations.append(mutate_operation)
next_temp_id -= 1
return operations
# [END add_performance_max_campaign_8]
def create_and_link_brand_assets(
client, customer_id, brand_guidelines_enabled, business_name, logo_url, logo_name
):
"""Creates a list of MutateOperations that create linked brand assets.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
brand_guidelines_enabled: a boolean value indicating if the campaign is
enabled for brand guidelines.
business_name: the business name text to be put into an asset.
logo_url: the url of the logo to be retrieved and put into an asset.
logo_name: the asset name of the logo.
Returns:
MutateOperations that create linked brand assets.
"""
global next_temp_id
operations = []
asset_service = client.get_service("AssetService")
# Create the Text Asset.
text_asset_temp_id = next_temp_id
next_temp_id -= 1
text_mutate_operation = client.get_type("MutateOperation")
text_asset = text_mutate_operation.asset_operation.create
text_asset.resource_name = asset_service.asset_path(customer_id, text_asset_temp_id)
text_asset.text_asset.text = business_name
operations.append(text_mutate_operation)
# Create the Image Asset.
image_asset_temp_id = next_temp_id
next_temp_id -= 1
image_mutate_operation = client.get_type("MutateOperation")
image_asset = image_mutate_operation.asset_operation.create
image_asset.resource_name = asset_service.asset_path(
customer_id, image_asset_temp_id
)
# Provide a unique friendly name to identify your asset.
# When there is an existing image asset with the same content but a different
# name, the new name will be dropped silently.
image_asset.name = logo_name
image_asset.type_ = client.enums.AssetTypeEnum.IMAGE
image_asset.image_asset.data = get_image_bytes(logo_url)
operations.append(image_mutate_operation)
if brand_guidelines_enabled:
# Create CampaignAsset resources to link the Asset resources to the Campaign.
campaign_service = client.get_service("CampaignService")
business_name_mutate_operation = client.get_type("MutateOperation")
business_name_campaign_asset = (
business_name_mutate_operation.campaign_asset_operation.create
)
business_name_campaign_asset.field_type = (
client.enums.AssetFieldTypeEnum.BUSINESS_NAME
)
business_name_campaign_asset.campaign = campaign_service.campaign_path(
customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID
)
business_name_campaign_asset.asset = asset_service.asset_path(
customer_id, text_asset_temp_id
)
operations.append(business_name_mutate_operation)
logo_mutate_operation = client.get_type("MutateOperation")
logo_campaign_asset = logo_mutate_operation.campaign_asset_operation.create
logo_campaign_asset.field_type = client.enums.AssetFieldTypeEnum.LOGO
logo_campaign_asset.campaign = campaign_service.campaign_path(
customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID
)
logo_campaign_asset.asset = asset_service.asset_path(
customer_id, image_asset_temp_id
)
operations.append(logo_mutate_operation)
else:
# Create AssetGroupAsset resources to link the Asset resources to the AssetGroup.
asset_group_service = client.get_service("AssetGroupService")
business_name_mutate_operation = client.get_type("MutateOperation")
business_name_asset_group_asset = (
business_name_mutate_operation.asset_group_asset_operation.create
)
business_name_asset_group_asset.field_type = (
client.enums.AssetFieldTypeEnum.BUSINESS_NAME
)
business_name_asset_group_asset.asset_group = (
asset_group_service.asset_group_path(
customer_id,
_ASSET_GROUP_TEMPORARY_ID,
)
)
business_name_asset_group_asset.asset = asset_service.asset_path(
customer_id, text_asset_temp_id
)
operations.append(business_name_mutate_operation)
logo_mutate_operation = client.get_type("MutateOperation")
logo_asset_group_asset = (
logo_mutate_operation.asset_group_asset_operation.create
)
logo_asset_group_asset.field_type = client.enums.AssetFieldTypeEnum.LOGO
logo_asset_group_asset.asset_group = asset_group_service.asset_group_path(
customer_id,
_ASSET_GROUP_TEMPORARY_ID,
)
logo_asset_group_asset.asset = asset_service.asset_path(
customer_id, image_asset_temp_id
)
operations.append(logo_mutate_operation)
return operations
def get_image_bytes(url):
"""Loads image data from a URL.
Args:
url: a URL str.
Returns:
Images bytes loaded from the given URL.
"""
response = requests.get(url)
return response.content
def print_response_details(response):
"""Prints the details of a MutateGoogleAdsResponse.
Parses the "response" oneof field name and uses it to extract the new
entity's name and resource name.
Args:
response: a MutateGoogleAdsResponse object.
"""
# Parse the Mutate response to print details about the entities that
# were created by the request.
suffix = "_result"
for result in response.mutate_operation_responses:
for field_descriptor, value in result._pb.ListFields():
if field_descriptor.name.endswith(suffix):
name = field_descriptor.name[: -len(suffix)]
else:
name = field_descriptor.name
print(
f"Created a(n) {convert_snake_case_to_upper_case(name)} with "
f"{str(value).strip()}."
)
def create_asset_group_signal_operations(client, customer_id, audience_id):
"""Creates a list of MutateOperations that may create asset group signals.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
audience_id: an optional audience ID.
Returns:
MutateOperations that create new asset group signals.
"""
googleads_service = client.get_service("GoogleAdsService")
asset_group_resource_name = googleads_service.asset_group_path(
customer_id, _ASSET_GROUP_TEMPORARY_ID
)
operations = []
if audience_id:
# Create an audience asset group signal.
# To learn more about Audience Signals, see:
# https://developers.google.com/google-ads/api/performance-max/asset-group-signals#audiences
# [START add_performance_max_campaign_9]
mutate_operation = client.get_type("MutateOperation")
operation = mutate_operation.asset_group_signal_operation.create
operation.asset_group = asset_group_resource_name
operation.audience.audience = googleads_service.audience_path(
customer_id, audience_id
)
operations.append(mutate_operation)
# [END add_performance_max_campaign_9]
# Create a search theme asset group signal.
# To learn more about Search Themes Signals, see:
# https://developers.google.com/google-ads/api/performance-max/asset-group-signals#search_themes
# [START add_performance_max_campaign_10]
mutate_operation = client.get_type("MutateOperation")
operation = mutate_operation.asset_group_signal_operation.create
operation.asset_group = asset_group_resource_name
operation.search_theme.text = "travel"
operations.append(mutate_operation)
# [END add_performance_max_campaign_10]
return operations
# [END add_performance_max_campaign]
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=("Creates a Performance Max campaign.")
)
# 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",
"--audience_id",
type=str,
help="The ID of an audience.",
)
parser.add_argument(
"-b",
"--brand_guidelines_enabled",
type=bool,
default=False,
help=(
"A boolean value indicating if the created campaign is enabled "
"for brand guidelines."
),
)
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="v19")
try:
main(
googleads_client,
args.customer_id,
args.audience_id,
args.brand_guidelines_enabled,
)
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'Error 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)