式ルールのユーザーリストを追加

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.v11.common.ExpressionRuleUserListInfo;
import com.google.ads.googleads.v11.common.RuleBasedUserListInfo;
import com.google.ads.googleads.v11.common.UserListRuleInfo;
import com.google.ads.googleads.v11.common.UserListRuleItemGroupInfo;
import com.google.ads.googleads.v11.common.UserListRuleItemInfo;
import com.google.ads.googleads.v11.common.UserListStringRuleItemInfo;
import com.google.ads.googleads.v11.enums.UserListMembershipStatusEnum.UserListMembershipStatus;
import com.google.ads.googleads.v11.enums.UserListPrepopulationStatusEnum.UserListPrepopulationStatus;
import com.google.ads.googleads.v11.enums.UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator;
import com.google.ads.googleads.v11.errors.GoogleAdsError;
import com.google.ads.googleads.v11.errors.GoogleAdsException;
import com.google.ads.googleads.v11.resources.UserList;
import com.google.ads.googleads.v11.services.MutateUserListsResponse;
import com.google.ads.googleads.v11.services.UserListOperation;
import com.google.ads.googleads.v11.services.UserListServiceClient;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Creates a rule-based user list defined by an expression rule for users who have visited two
 * different sections of a website.
 */
public class AddExpressionRuleUserList {

  private static class AddExpressionRuleUserListParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;
  }

  public static void main(String[] args) {
    AddExpressionRuleUserListParams params = new AddExpressionRuleUserListParams();
    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 AddExpressionRuleUserList().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 contains 'example.com/section1'.
    UserListRuleItemInfo rule1 =
        UserListRuleItemInfo.newBuilder()
            // Uses a built-in parameter to create a domain URL rule.
            .setName(urlString)
            .setStringRuleItem(
                UserListStringRuleItemInfo.newBuilder()
                    .setOperator(UserListStringRuleItemOperator.CONTAINS)
                    .setValue("example.com/section1")
                    .build())
            .build();

    // Creates a rule targeting any user that visited a url that contains 'example.com/section2'.
    UserListRuleItemInfo rule2 =
        UserListRuleItemInfo.newBuilder()
            // Uses a built-in parameter to create a domain URL rule.
            .setName(urlString)
            .setStringRuleItem(
                UserListStringRuleItemInfo.newBuilder()
                    .setOperator(UserListStringRuleItemOperator.CONTAINS)
                    .setValue("example.com/section2")
                    .build())
            .build();

    // Creates an ExpressionRuleUserListInfo object, or a boolean rule that defines this user list.
    // The default rule_type for a UserListRuleInfo object is OR of ANDs (disjunctive normal form).
    // That is, rule items will be ANDed together within rule item groups and the groups themselves
    // will be ORed together.
    ExpressionRuleUserListInfo expressionRuleUserListInfo =
        ExpressionRuleUserListInfo.newBuilder()
            .setRule(
                UserListRuleInfo.newBuilder()
                    .addRuleItemGroups(
                        // Combine the two rule items into a UserListRuleItemGroupInfo object so
                        // Google Ads will AND their rules together. To instead OR the rules
                        // together, each rule should be placed in its own rule item group.
                        UserListRuleItemGroupInfo.newBuilder()
                            .addAllRuleItems(ImmutableList.of(rule1, rule2))
                            .build())
                    .build())
            .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)
            .setExpressionRuleUserList(expressionRuleUserListInfo)
            .build();

    // Creates a user list.
    UserList userList =
        UserList.newBuilder()
            .setName(
                "All visitors to example.com/section1 AND example.com/section2 #"
                    + getPrintableDateTime())
            .setDescription("Visitors of both example.com/section1 AND example.com/section2")
            .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.V11.Common;
