Java
// 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. package com.google.ads.googleads.examples.remarketing; import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime; import com.beust.jcommander.Parameter; import com.google.ads.googleads.examples.utils.ArgumentNames; import com.google.ads.googleads.examples.utils.CodeSampleParams; import com.google.ads.googleads.lib.GoogleAdsClient; import com.google.ads.googleads.v12.common.CombinedRuleUserListInfo; import com.google.ads.googleads.v12.common.RuleBasedUserListInfo; import com.google.ads.googleads.v12.common.UserListRuleInfo; import com.google.ads.googleads.v12.common.UserListRuleItemGroupInfo; import com.google.ads.googleads.v12.common.UserListRuleItemInfo; import com.google.ads.googleads.v12.common.UserListStringRuleItemInfo; import com.google.ads.googleads.v12.enums.UserListCombinedRuleOperatorEnum.UserListCombinedRuleOperator; import com.google.ads.googleads.v12.enums.UserListMembershipStatusEnum.UserListMembershipStatus; import com.google.ads.googleads.v12.enums.UserListPrepopulationStatusEnum.UserListPrepopulationStatus; import com.google.ads.googleads.v12.enums.UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator; import com.google.ads.googleads.v12.errors.GoogleAdsError; import com.google.ads.googleads.v12.errors.GoogleAdsException; import com.google.ads.googleads.v12.resources.UserList; import com.google.ads.googleads.v12.services.MutateUserListsResponse; import com.google.ads.googleads.v12.services.UserListOperation; import com.google.ads.googleads.v12.services.UserListServiceClient; import com.google.common.collect.ImmutableList; import java.io.FileNotFoundException; import java.io.IOException; /** * Creates a rule-based user list defined by a combination of rules for users who have visited two * different pages of a website. */ public class AddCombinedRuleUserList { private static class AddCombinedRuleUserListParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true) private Long customerId; } public static void main(String[] args) { AddCombinedRuleUserListParams params = new AddCombinedRuleUserListParams(); if (!params.parseArguments(args)) { // Either pass the required parameters for this example on the command line, or insert them // into the code here. See the parameter class definition above for descriptions. params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE"); } GoogleAdsClient googleAdsClient = null; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); System.exit(1); } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); System.exit(1); } try { new AddCombinedRuleUserList().runExample(googleAdsClient, params.customerId); } catch (GoogleAdsException gae) { // GoogleAdsException is the base class for most exceptions thrown by an API request. // Instances of this exception have a message and a GoogleAdsFailure that contains a // collection of GoogleAdsErrors that indicate the underlying causes of the // GoogleAdsException. System.err.printf( "Request ID %s failed due to GoogleAdsException. Underlying errors:%n", gae.getRequestId()); int i = 0; for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) { System.err.printf(" Error %d: %s%n", i++, googleAdsError); } System.exit(1); } } /** * Runs the example. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private void runExample(GoogleAdsClient googleAdsClient, long customerId) { String urlString = "url__"; // Creates a rule targeting any user that visited a url that equals // http://example.com/example1'. UserListRuleItemInfo userVisitedSite1Rule = UserListRuleItemInfo.newBuilder() // Uses a built-in parameter to create a domain URL rule. .setName(urlString) .setStringRuleItem( UserListStringRuleItemInfo.newBuilder() .setOperator(UserListStringRuleItemOperator.EQUALS) .setValue("http://example.com/example1") .build()) .build(); // Creates a UserListRuleInfo object containing the first rule. UserListRuleInfo userVisitedSite1RuleInfo = UserListRuleInfo.newBuilder() .addRuleItemGroups( UserListRuleItemGroupInfo.newBuilder().addRuleItems(userVisitedSite1Rule).build()) .build(); // Creates a rule targeting any user that visited a url that equals // http://example.com/example2'. UserListRuleItemInfo userVisitedSite2Rule = UserListRuleItemInfo.newBuilder() // Uses a built-in parameter to create a domain URL rule. .setName(urlString) .setStringRuleItem( UserListStringRuleItemInfo.newBuilder() .setOperator(UserListStringRuleItemOperator.EQUALS) .setValue("http://example.com/example2") .build()) .build(); // Creates a UserListRuleInfo object containing the second rule. UserListRuleInfo userVisitedSite2RuleInfo = UserListRuleInfo.newBuilder() .addRuleItemGroups( UserListRuleItemGroupInfo.newBuilder().addRuleItems(userVisitedSite2Rule).build()) .build(); // Creates the user list where "Visitors of a page who did visit another page". To create a user // list where "Visitors of a page who did not visit another page", change the // UserListCombinedRuleOperator from AND to AND_NOT. CombinedRuleUserListInfo combinedRuleUserListInfo = CombinedRuleUserListInfo.newBuilder() .setLeftOperand(userVisitedSite1RuleInfo) .setRightOperand(userVisitedSite2RuleInfo) .setRuleOperator(UserListCombinedRuleOperator.AND) .build(); // Defines a representation of a user list that is generated by a rule. RuleBasedUserListInfo ruleBasedUserListInfo = RuleBasedUserListInfo.newBuilder() // Optional: To include past users in the user list, set the prepopulation_status to // REQUESTED. .setPrepopulationStatus(UserListPrepopulationStatus.REQUESTED) .setCombinedRuleUserList(combinedRuleUserListInfo) .build(); // Creates a user list. UserList userList = UserList.newBuilder() .setName( "All visitors to http://example.com/example1 AND http://example.com/example2 #" + getPrintableDateTime()) .setDescription( "Visitors of both http://example.com/example1 AND http://example.com/example2") .setMembershipStatus(UserListMembershipStatus.OPEN) .setMembershipLifeSpan(365) .setRuleBasedUserList(ruleBasedUserListInfo) .build(); // Creates the operation. UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build(); // Creates the user list service client. try (UserListServiceClient userListServiceClient = googleAdsClient.getLatestVersion().createUserListServiceClient()) { // Adds the user list. MutateUserListsResponse response = userListServiceClient.mutateUserLists( Long.toString(customerId), ImmutableList.of(operation)); String userListResourceName = response.getResults(0).getResourceName(); // Prints the result. System.out.printf("Created user list with resource name '%s'.%n", userListResourceName); } } }
C#
// 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 // // http://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. using CommandLine; using Google.Ads.Gax.Examples; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V12.Common; using Google.Ads.GoogleAds.V12.Errors; using Google.Ads.GoogleAds.V12.Resources; using Google.Ads.GoogleAds.V12.Services; using System; using System.Collections.Generic; using System.Linq; using static Google.Ads.GoogleAds.V12.Enums.UserListCombinedRuleOperatorEnum.Types; using static Google.Ads.GoogleAds.V12.Enums.UserListMembershipStatusEnum.Types; using static Google.Ads.GoogleAds.V12.Enums.UserListPrepopulationStatusEnum.Types; using static Google.Ads.GoogleAds.V12.Enums.UserListStringRuleItemOperatorEnum.Types; namespace Google.Ads.GoogleAds.Examples.V12 { /// <summary> /// This code example creates a rule-based user list defined by a combination of rules for users /// who have visited two different pages of a website. /// </summary> public class AddCombinedRuleUserList : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddCombinedRuleUserList"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID.")] public long CustomerId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = ExampleUtilities.ParseCommandLine<Options>(args); AddCombinedRuleUserList codeExample = new AddCombinedRuleUserList(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example creates a rule-based user list defined by a combination of rules " + "for users who have visited two different pages of a website."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID.</param> public void Run(GoogleAdsClient client, long customerId) { // Get the UserListServiceClient. UserListServiceClient userListServiceClient = client.GetService(Services.V12.UserListService); // Creates a rule targeting any user that visited a url that equals // 'http://example.com/example1'. UserListRuleInfo userVisitedSite1RuleInfo = BuildVisitedSiteRuleInfo("http://example.com/example1"); // Creates a rule targeting any user that visited a url that equals // 'http://example.com/example2'. UserListRuleInfo userVisitedSite2RuleInfo = BuildVisitedSiteRuleInfo("http://example.com/example2"); // Creates the user list where "Visitors of a page who did visit another page". // To create a user list where "Visitors of a page who did not visit another page", // change the UserListCombinedRuleOperator from .And to .AndNot. CombinedRuleUserListInfo combinedRuleUserListInfo = new CombinedRuleUserListInfo() { LeftOperand = userVisitedSite1RuleInfo, RightOperand = userVisitedSite2RuleInfo, RuleOperator = UserListCombinedRuleOperator.And }; // Defines a representation of a user list that is generated by a rule. RuleBasedUserListInfo ruleBasedUserListInfo = new RuleBasedUserListInfo() { // Optional: To include past users in the user list, set the prepopulation_status to // REQUESTED. PrepopulationStatus = UserListPrepopulationStatus.Requested, CombinedRuleUserList = combinedRuleUserListInfo }; // Creates a user list. UserList userList = new UserList() { Name = "All visitors to http://example.com/example1 AND " + $"http://example.com/example2 #{ExampleUtilities.GetShortRandomString()}", Description = "Visitors of both http://example.com/example1 AND " + "http://example.com/example2", MembershipStatus = UserListMembershipStatus.Open, MembershipLifeSpan = 365L, RuleBasedUserList = ruleBasedUserListInfo }; // Creates the operation. UserListOperation operation = new UserListOperation() { Create = userList }; try { // Adds the new user list and prints the result. MutateUserListsResponse response = userListServiceClient.MutateUserLists (customerId.ToString(), new[] { operation }); Console.WriteLine("Created user list with resource name:" + $"{response.Results.First().ResourceName}"); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Creates and returns a UserListRuleInfo object targeting a visit to a specified URL. /// </summary> /// <param name="url">The URL at which the rule will be targeted.</param> /// <returns>A populated UserListRuleInfo object.</returns> private UserListRuleInfo BuildVisitedSiteRuleInfo(string url) { // Creates a rule targeting any user that visited the specified URL. UserListRuleItemInfo userVisitedSiteRule = new UserListRuleItemInfo() { // Uses a built-in parameter to create a domain URL rule. Name = "url__", StringRuleItem = new UserListStringRuleItemInfo() { Operator = UserListStringRuleItemOperator.Equals, Value = url } }; // Creates a UserListRuleInfo object containing the new rule. UserListRuleInfo userVisitedSiteRuleInfo = new UserListRuleInfo() { RuleItemGroups = { new UserListRuleItemGroupInfo() { RuleItems = {userVisitedSiteRule} } } }; return userVisitedSiteRuleInfo; } } }
PHP
<?php /** * 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. */ namespace Google\Ads\GoogleAds\Examples\Remarketing; require __DIR__ . '/../../vendor/autoload.php'; use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Examples\Utils\Helper; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Lib\V12\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V12\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V12\GoogleAdsException; use Google\Ads\GoogleAds\V12\Common\CombinedRuleUserListInfo; use Google\Ads\GoogleAds\V12\Common\RuleBasedUserListInfo; use Google\Ads\GoogleAds\V12\Common\UserListRuleInfo; use Google\Ads\GoogleAds\V12\Common\UserListRuleItemGroupInfo; use Google\Ads\GoogleAds\V12\Common\UserListRuleItemInfo; use Google\Ads\GoogleAds\V12\Common\UserListStringRuleItemInfo; use Google\Ads\GoogleAds\V12\Enums\UserListCombinedRuleOperatorEnum\UserListCombinedRuleOperator; use Google\Ads\GoogleAds\V12\Enums\UserListMembershipStatusEnum\UserListMembershipStatus; use Google\Ads\GoogleAds\V12\Enums\UserListPrepopulationStatusEnum\UserListPrepopulationStatus; use Google\Ads\GoogleAds\V12\Enums\UserListStringRuleItemOperatorEnum\UserListStringRuleItemOperator; use Google\Ads\GoogleAds\V12\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V12\Resources\UserList; use Google\Ads\GoogleAds\V12\Services\UserListOperation; use Google\ApiCore\ApiException; /** * Creates a rule-based user list defined by a combination of rules for users who have visited two * different pages of a website. */ class AddCombinedRuleUserList { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; private const URL_STRING = 'url__'; public static function main() { // Either pass the required parameters for this example on the command line, or insert them // into the constants above. $options = (new ArgumentParser())->parseCommandArguments([ ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT ]); // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder()) ->fromFile() ->withOAuth2Credential($oAuth2Credential) ->build(); try { self::runExample( $googleAdsClient, $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID ); } catch (GoogleAdsException $googleAdsException) { printf( "Request with ID '%s' has failed.%sGoogle Ads failure details:%s", $googleAdsException->getRequestId(), PHP_EOL, PHP_EOL ); foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) { /** @var GoogleAdsError $error */ printf( "\t%s: %s%s", $error->getErrorCode()->getErrorCode(), $error->getMessage(), PHP_EOL ); } exit(1); } catch (ApiException $apiException) { printf( "ApiException was thrown with message '%s'.%s", $apiException->getMessage(), PHP_EOL ); exit(1); } } /** * Runs the example. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID */ public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId ) { // Creates a rule targeting any user that visited a url that equals // http://example.com/example1'. $userVisitedSite1Rule = new UserListRuleItemInfo([ // Uses a built-in parameter to create a domain URL rule. 'name' => self::URL_STRING, 'string_rule_item' => new UserListStringRuleItemInfo([ 'operator' => UserListStringRuleItemOperator::EQUALS, 'value' => 'http://example.com/example1' ]) ]); // Creates a UserListRuleInfo object containing the first rule. $userVisitedSite1RuleInfo = new UserListRuleInfo([ 'rule_item_groups' => [ new UserListRuleItemGroupInfo([ 'rule_items' => [$userVisitedSite1Rule] ]) ] ]); // Creates a rule targeting any user that visited a url that equals // http://example.com/example2'. $userVisitedSite2Rule = new UserListRuleItemInfo([ // Uses a built-in parameter to create a domain URL rule. 'name' => self::URL_STRING, 'string_rule_item' => new UserListStringRuleItemInfo([ 'operator' => UserListStringRuleItemOperator::EQUALS, 'value' => 'http://example.com/example2' ]) ]); // Creates a UserListRuleInfo object containing the second rule. $userVisitedSite2RuleInfo = new UserListRuleInfo([ 'rule_item_groups' => [ new UserListRuleItemGroupInfo([ 'rule_items' => [$userVisitedSite2Rule] ]) ] ]); // Creates the user list where "Visitors of a page who did visit another page". To create a // user list where "Visitors of a page who did not visit another page", change the // UserListCombinedRuleOperator from PBAND to AND_NOT. $combinedRuleUserListInfo = new CombinedRuleUserListInfo([ 'left_operand' => $userVisitedSite1RuleInfo, 'right_operand' => $userVisitedSite2RuleInfo, 'rule_operator' => UserListCombinedRuleOperator::PBAND ]); // Defines a representation of a user list that is generated by a rule. $ruleBasedUserListInfo = new RuleBasedUserListInfo([ // Optional: To include past users in the user list, set the prepopulation_status to // REQUESTED. 'prepopulation_status' => UserListPrepopulationStatus::REQUESTED, 'combined_rule_user_list' => $combinedRuleUserListInfo ]); // Creates a user list. $userList = new UserList([ 'name' => 'All visitors to http://example.com/example1 AND ' . 'http://example.com/example2 #' . Helper::getPrintableDatetime(), 'description' => 'Visitors of both http://example.com/example1 AND ' . 'http://example.com/example2', 'membership_status' => UserListMembershipStatus::OPEN, 'membership_life_span' => 365, 'rule_based_user_list' => $ruleBasedUserListInfo ]); // Creates the operation. $operation = new UserListOperation(); $operation->setCreate($userList); // Issues a mutate request to add the user list and prints some information. $userListServiceClient = $googleAdsClient->getUserListServiceClient(); $response = $userListServiceClient->mutateUserLists($customerId, [$operation]); printf( "Created user list with resource name '%s'.%s", $response->getResults()[0]->getResourceName(), PHP_EOL ); } } AddCombinedRuleUserList::main();
Python
#!/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. """Creates a rule-based user list. The list will be defined by a combination of rules for users who have visited two different pages of a website. """ import argparse 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): """Creates a rule-based user list. The list will be defined by a combination of rules for users who have visited two different pages of a website. Args: client: The Google Ads client. customer_id: The customer ID for which to add the user list. """ # Get the UserListService client. user_list_service = client.get_service("UserListService") rule_infos = [] # Create rules targeting any user that visits "http://example.com/example1" # and "http://example.com/example2". for url in ["http://example.com/example1", "http://example.com/example2"]: rule_infos.append(build_visited_site_rule_info(client, url)) # The two rules are combined by joining the first AND second URLs. See # https://developers.google.com/google-ads/api/reference/rpc/latest/CombinedRuleUserListInfo # for more details. # This rule will create a user list where "Visitors of a page who did visit # another page". To create a user list where "Visitors of a page who did not # visit another page", change the UserListCombinedRuleOperator from AND to # AND_NOT. combined_rule_user_list_info = client.get_type("CombinedRuleUserListInfo") client.copy_from(combined_rule_user_list_info.left_operand, rule_infos[0]) client.copy_from(combined_rule_user_list_info.right_operand, rule_infos[1]) combined_rule_user_list_info.rule_operator = ( client.enums.UserListCombinedRuleOperatorEnum.AND ) # Define a representation of a user list that is generated by a rule. rule_based_user_list_info = client.get_type("RuleBasedUserListInfo") # Optional: To include past users in the user list, set the # prepopulation_status to REQUESTED. rule_based_user_list_info.prepopulation_status = ( client.enums.UserListPrepopulationStatusEnum.REQUESTED ) client.copy_from( rule_based_user_list_info.combined_rule_user_list, combined_rule_user_list_info, ) # Create a UserListOperation and populate the UserList. user_list_operation = client.get_type("UserListOperation") user_list = user_list_operation.create user_list.name = ( "All visitors to http://example.com/example1 AND " f"http://example.com/example2 #{uuid4()}" ) user_list.description = ( "Visitors of both http://example.com/example1 AND " "http://example.com/example2" ) user_list.membership_status = client.enums.UserListMembershipStatusEnum.OPEN user_list.membership_life_span = 365 client.copy_from(user_list.rule_based_user_list, rule_based_user_list_info) # Issue a mutate request to add the user list, then print the results. response = user_list_service.mutate_user_lists( customer_id=customer_id, operations=[user_list_operation] ) print( "Created combined user list with resource name " f"'{response.results[0].resource_name}.'" ) def build_visited_site_rule_info(client, url): """Creates a UserListRuleInfo object targeting a visit to a specified URL. Args: client: An initialized Google Ads client. url: The string URL at which the rule will be targeted. Returns: A populated UserListRuleInfo object. """ user_visited_site_rule = client.get_type("UserListRuleItemInfo") # Use a built-in parameter to create a domain URL rule. user_visited_site_rule.name = "url__" user_visited_site_rule.string_rule_item.operator = ( client.enums.UserListStringRuleItemOperatorEnum.EQUALS ) user_visited_site_rule.string_rule_item.value = url user_visited_site_rule_info = client.get_type("UserListRuleInfo") rule_item_group_info = client.get_type("UserListRuleItemGroupInfo") rule_item_group_info.rule_items.append(user_visited_site_rule) user_visited_site_rule_info.rule_item_groups.append(rule_item_group_info) return user_visited_site_rule_info 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="v12") parser = argparse.ArgumentParser( description="Creates a combination user list containing users that are " "present on any one of the provided user lists." ) # 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.", ) args = parser.parse_args() try: main(googleads_client, args.customer_id) 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)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # 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. # # Creates a rule-based user list defined by a combination of rules for users who # have visited two different pages of a website. require 'optparse' require 'google/ads/google_ads' require 'date' def add_combined_rule_user_list(customer_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new # Creates a user list. operation = client.operation.create_resource.user_list do |u| u.name = "All visitors to http://example.com/example1 AND " \ "http://example.com/example2 ##{(Time.new.to_f * 1000).to_i}" u.description = "Visitors of both http://example.com/example1 AND " \ "http://example.com/example2" u.membership_status = :OPEN u.membership_life_span = 365 # Defines a representation of a user list that is generated by a rule. u.rule_based_user_list = client.resource.rule_based_user_list_info do |r| # Optional: To include past users in the user list, set the # prepopulation_status to REQUESTED. r.prepopulation_status = :REQUESTED # Creates the user list where "Visitors of a page who did visit another # page". To create a user list where "Visitors of a page who did not visit # another page", change the rule_operator from AND to AND_NOT. r.combined_rule_user_list = client.resource.combined_rule_user_list_info do |c| # Creates a UserListRuleInfo object containing the first rule. c.left_operand = client.resource.user_list_rule_info do |rule| rule.rule_item_groups << client.resource.user_list_rule_item_group_info do |group| # Creates a rule targeting any user that visited a url that equals # 'http://example.com/example1'. group.rule_items << client.resource.user_list_rule_item_info do |item| # Uses a built-in parameter to create a domain URL rule. item.name = URL_STRING item.string_rule_item = client.resource.user_list_string_rule_item_info do |string_rule| string_rule.operator = :EQUALS string_rule.value = "http://example.com/example1" end end end end # Creates a UserListRuleInfo object containing the second rule. c.right_operand = client.resource.user_list_rule_info do |rule| rule.rule_item_groups << client.resource.user_list_rule_item_group_info do |group| # Creates a rule targeting any user that visited a url that equals # 'http://example.com/example2'. group.rule_items << client.resource.user_list_rule_item_info do |item| # Uses a built-in parameter to create a domain URL rule. item.name = URL_STRING item.string_rule_item = client.resource.user_list_string_rule_item_info do |string_rule| string_rule.operator = :EQUALS string_rule.value = "http://example.com/example2" end end end end c.rule_operator = :AND end end end # Issues a mutate request to add the user list and prints some information. response = client.service.user_list.mutate_user_lists( customer_id: customer_id, operations: [operation], ) puts "Created user list with resource name " \ "#{response.results.first.resource_name}" end if __FILE__ == $0 URL_STRING = "url__" options = {} # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' OptionParser.new do |opts| opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__)) opts.separator '' opts.separator 'Options:' opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v| options[:customer_id] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin add_combined_rule_user_list(options.fetch(:customer_id).tr("-", "")) rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e e.failure.errors.each do |error| STDERR.printf("Error with message: %s\n", error.message) if error.location error.location.field_path_elements.each do |field_path_element| STDERR.printf("\tOn field: %s\n", field_path_element.field_name) end end error.error_code.to_h.each do |k, v| next if v == :UNSPECIFIED STDERR.printf("\tType: %s\n\tCode: %s\n", k, v) end end raise end end
Perl
#!/usr/bin/perl -w # # 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 # # http://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. # # Creates a rule-based user list defined by a combination of rules for users who # have visited two different pages of a website. use strict; use warnings; use utf8; use FindBin qw($Bin); use lib "$Bin/../../lib"; use Google::Ads::GoogleAds::Client; use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; use Google::Ads::GoogleAds::V12::Resources::UserList; use Google::Ads::GoogleAds::V12::Common::UserListRuleItemInfo; use Google::Ads::GoogleAds::V12::Common::UserListStringRuleItemInfo; use Google::Ads::GoogleAds::V12::Common::UserListRuleInfo; use Google::Ads::GoogleAds::V12::Common::UserListRuleItemGroupInfo; use Google::Ads::GoogleAds::V12::Common::CombinedRuleUserListInfo; use Google::Ads::GoogleAds::V12::Common::RuleBasedUserListInfo; use Google::Ads::GoogleAds::V12::Enums::UserListStringRuleItemOperatorEnum qw(EQUALS); use Google::Ads::GoogleAds::V12::Enums::UserListCombinedRuleOperatorEnum qw(AND); use Google::Ads::GoogleAds::V12::Enums::UserListPrepopulationStatusEnum qw(REQUESTED); use Google::Ads::GoogleAds::V12::Enums::UserListMembershipStatusEnum qw(OPEN); use Google::Ads::GoogleAds::V12::Services::UserListService::UserListOperation; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); use Data::Uniqid qw(uniqid); use constant URL_STRING => "url__"; # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. my $customer_id = "INSERT_CUSTOMER_ID_HERE"; sub add_combined_rule_user_list { my ($api_client, $customer_id) = @_; # Create a rule targeting any user that visited a URL that equals # 'http://example.com/example1'. my $user_visited_site1_rule = Google::Ads::GoogleAds::V12::Common::UserListRuleItemInfo->new({ # Use a built-in parameter to create a domain URL rule. name => URL_STRING, stringRuleItem => Google::Ads::GoogleAds::V12::Common::UserListStringRuleItemInfo->new({ operator => EQUALS, value => "http://example.com/example1" })}); # Create a UserListRuleInfo object containing the first rule. my $user_visited_site1_rule_info = Google::Ads::GoogleAds::V12::Common::UserListRuleInfo->new({ ruleItemGroups => Google::Ads::GoogleAds::V12::Common::UserListRuleItemGroupInfo->new({ ruleItems => [$user_visited_site1_rule]})}); # Create a rule targeting any user that visited a URL that equals # 'http://example.com/example2'. my $user_visited_site2_rule = Google::Ads::GoogleAds::V12::Common::UserListRuleItemInfo->new({ # Use a built-in parameter to create a domain URL rule. name => URL_STRING, stringRuleItem => Google::Ads::GoogleAds::V12::Common::UserListStringRuleItemInfo->new({ operator => EQUALS, value => "http://example.com/example2" })}); # Create a UserListRuleInfo object containing the second rule. my $user_visited_site2_rule_info = Google::Ads::GoogleAds::V12::Common::UserListRuleInfo->new({ ruleItemGroups => Google::Ads::GoogleAds::V12::Common::UserListRuleItemGroupInfo->new({ ruleItems => [$user_visited_site2_rule]})}); # Create the user list where "Visitors of a page who did visit another page". # To create a user list where "Visitors of a page who did not visit another page", # change the UserListCombinedRuleOperator from AND to AND_NOT. my $combined_rule_user_list_info = Google::Ads::GoogleAds::V12::Common::CombinedRuleUserListInfo->new({ leftOperand => $user_visited_site1_rule_info, rightOperand => $user_visited_site2_rule_info, ruleOperator => AND }); # Define a representation of a user list that is generated by a rule. my $rule_based_user_list_info = Google::Ads::GoogleAds::V12::Common::RuleBasedUserListInfo->new({ # Optional: To include past users in the user list, set the prepopulationStatus # to REQUESTED. prepopulationStatus => REQUESTED, combinedRuleUserList => $combined_rule_user_list_info }); # Create a user list. my $user_list = Google::Ads::GoogleAds::V12::Resources::UserList->new({ name => "All visitors to http://example.com/example1 AND " . "http://example.com/example2 #" . uniqid(), description => "Visitors of both http://example.com/example1 AND " . "http://example.com/example2", membershipStatus => OPEN, membershipLifespan => 365, ruleBasedUserList => $rule_based_user_list_info }); # Create the operation. my $user_list_operation = Google::Ads::GoogleAds::V12::Services::UserListService::UserListOperation-> new({ create => $user_list }); # Issue a mutate request to add the user list and print some information. my $user_lists_response = $api_client->UserListService()->mutate({ customerId => $customer_id, operations => [$user_list_operation]}); printf "Created user list with resource name '%s'.\n", $user_lists_response->{results}[0]{resourceName}; return 1; } # Don't run the example if the file is being included. if (abs_path($0) ne abs_path(__FILE__)) { return 1; } # Get Google Ads Client, credentials will be read from ~/googleads.properties. my $api_client = Google::Ads::GoogleAds::Client->new(); # By default examples are set to die on any server returned fault. $api_client->set_die_on_faults(1); # Parameters passed on the command line will override any parameters set in code. GetOptions("customer_id=s" => \$customer_id); # Print the help message if the parameters are not initialized in the code nor # in the command line. pod2usage(2) if not check_params($customer_id); # Call the example. add_combined_rule_user_list($api_client, $customer_id =~ s/-//gr); =pod =head1 NAME add_combined_rule_user_list =head1 DESCRIPTION Creates a rule-based user list defined by a combination of rules for users who have visited two different pages of a website. =head1 SYNOPSIS add_combined_rule_user_list.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. =cut