Hi there, I am creating app campaign (UAC) using Python code (https://github.com/googleads/google-ads-python/blob/bcee4d08df0ea037d695d1bbcb595d7ee8adf9cd/examples/advanced_operations/add_app_campaign.py). I am successfully able to create it, but I want to target custom audience based upon user list, which I already have created using https://github.com/googleads/google-ads-python/blob/bcee4d08df0ea037d695d1bbcb595d7ee8adf9cd/examples/remarketing/set_up_remarketing.py#L78
then I changed campaign_criterion to user_list https://github.com/googleads/google-ads-python/blob/bcee4d08df0ea037d695d1bbcb595d7ee8adf9cd/examples/advanced_operations/add_app_campaign.py#L186 and I am getting following error: ``` Request made: ClientCustomerId: XXXXXXX, Host: googleads.googleapis.com, Method: /google.ads.googleads.v15.services.CampaignCriterionService/MutateCampaignCriteria, RequestId: TaaDFfP__RdmrcF7uunI5w, IsFault: True, FaultMessage: This operation is not permitted on this campaign type Request with ID "TaaDFfP__RdmrcF7uunI5w" failed with status "INVALID_ARGUMENT" and includes the following errors: Error with message "This operation is not permitted on this campaign type". On field: operations On field: create On field: user_list On field: user_list ``` I created ad_group_criterian also to target user_list and kept campaign_criterian to target only location and language but I am getting following error: `` Request made: ClientCustomerId: XXXXXXX, Host: googleads.googleapis.com, Method: /google.ads.googleads.v15.services.AdGroupCriterionService/MutateAdGroupCriteria, RequestId: 76BzHjswXVxpQb6ccgoI9g, IsFault: True, FaultMessage: The operation is not allowed for the given context. Request with ID "76BzHjswXVxpQb6ccgoI9g" failed with status "INVALID_ARGUMENT" and includes the following errors: Error with message "The operation is not allowed for the given context.". On field: operations On field: create On field: user_list `` Attached file are the code I have tried. -- -- =~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ Also find us on our blog: https://googleadsdeveloper.blogspot.com/ =~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ You received this message because you are subscribed to the Google Groups "AdWords API and Google Ads API Forum" group. To post to this group, send email to adwords-api@googlegroups.com To unsubscribe from this group, send email to adwords-api+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/adwords-api?hl=en --- You received this message because you are subscribed to the Google Groups "Google Ads API and AdWords API Forum" group. To unsubscribe from this group and stop receiving emails from it, send an email to adwords-api+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/adwords-api/4a962e7f-6c17-428c-9e74-02ee223c318bn%40googlegroups.com.
#!/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. """This example adds an App campaign. For guidance regarding App Campaigns, see: https://developers.google.com/google-ads/api/docs/app-campaigns/overview To get campaigns, run basic_operations/get_campaigns.py. To upload image assets for this campaign, run misc/upload_image_asset.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 def main(client, customer_id): """Main function for running this example.""" # Creates the budget for the campaign. budget_resource_name = create_budget(client, customer_id) # Creates the campaign. campaign_resource_name = create_campaign( client, customer_id, budget_resource_name ) # Sets campaign targeting. set_campaign_targeting_criteria( client, customer_id, campaign_resource_name) # Creates an Ad Group. ad_group_resource_name = create_ad_group( client, customer_id, campaign_resource_name ) # New target_in_ad_group_to_user_list( client, customer_id, ad_group_resource_name, "customers/XXXXXXX/userLists/XXXXXXXX") # Creates an App Ad. create_app_ad(client, customer_id, ad_group_resource_name) ###############################3 # new def target_in_ad_group_to_user_list(client, customer_id, ad_group_path, user_list_resource_name ): """Creates an ad group criterion that targets a user list with an ad group. Args: client: an initialized GoogleAdsClient instance. customer_id: a str client customer ID used to create an ad group criterion. ad_group_id: a str ID for an ad group used to create an ad group criterion that targets members of a user list. user_list_resource_name: a str resource name for a user list. Returns: a str resource name for an ad group criterion. """ ad_group_criterion_operation = client.get_type( "AdGroupCriterionOperation") # Creates the ad group criterion targeting members of the user list. ad_group_criterion = ad_group_criterion_operation.create # ad_group_criterion.ad_group = client.get_service( # "AdGroupService" # ).ad_group_path(customer_id, ad_group_id) ad_group_criterion.ad_group = ad_group_path ad_group_criterion.user_list.user_list = user_list_resource_name 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_operation] ) resource_name = response.results[0].resource_name print( "Successfully created ad group criterion with resource name: " f"'{resource_name}' targeting user list with resource name: " f"'{user_list_resource_name}' and with ad group with ID " f"{ad_group_path}." ) return resource_name # [END setup_remarketing_1] ##################################33 def create_budget(client, customer_id): """Creates a budget under the given customer ID. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. Returns: A resource_name str for the newly created Budget. """ # Retrieves the campaign budget service. campaign_budget_service = client.get_service("CampaignBudgetService") # Retrieves a new campaign budget operation object. campaign_budget_operation = client.get_type("CampaignBudgetOperation") # Creates a campaign budget. campaign_budget = campaign_budget_operation.create campaign_budget.name = "Demo campaign-budget for app-campaign" campaign_budget.amount_micros = 50000000 campaign_budget.delivery_method = ( client.enums.BudgetDeliveryMethodEnum.STANDARD ) # An App campaign cannot use a shared campaign budget. # explicitly_shared must be set to false. campaign_budget.explicitly_shared = False # Submits the campaign budget operation to add the campaign budget. response = campaign_budget_service.mutate_campaign_budgets( customer_id=customer_id, operations=[campaign_budget_operation] ) resource_name = response.results[0].resource_name print(f'Created campaign budget with resource_name: "{resource_name}"') return resource_name def create_campaign(client, customer_id, budget_resource_name): """Creates an app campaign under the given customer ID. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. budget_resource_name: the budget to associate with the campaign Returns: A resource_name str for the newly created app campaign. """ campaign_service = client.get_service("CampaignService") campaign_operation = client.get_type("CampaignOperation") campaign = campaign_operation.create campaign.name = "Demo campaign-name for app-campaign" campaign.campaign_budget = budget_resource_name # Recommendation: Set the campaign to PAUSED when creating it to # prevent the ads from immediately serving. Set to ENABLED once you've # added targeting and the ads are ready to serve. campaign.status = client.enums.CampaignStatusEnum.PAUSED # All App campaigns have an advertising_channel_type of # MULTI_CHANNEL to reflect the fact that ads from these campaigns are # eligible to appear on multiple channels. campaign.advertising_channel_type = ( client.enums.AdvertisingChannelTypeEnum.MULTI_CHANNEL ) campaign.advertising_channel_sub_type = ( client.enums.AdvertisingChannelSubTypeEnum.APP_CAMPAIGN ) # Sets the target CPA to $1 / app install. # # campaign_bidding_strategy is a 'oneof' message so setting target_cpa # is mutually exclusive with other bidding strategies such as # manual_cpc, commission, maximize_conversions, etc. # See https://developers.google.com/google-ads/api/reference/rpc # under current version / resources / Campaign campaign.target_cpa.target_cpa_micros = 1000000 # Sets the App Campaign Settings. campaign.app_campaign_setting.app_id = "com.google.android.apps.adwords" campaign.app_campaign_setting.app_store = ( client.enums.AppCampaignAppStoreEnum.GOOGLE_APP_STORE ) # Optimize this campaign for getting new users for your app. campaign.app_campaign_setting.bidding_strategy_goal_type = ( client.enums.AppCampaignBiddingStrategyGoalTypeEnum.OPTIMIZE_INSTALLS_TARGET_INSTALL_COST ) # Optional fields campaign.start_date = (datetime.now() + timedelta(1)).strftime("%Y%m%d") campaign.end_date = (datetime.now() + timedelta(365)).strftime("%Y%m%d") # Optional: If you select the # OPTIMIZE_IN_APP_CONVERSIONS_TARGET_INSTALL_COST goal type, then also # specify your in-app conversion types so the Google Ads API can focus # your campaign on people who are most likely to complete the # corresponding in-app actions. # # campaign.selective_optimization.conversion_actions.extend( # ["INSERT_CONVERSION_ACTION_RESOURCE_NAME_HERE"] # ) # Submits the campaign operation and print the results. campaign_response = campaign_service.mutate_campaigns( customer_id=customer_id, operations=[campaign_operation] ) resource_name = campaign_response.results[0].resource_name print(f'Created App campaign with resource name: "{resource_name}".') return resource_name def set_campaign_targeting_criteria( client, customer_id, campaign_resource_name ): """Sets campaign targeting criteria for a given campaign. Both location and language targeting are illustrated. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. campaign_resource_name: the campaign to apply targeting to """ campaign_criterion_service = client.get_service("CampaignCriterionService") geo_target_constant_service = client.get_service( "GeoTargetConstantService") googleads_service = client.get_service("GoogleAdsService") campaign_criterion_operations = [] # Creates the location campaign criteria. # Besides using location_id, you can also search by location names from # GeoTargetConstantService.suggest_geo_target_constants() and directly # apply GeoTargetConstant.resource_name here. An example can be found # in targeting/get_geo_target_constant_by_names.py. # Previous for location_id in ["21137", "2484"]: # California # Mexico campaign_criterion_operation = client.get_type( "CampaignCriterionOperation" ) campaign_criterion = campaign_criterion_operation.create campaign_criterion.campaign = campaign_resource_name campaign_criterion.location.geo_target_constant = ( geo_target_constant_service.geo_target_constant_path(location_id) ) campaign_criterion_operations.append(campaign_criterion_operation) # Creates the language campaign criteria. for language_id in ["1000", "1003"]: # English # Spanish campaign_criterion_operation = client.get_type( "CampaignCriterionOperation" ) campaign_criterion = campaign_criterion_operation.create campaign_criterion.campaign = campaign_resource_name campaign_criterion.language.language_constant = ( googleads_service.language_constant_path(language_id) ) campaign_criterion_operations.append(campaign_criterion_operation) # Previous ################################## # Modified # campaign_criterion_operation = client.get_type( # "CampaignCriterionOperation" # ) # campaign_criterion = campaign_criterion_operation.create # campaign_criterion.campaign = campaign_resource_name # campaign_criterion.user_list.user_list = "customers/XXXXXXXX/userLists/XXXXXXXX" # campaign_criterion_operations.append(campaign_criterion_operation) # Modified ############################## # Submits the criteria operations. for row in campaign_criterion_service.mutate_campaign_criteria( customer_id=customer_id, operations=campaign_criterion_operations ).results: print( "Created Campaign Criteria with resource name: " f'"{row.resource_name}".' ) def create_ad_group(client, customer_id, campaign_resource_name): """Creates an ad group for a given campaign. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. campaign_resource_name: the campaign to be modified Returns: A resource_name str for the newly created ad group. """ ad_group_service = client.get_service("AdGroupService") # Creates the ad group. # Note that the ad group type must not be set. # Since the advertising_channel_sub_type is APP_CAMPAIGN, # 1- you cannot override bid settings at the ad group level. # 2- you cannot add ad group criteria. ad_group_operation = client.get_type("AdGroupOperation") ad_group = ad_group_operation.create ad_group.name = "Demo adgroup for app campaign" ad_group.status = client.enums.AdGroupStatusEnum.ENABLED ad_group.campaign = campaign_resource_name ad_group_response = ad_group_service.mutate_ad_groups( customer_id=customer_id, operations=[ad_group_operation] ) ad_group_resource_name = ad_group_response.results[0].resource_name print(f'Ad Group created with resource name: "{ad_group_resource_name}".') return ad_group_resource_name def create_app_ad(client, customer_id, ad_group_resource_name): """Creates an App ad for a given ad group. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. ad_group_resource_name: the ad group where the ad will be added. """ # Creates the ad group ad. ad_group_ad_service = client.get_service("AdGroupAdService") ad_group_ad_operation = client.get_type("AdGroupAdOperation") ad_group_ad = ad_group_ad_operation.create ad_group_ad.status = client.enums.AdGroupAdStatusEnum.ENABLED ad_group_ad.ad_group = ad_group_resource_name # ad_data is a 'oneof' message so setting app_ad # is mutually exclusive with ad data fields such as # text_ad, gmail_ad, etc. ad_group_ad.ad.app_ad.headlines.extend( [ create_ad_text_asset(client, "A cool puzzle game"), create_ad_text_asset(client, "Remove connected blocks"), ] ) ad_group_ad.ad.app_ad.descriptions.extend( [ create_ad_text_asset(client, "3 difficulty levels"), create_ad_text_asset(client, "4 colorful fun skins"), ] ) # Optional: You can set up to 20 image assets for your campaign. # ad_group_ad.ad.app_ad.images.extend( # [INSERT_AD_IMAGE_RESOURCE_NAME(s)_HERE]) ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads( customer_id=customer_id, operations=[ad_group_ad_operation] ) ad_group_ad_resource_name = ad_group_ad_response.results[0].resource_name print( "Ad Group App Ad created with resource name:" f'"{ad_group_ad_resource_name}".' ) def create_ad_text_asset(client, text): ad_text_asset = client.get_type("AdTextAsset") ad_text_asset.text = text return ad_text_asset if __name__ == "__main__": # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v15") try: main(googleads_client, XXXXXX) 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)
"""Creates operations to add members to a user list (a.k.a. audience). The example uses an OfflineUserDataJob, and if requested, runs the job. If a job ID is specified, the example adds operations to that job. Otherwise, it creates a new job for the operations. IMPORTANT: Your application should create a single job containing all of the operations for a user list. This will be far more efficient than creating and running multiple jobs that each contain a small set of operations. This feature is only available to accounts that meet the requirements described at: https://support.google.com/adspolicy/answer/6299717. """ import csv import uuid from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException class UserList: def __init__(self) -> None: self.client = GoogleAdsClient.load_from_storage(version="v15") def main(self, customer_id, name, maid_ids, run_job, user_list_id, offline_user_data_job_id, ad_user_data_consent, ad_personalization_consent, ): googleads_service = self.client.get_service("GoogleAdsService") user_list_resource_name = googleads_service.user_list_path( customer_id, user_list_id ) if not offline_user_data_job_id: if user_list_id: # Uses the specified Customer Match user list. user_list_resource_name = googleads_service.user_list_path( customer_id, user_list_id ) else: # Creates a Customer Match user list. user_list_resource_name = self.create_customer_match_user_list( customer_id, name ) self.add_users_to_customer_match_user_list( customer_id, maid_ids, user_list_resource_name, run_job, offline_user_data_job_id, ad_user_data_consent, ad_personalization_consent, ) return user_list_resource_name def create_customer_match_user_list(self, customer_id, name): user_list_service_client = self.client.get_service("UserListService") user_list_operation = self.client.get_type("UserListOperation") user_list = user_list_operation.create user_list.name = name user_list.description = ( "A list of customers that originated from email and physical addresses" ) user_list.crm_based_user_list.upload_key_type = ( self.client.enums.CustomerMatchUploadKeyTypeEnum.CRM_ID ) # Customer Match user lists can set an unlimited membership life span; # to do so, use the special life span value 10000. Otherwise, membership # life span must be between 0 and 540 days inclusive. See: # https://developers.devsite.corp.google.com/google-ads/api/reference/rpc/latest/UserList#membership_life_span # Sets the membership life span to 30 days. user_list.membership_life_span = 30 response = user_list_service_client.mutate_user_lists( customer_id=customer_id, operations=[user_list_operation] ) user_list_resource_name = response.results[0].resource_name print( f"User list with resource name '{user_list_resource_name}' was created." ) return user_list_resource_name def add_users_to_customer_match_user_list(self, customer_id, maid_ids, user_list_resource_name, run_job, offline_user_data_job_id, ad_user_data_consent, ad_personalization_consent, ): offline_user_data_job_service_client = self.client.get_service( "OfflineUserDataJobService" ) if offline_user_data_job_id: # Reuses the specified offline user data job. offline_user_data_job_resource_name = ( offline_user_data_job_service_client.offline_user_data_job_path( customer_id, offline_user_data_job_id ) ) else: # Creates a new offline user data job. offline_user_data_job = self.client.get_type("OfflineUserDataJob") offline_user_data_job.type_ = ( self.client.enums.OfflineUserDataJobTypeEnum.CUSTOMER_MATCH_USER_LIST ) offline_user_data_job.customer_match_user_list_metadata.user_list = ( user_list_resource_name ) # Specifies whether user consent was obtained for the data you are # uploading. For more details, see: # https://www.google.com/about/company/user-consent-policy if ad_user_data_consent: offline_user_data_job.customer_match_user_list_metadata.consent.ad_user_data = self.client.enums.ConsentStatusEnum[ ad_user_data_consent ] if ad_personalization_consent: offline_user_data_job.customer_match_user_list_metadata.consent.ad_personalization = self.client.enums.ConsentStatusEnum[ ad_personalization_consent ] # Issues a request to create an offline user data job. create_offline_user_data_job_response = ( offline_user_data_job_service_client.create_offline_user_data_job( customer_id=customer_id, job=offline_user_data_job ) ) offline_user_data_job_resource_name = ( create_offline_user_data_job_response.resource_name ) print( "Created an offline user data job with resource name: " f"'{offline_user_data_job_resource_name}'." ) # Issues a request to add the operations to the offline user data job. # Best Practice: This example only adds a few operations, so it only sends # one AddOfflineUserDataJobOperations request. If your application is adding # a large number of operations, split the operations into batches and send # multiple AddOfflineUserDataJobOperations requests for the SAME job. See # https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations # and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data # for more information on the per-request limits. request = self.client.get_type( "AddOfflineUserDataJobOperationsRequest") request.resource_name = offline_user_data_job_resource_name request.operations = self.build_offline_user_data_job_operations( maid_ids) request.enable_partial_failure = True # Issues a request to add the operations to the offline user data job. response = offline_user_data_job_service_client.add_offline_user_data_job_operations( request=request ) # Prints the status message if any partial failure error is returned. # Note: the details of each partial failure error are not printed here. # Refer to the error_handling/handle_partial_failure.py example to learn # more. # Extracts the partial failure from the response status. partial_failure = getattr(response, "partial_failure_error", None) if getattr(partial_failure, "code", None) != 0: error_details = getattr(partial_failure, "details", []) for error_detail in error_details: failure_message = self.client.get_type("GoogleAdsFailure") # Retrieve the class definition of the GoogleAdsFailure instance # in order to use the "deserialize" class method to parse the # error_detail string into a protobuf message object. failure_object = type(failure_message).deserialize( error_detail.value ) for error in failure_object.errors: print( "A partial failure at index " f"{error.location.field_path_elements[0].index} occurred.\n" f"Error message: {error.message}\n" f"Error code: {error.error_code}" ) print("The operations are added to the offline user data job.") if not run_job: print( "Not running offline user data job " f"'{offline_user_data_job_resource_name}', as requested." ) return # Issues a request to run the offline user data job for executing all # added operations. offline_user_data_job_service_client.run_offline_user_data_job( resource_name=offline_user_data_job_resource_name ) # Retrieves and displays the job status. self.check_job_status(customer_id, offline_user_data_job_resource_name) # [END add_customer_match_user_list] # [START add_customer_match_user_list_2] def build_offline_user_data_job_operations(self, maid_ids): """Creates a raw input list of unhashed user information. Each element of the list represents a single user and is a dict containing a separate entry for the keys "email", "phone", "first_name", "last_name", "country_code", and "postal_code". In your application, this data might come from a file or a database. Args: client: The Google Ads client. Returns: A list containing the operations. """ # The first user data has an email address and a phone number. raw_records = [] for maid_id in maid_ids: raw_record = { "third_party_user_id": maid_id } # Adds the raw records to a raw input list. raw_records.append(raw_record) operations = [] # Iterates over the raw input list and creates a UserData object for each # record. for record in raw_records: # Creates a UserData object that represents a member of the user list. user_data = self.client.get_type("UserData") # Checks if the record has email, phone, or address information, and # adds a SEPARATE UserIdentifier object for each one found. For example, # a record with an email address and a phone number will result in a # UserData with two UserIdentifiers. # IMPORTANT: Since the identifier attribute of UserIdentifier # (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) # is a oneof # (https://protobuf.dev/programming-guides/proto3/#oneof-features), you # must set only ONE of hashed_email, hashed_phone_number, mobile_id, # third_party_user_id, or address-info. Setting more than one of these # attributes on the same UserIdentifier will clear all the other members # of the oneof. For example, the following code is INCORRECT and will # result in a UserIdentifier with ONLY a hashed_phone_number: # incorrect_user_identifier = client.get_type("UserIdentifier") # incorrect_user_identifier.hashed_email = "..." # incorrect_user_identifier.hashed_phone_number = "..." # The separate 'if' statements below demonstrate the correct approach # for creating a UserData object for a member with multiple # UserIdentifiers. # Checks if the record has an email address, and if so, adds a # UserIdentifier for it. user_identifier = self.client.get_type("UserIdentifier") user_identifier.third_party_user_id = record["third_party_user_id"] user_data.user_identifiers.append(user_identifier) # If the user_identifiers repeated field is not empty, create a new # OfflineUserDataJobOperation and add the UserData to it. if user_data.user_identifiers: operation = self.client.get_type("OfflineUserDataJobOperation") operation.create = user_data operations.append(operation) # [END add_customer_match_user_list_2] return operations # [START add_customer_match_user_list_4] def check_job_status(self, customer_id, offline_user_data_job_resource_name): """Retrieves, checks, and prints the status of the offline user data job. If the job is completed successfully, information about the user list is printed. Otherwise, a GAQL query will be printed, which can be used to check the job status at a later date. Offline user data jobs may take 6 hours or more to complete, so checking the status periodically, instead of waiting, can be more efficient. Args: client: The Google Ads client. customer_id: The ID for the customer that owns the user list. offline_user_data_job_resource_name: The resource name of the offline user data job to get the status of. """ query = f""" SELECT offline_user_data_job.resource_name, offline_user_data_job.id, offline_user_data_job.status, offline_user_data_job.type, offline_user_data_job.failure_reason, offline_user_data_job.customer_match_user_list_metadata.user_list FROM offline_user_data_job WHERE offline_user_data_job.resource_name = '{offline_user_data_job_resource_name}' LIMIT 1""" # Issues a search request using streaming. google_ads_service = self.client.get_service("GoogleAdsService") results = google_ads_service.search( customer_id=customer_id, query=query) offline_user_data_job = next(iter(results)).offline_user_data_job status_name = offline_user_data_job.status.name user_list_resource_name = ( offline_user_data_job.customer_match_user_list_metadata.user_list ) print( f"Offline user data job ID '{offline_user_data_job.id}' with type " f"'{offline_user_data_job.type_.name}' has status: {status_name}" ) if status_name == "SUCCESS": self.print_customer_match_user_list_info( customer_id, user_list_resource_name ) elif status_name == "FAILED": print(f"\tFailure Reason: {offline_user_data_job.failure_reason}") elif status_name in ("PENDING", "RUNNING"): print( "To check the status of the job periodically, use the following " f"GAQL query with GoogleAdsService.Search: {query}" ) # [END add_customer_match_user_list_4] def print_customer_match_user_list_info(self, customer_id, user_list_resource_name ): """Prints information about the Customer Match user list. Args: client: The Google Ads client. customer_id: The ID for the customer that owns the user list. user_list_resource_name: The resource name of the user list to which to add users. """ # [START add_customer_match_user_list_5] googleads_service_client = self.client.get_service("GoogleAdsService") # Creates a query that retrieves the user list. query = f""" SELECT user_list.size_for_display, user_list.size_for_search FROM user_list WHERE user_list.resource_name = '{user_list_resource_name}'""" # Issues a search request. search_results = googleads_service_client.search( customer_id=customer_id, query=query ) # [END add_customer_match_user_list_5] # Prints out some information about the user list. user_list = next(iter(search_results)).user_list print( "The estimated number of users that the user list " f"'{user_list.resource_name}' has is " f"{user_list.size_for_display} for Display and " f"{user_list.size_for_search} for Search." ) print( "Reminder: It may take several hours for the user list to be " "populated. Estimates of size zero are possible." ) def add_userlist(self, customer_id, name, maid_ids, run_job=False, user_list_id=None, offline_user_data_job_id=None, ad_user_data_consent=None, ad_personalization_consent=None, ): # run_job # "If true, runs the OfflineUserDataJob after adding operations. " # "The default value is False." # user_list_id # "The ID of an existing user list. If not specified, this example " # "will create a new user list." # offline job id # "The ID of an existing OfflineUserDataJob in the PENDING state. If " # "not specified, this example will create a new job." # ad_user_consent # "The data consent status for ad user data for all members in " # "the job." # ad_personalization_consent # "The personalization consent status for ad user data for all " # "members in the job." try: return self.main( customer_id, name, maid_ids, run_job, user_list_id, offline_user_data_job_id, ad_user_data_consent, ad_personalization_consent, ) 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}") def get_userlist(self, id): googleads_service = self.client.get_service("GoogleAdsService") query = f""" SELECT user_list.id, user_list.name FROM user_list """ search_response = googleads_service.search( customer_id=id, query=query ) data = [] for res in search_response: data.append({"name": res.user_list.name, "id": res.user_list.id}) return data