using Google.Ads.GoogleAds.V11.Errors;
using Google.Ads.GoogleAds.V11.Resources;
using Google.Ads.GoogleAds.V11.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V11.Enums.UserListMembershipStatusEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.UserListPrepopulationStatusEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.UserListStringRuleItemOperatorEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V11
{
    /// <summary>
    /// This code example creates a rule-based user list defined by an expression rule for users who
    /// have visited two different sections of a website.
    /// </summary>
    public class AddExpressionRuleUserList : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddExpressionRuleUserList"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID to which the new user list will be added.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID to which the new user list will be added.")]
            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);

            AddExpressionRuleUserList codeExample = new AddExpressionRuleUserList();
            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 an expression rule for " +
            "users who have visited two different sections 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 to which the new user list will be
        ///     added.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Gets the UserListService.
            UserListServiceClient userListServiceClient =
                client.GetService(Services.V11.UserListService);

            // Creates the user targeting rules for each URL.
            UserListRuleItemInfo rule1 = BuildVisitedSiteRuleInfo("example.com/section1");
            UserListRuleItemInfo rule2 = BuildVisitedSiteRuleInfo("example.com/section2");

            // Combine the two rule items into a UserListRuleItemGroupInfo object so Google Ads will
            // AND their rules together. To instead OR the rules together, each rule should be
            // placed in its own rule item group.
            UserListRuleItemGroupInfo userListRuleItemGroupInfo = new UserListRuleItemGroupInfo();
            userListRuleItemGroupInfo.RuleItems.Add(rule1);
            userListRuleItemGroupInfo.RuleItems.Add(rule2);

            UserListRuleInfo userListRuleInfo = new UserListRuleInfo();
            userListRuleInfo.RuleItemGroups.Add(userListRuleItemGroupInfo);

            // Creates an ExpressionRuleUserListInfo object, or a boolean rule that defines this
            // user list. The default rule_type for a UserListRuleInfo object is OR of ANDs
            // (disjunctive normal form). That is, rule items will be ANDed together within rule
            // item groups and the groups themselves will be ORed together.
            ExpressionRuleUserListInfo expressionRuleUserListInfo = new ExpressionRuleUserListInfo
            {
                Rule = userListRuleInfo
            };

            // 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,
                ExpressionRuleUserList = expressionRuleUserListInfo
            };

            // Creates a new user list.
            UserList userList = new UserList
            {
                Name = "All visitors to example.com/section1 AND example.com/section2 " +
                       $"#{ExampleUtilities.GetRandomString()}",
                Description = "Visitors of both example.com/section1 AND example.com/section2",
                MembershipStatus = UserListMembershipStatus.Open,
                MembershipLifeSpan = 365L,
                RuleBasedUserList = ruleBasedUserListInfo
            };

            // Creates the operation.
            UserListOperation operation = new UserListOperation()
            {
                Create = userList
            };

            try
            {
                // Adds the user list.
                MutateUserListsResponse response = userListServiceClient.MutateUserLists
                    (customerId.ToString(), new[] { operation });

                // Displays the results.
                Console.WriteLine("Created new 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 UserListRuleItemInfo object targeting a visit to a specified URL.
        /// </summary>
        /// <param name="url">The URL at which the rule will target users.</param>
        /// <returns>A populated UserListRuleItemInfo object.</returns>
        private UserListRuleItemInfo 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.Contains,
                    Value = url
                }
            };

            return userVisitedSiteRule;
        }
    }
}

      

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\V11\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsException;
use Google\Ads\GoogleAds\V11\Common\ExpressionRuleUserListInfo;
use Google\Ads\GoogleAds\V11\Common\RuleBasedUserListInfo;
use Google\Ads\GoogleAds\V11\Common\UserListRuleInfo;
use Google\Ads\GoogleAds\V11\Common\UserListRuleItemGroupInfo;
use Google\Ads\GoogleAds\V11\Common\UserListRuleItemInfo;
use Google\Ads\GoogleAds\V11\Common\UserListStringRuleItemInfo;
use Google\Ads\GoogleAds\V11\Enums\UserListMembershipStatusEnum\UserListMembershipStatus;
use Google\Ads\GoogleAds\V11\Enums\UserListPrepopulationStatusEnum\UserListPrepopulationStatus;
use Google\Ads\GoogleAds\V11\Enums\UserListStringRuleItemOperatorEnum\UserListStringRuleItemOperator;
use Google\Ads\GoogleAds\V11\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V11\Resources\UserList;
use Google\Ads\GoogleAds\V11\Services\UserListOperation;
use Google\ApiCore\ApiException;

/**
 * Creates a rule-based user list defined by an expression rule for users who have visited two
 * different sections of a website.
 */
class AddExpressionRuleUserList
{
    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 contains
        // 'example.com/section1'.
        $rule1 = new UserListRuleItemInfo([
            // Uses a built-in parameter to create a domain URL rule.
            'name' => self::URL_STRING,
            'string_rule_item' => new UserListStringRuleItemInfo([
                'operator' => UserListStringRuleItemOperator::CONTAINS,
                'value' => 'example.com/section1'
            ])
        ]);

        // Creates a rule targeting any user that visited a url that contains
        // 'example.com/section2'.
        $rule2 = new UserListRuleItemInfo([
            // Uses a built-in parameter to create a domain URL rule.
            'name' => self::URL_STRING,
            'string_rule_item' => new UserListStringRuleItemInfo([
                'operator' => UserListStringRuleItemOperator::CONTAINS,
                'value' => 'example.com/section2'
            ])
        ]);

        // Creates an ExpressionRuleUserListInfo object, or a boolean rule that defines this user
        // list. The default rule_type for a UserListRuleInfo object is OR of ANDs (disjunctive
        // normal form). That is, rule items will be ANDed together within rule item groups and
        // the groups themselves will be ORed together.
        $expressionRuleUserListInfo = new ExpressionRuleUserListInfo([
            'rule' => new UserListRuleInfo([
                'rule_item_groups' => [
                    // Combines the two rule items into a UserListRuleItemGroupInfo object so
                    // Google Ads will AND their rules together. To instead OR the rules
                    // together, each rule should be placed in its own rule item group.
                    new UserListRuleItemGroupInfo([
                        'rule_items' => [$rule1, $rule2]
                    ])
                ]
            ])
        ]);

        // 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,
            'expression_rule_user_list' => $expressionRuleUserListInfo
        ]);

        // Creates a user list.
        $userList = new UserList([
            'name' => 'All visitors to example.com/section1 AND example.com/section2 #' .
                Helper::getPrintableDatetime(),
            'description' => 'Visitors of both example.com/section1 AND example.com/section2',
            '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
        );
    }
}

AddExpressionRuleUserList::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 an expression rule 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

URL_LIST = ["http://example.com/section1", "http://example.com/section2"]


def main(client, customer_id):
    """Creates a rule-based user list.

    The list will be defined by an expression rule 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")

    user_list_rule_info = client.get_type("UserListRuleInfo")

    # Combine the two rule items into a UserListRuleItemGroupInfo object so
    # Google Ads will AND their rules together. To instead OR the rules
    # together, each rule should be placed in its own rule item group.
    user_list_rule_item_group_info = client.get_type(
        "UserListRuleItemGroupInfo"
    )

    # Create rules targeting any user that visits the URLs in URL_LIST.
    for url in URL_LIST:
        user_list_rule_item_group_info.rule_items.append(
            _build_visited_site_rule_info(client, url)
        )
    user_list_rule_info.rule_item_groups.append(user_list_rule_item_group_info)

    # Creates an ExpressionRuleUserListInfo object, or a boolean rule that
    # defines this user list. The default rule_type for a UserListRuleInfo
    # object is OR of ANDs (disjunctive normal form). That is, rule items will
    # be ANDed together within rule item groups and the groups themselves will
    # be ORed together.
    expression_rule_user_list_info = client.get_type(
        "ExpressionRuleUserListInfo"
    )
    client.copy_from(expression_rule_user_list_info.rule, user_list_rule_info)

    # 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.expression_rule_user_list,
        expression_rule_user_list_info,
    )

    # Create a UserListOperation and populate the UserList.
    user_list_operation = client.get_type("UserListOperation")
    user_list = user_list_operation.create
    joined_urls = " AND ".join(URL_LIST)
    user_list.name = f"All visitors to {joined_urls} #{uuid4()}"
    user_list.description = f"Visitors of {joined_urls}"
    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 expression rule user list with resource name "
        f"'{response.results[0].resource_name}.'"
    )


def _build_visited_site_rule_info(client, url):
    """Creates a UserListRuleItemInfo object targeting a visit to a given URL.

    Args:
        client: An initialized Google Ads client.
        url: The URL at which the rule will be targeted.
    Returns:
        A populated UserListRuleItemInfo 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.CONTAINS
    )
    user_visited_site_rule.string_rule_item.value = url

    return user_visited_site_rule


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="v11")

    parser = argparse.ArgumentParser(
        description="Creates a rule-based user list defined by an expression "
        "rule for users who have visited two different sections of a website."
    )
    # 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 an expression rule for users who
# have visited two different sections of a website.

require 'optparse'
require 'google/ads/google_ads'
require 'date'

def add_expression_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 example.com/section1 AND example.com/section2 #" \
      "#{(Time.new.to_f * 1000).to_i}"
    u.description = "Visitors of both example.com/section1 AND " \
      "example.com/section2"
    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 an ExpressionRuleUserListInfo object, or a boolean rule that
      # defines this user list. The default rule_type for a user_list_rule_info
      # object is OR of ANDs (disjunctive normal form). That is, rule items will
      # be ANDed together within rule item groups and the groups themselves will
      # be ORed together.
      r.expression_rule_user_list =
        client.resource.expression_rule_user_list_info do |expr|
        expr.rule = client.resource.user_list_rule_info do |info|
          # Combines the two rule items into a UserListRuleItemGroupInfo object
          # so Google Ads will AND their rules together. To instead OR the rules
          # together, each rule should be placed in its own rule item group.
          info.rule_item_groups << client.resource.user_list_rule_item_group_info do |group|
            # Creates a rule targeting any user that visited a url that contains
            # 'example.com/section1'.
            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 = :CONTAINS
                string_rule.value = "example.com/section1"
              end
            end
            # Creates a rule targeting any user that visited a url that contains
            # 'example.com/section2'.
            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 = :CONTAINS
                string_rule.value = "example.com/section2"
              end
            end
          end
        end
      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_expression_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 an expression rule for users who have
# visited two different sections 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::V11::Common::UserListRuleItemInfo;
use Google::Ads::GoogleAds::V11::Common::UserListStringRuleItemInfo;
use Google::Ads::GoogleAds::V11::Common::ExpressionRuleUserListInfo;
use Google::Ads::GoogleAds::V11::Common::UserListRuleInfo;
use Google::Ads::GoogleAds::V11::Common::UserListRuleItemGroupInfo;
use Google::Ads::GoogleAds::V11::Common::RuleBasedUserListInfo;
use Google::Ads::GoogleAds::V11::Resources::UserList;
use Google::Ads::GoogleAds::V11::Enums::UserListStringRuleItemOperatorEnum
  qw(CONTAINS);
use Google::Ads::GoogleAds::V11::Enums::UserListPrepopulationStatusEnum
  qw(REQUESTED);
use Google::Ads::GoogleAds::V11::Enums::UserListMembershipStatusEnum qw(OPEN);
use Google::Ads::GoogleAds::V11::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_expression_rule_user_list {
  my ($api_client, $customer_id) = @_;

  # Create a rule targeting any user that visited a URL that contains
  # 'example.com/section1'.
  my $rule1 = Google::Ads::GoogleAds::V11::Common::UserListRuleItemInfo->new({
      # Use a built-in parameter to create a domain URL rule.
      name           => URL_STRING,
      stringRuleItem =>
        Google::Ads::GoogleAds::V11::Common::UserListStringRuleItemInfo->new({
          operator => CONTAINS,
          value    => "example.com/section1"
        })});

  # Create a rule targeting any user that visited a URL that contains
  # 'example.com/section2'.
  my $rule2 = Google::Ads::GoogleAds::V11::Common::UserListRuleItemInfo->new({
      # Use a built-in parameter to create a domain URL rule.
      name           => URL_STRING,
      stringRuleItem =>
        Google::Ads::GoogleAds::V11::Common::UserListStringRuleItemInfo->new({
          operator => CONTAINS,
          value    => "example.com/section2"
        })});

  # Create an ExpressionRuleUserListInfo object, or a boolean rule that defines
  # this user list. The default rule_type for a UserListRuleInfo object is OR of
  # ANDs (disjunctive normal form). That is, rule items will be ANDed together
  # within rule item groups and the groups themselves will be ORed together.
  my $expression_rule_user_list_info =
    Google::Ads::GoogleAds::V11::Common::ExpressionRuleUserListInfo->new({
      rule => Google::Ads::GoogleAds::V11::Common::UserListRuleInfo->new({
          ruleItemGroups => [
            # Combine the two rule items into a UserListRuleItemGroupInfo object
            # so Google Ads will AND their rules together. To instead OR the rules
            # together, each rule should be placed in its own rule item group.
            Google::Ads::GoogleAds::V11::Common::UserListRuleItemGroupInfo->new(
              {ruleItems => [$rule1, $rule2]})]})});

  # Define a representation of a user list that is generated by a rule.
  my $rule_based_user_list_info =
    Google::Ads::GoogleAds::V11::Common::RuleBasedUserListInfo->new({
      # Optional: To include past users in the user list, set the prepopulationStatus
      # to REQUESTED.
      prepopulationStatus    => REQUESTED,
      expressionRuleUserList => $expression_rule_user_list_info
    });

  # Create a user list.
  my $user_list = Google::Ads::GoogleAds::V11::Resources::UserList->new({
    name =>
      "All visitors to example.com/section1 AND example.com/section2 #" .
      uniqid(),
    description =>
      "Visitors of both example.com/section1 AND example.com/section2",
    membershipStatus   => OPEN,
    membershipLifeSpan => 365,
    ruleBasedUserList  => $rule_based_user_list_info
  });

  # Create the operation.
  my $user_list_operation =
    Google::Ads::GoogleAds::V11::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_expression_rule_user_list($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

add_expression_rule_user_list

=head1 DESCRIPTION

Creates a rule-based user list defined by an expression rule for users who have
visited two different sections of a website.

=head1 SYNOPSIS

add_expression_rule_user_list.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut