Add Flexible Rule User List

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.v17.common.FlexibleRuleOperandInfo;
import com.google.ads.googleads.v17.common.FlexibleRuleUserListInfo;
import com.google.ads.googleads.v17.common.RuleBasedUserListInfo;
import com.google.ads.googleads.v17.common.UserListRuleInfo;
import com.google.ads.googleads.v17.common.UserListRuleItemGroupInfo;
import com.google.ads.googleads.v17.common.UserListRuleItemInfo;
import com.google.ads.googleads.v17.common.UserListStringRuleItemInfo;
import com.google.ads.googleads.v17.enums.UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator;
import com.google.ads.googleads.v17.enums.UserListMembershipStatusEnum.UserListMembershipStatus;
import com.google.ads.googleads.v17.enums.UserListPrepopulationStatusEnum.UserListPrepopulationStatus;
import com.google.ads.googleads.v17.enums.UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.UserList;
import com.google.ads.googleads.v17.services.MutateUserListsResponse;
import com.google.ads.googleads.v17.services.UserListOperation;
import com.google.ads.googleads.v17.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 AddFlexibleRuleUserList {

  private static final String URL_STRING = "url__";

  private static class AddFlexibleRuleUserListParams extends CodeSampleParams {

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

  public static void main(String[] args) {
    AddFlexibleRuleUserListParams params = new AddFlexibleRuleUserListParams();
    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 AddFlexibleRuleUserList().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) {
    // Creates a UserListRuleInfo object containing the first rule.
    UserListRuleInfo userVisitedSite1Rule =
        createUserListRuleInfoFromUrl("http://example.com/example1");

    // Creates a UserListRuleInfo object containing the second rule.
    UserListRuleInfo userVisitedSite2Rule =
        createUserListRuleInfoFromUrl("http://example.com/example2");

    // Creates a UserListRuleInfo object containing the third rule.
    UserListRuleInfo userVisitedSite3Rule =
        createUserListRuleInfoFromUrl("http://example.com/example3");

    // Create the user list "Visitors of page 1 AND page 2, but not page 3". To create the user list
    // "Visitors of page 1 *OR* page 2, but not page 3", change the UserListFlexibleRuleOperator
    // from AND to OR.
    FlexibleRuleUserListInfo flexibleRuleUserListInfo =
        FlexibleRuleUserListInfo.newBuilder()
            .setInclusiveRuleOperator(UserListFlexibleRuleOperator.AND)
            // Inclusive operands are joined together with the specified inclusiveRuleOperator. This
            // represents the set of users that should be included in the user list.
            .addInclusiveOperands(
                FlexibleRuleOperandInfo.newBuilder()
                    .setRule(userVisitedSite1Rule)
                    // Optional: adds a lookback window for this rule, in days.
                    .setLookbackWindowDays(7L))
            .addInclusiveOperands(
                FlexibleRuleOperandInfo.newBuilder()
                    .setRule(userVisitedSite2Rule)
                    // Optional: adds a lookback window for this rule, in days.
                    .setLookbackWindowDays(7L))
            .addExclusiveOperands(
                // Exclusive operands are joined together with OR. This represents the set of users
                // to be excluded from the user list.
                FlexibleRuleOperandInfo.newBuilder().setRule(userVisitedSite3Rule))
            .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)
            .setFlexibleRuleUserList(flexibleRuleUserListInfo)
            .build();

    // Creates a user list.
    UserList userList =
        UserList.newBuilder()
            .setName("Flexible rule user list for example.com #" + getPrintableDateTime())
            .setDescription(
                "Visitors of both http://example.com/example1 AND http://example.com/example2 but"
                    + " NOT http://example.com/example3")
            .setMembershipStatus(UserListMembershipStatus.OPEN)
            .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);
    }
  }

  /**
   * Creates a UserListRuleInfo object containing a rule targeting any user that visited the
   * provided URL.
   */
  private UserListRuleInfo createUserListRuleInfoFromUrl(String urlString) {
    // Creates a rule targeting any user that visited a URL that equals the given urlString.
    UserListRuleItemInfo userVisitedSiteRule =
        UserListRuleItemInfo.newBuilder()
            // Uses a built-in parameter to create a domain URL rule.
            .setName(URL_STRING)
            .setStringRuleItem(
                UserListStringRuleItemInfo.newBuilder()
                    .setOperator(UserListStringRuleItemOperator.EQUALS)
                    .setValue(urlString))
            .build();

    // Returns a UserListRuleInfo object containing the rule.
    return UserListRuleInfo.newBuilder()
        .addRuleItemGroups(UserListRuleItemGroupInfo.newBuilder().addRuleItems(userVisitedSiteRule))
        .build();
  }
}

      

C#

// Copyright 2023 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.V17.Common;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using System;
using static Google.Ads.GoogleAds.V17.Enums.UserListFlexibleRuleOperatorEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListMembershipStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListPrepopulationStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.UserListStringRuleItemOperatorEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// 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 AddFlexibleRuleUserList : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddFlexibleRuleUserList"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the user list is added.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the user list is 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);

            AddFlexibleRuleUserList codeExample = new AddFlexibleRuleUserList();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId);
        }

        private const string URL_STRING = "url__";

        /// <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 for which the user list is
        /// added.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Creates a UserListRuleInfo object containing the first rule.
            UserListRuleInfo userVisitedSite1Rule =
                CreateUserListRuleInfoFromUrl("http://example.com/example1");

            // Creates a UserListRuleInfo object containing the second rule.
            UserListRuleInfo userVisitedSite2Rule =
                CreateUserListRuleInfoFromUrl("http://example.com/example2");

            // Creates a UserListRuleInfo object containing the third rule.
            UserListRuleInfo userVisitedSite3Rule =
                CreateUserListRuleInfoFromUrl("http://example.com/example3");

            // Create the user list "Visitors of page 1 AND page 2, but not page 3". To create the
            // user list "Visitors of page 1 *OR* page 2, but not page 3", change the
            // UserListFlexibleRuleOperator from And to Or.
            FlexibleRuleUserListInfo flexibleRuleUserListInfo = new FlexibleRuleUserListInfo
            {
                InclusiveRuleOperator = UserListFlexibleRuleOperator.And
            };

            // Inclusive operands are joined together with the specified inclusiveRuleOperator. This
            // represents the set of users that should be included in the user list.
            flexibleRuleUserListInfo.InclusiveOperands.Add(new FlexibleRuleOperandInfo
            {
                Rule = userVisitedSite1Rule,
                // Optional: adds a lookback window for this rule, in days.
                LookbackWindowDays = 7
            });
            flexibleRuleUserListInfo.InclusiveOperands.Add(new FlexibleRuleOperandInfo
            {
                Rule = userVisitedSite2Rule,
                // Optional: adds a lookback window for this rule, in days.
                LookbackWindowDays = 7
            });

            // Exclusive operands are joined together with OR. This represents the set of users
            // to be excluded from the user list.
            flexibleRuleUserListInfo.InclusiveOperands.Add(new FlexibleRuleOperandInfo
            {
                Rule = userVisitedSite3Rule
            });

            // 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,
                FlexibleRuleUserList = flexibleRuleUserListInfo
            };

            // Creates a user list.
            UserList userList = new UserList
            {
                Name = $"Flexible rule user list example.com #{ExampleUtilities.GetRandomString()}",
                Description = "Visitors of both https://example.com/example1 AND " +
                    "https://example.com/example2 but NOT https://example.com/example3",
                MembershipStatus = UserListMembershipStatus.Open,
                RuleBasedUserList = ruleBasedUserListInfo
            };

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

            try
            {
                UserListServiceClient userListServiceClient =
                    client.GetService(Services.V17.UserListService);
                MutateUserListsResponse response =
                    userListServiceClient.MutateUserLists(customerId.ToString(),
                        new[] { operation });

                string userListResourceName = response.Results[0].ResourceName;
                Console.WriteLine($"Created user list with resource name '{userListResourceName}'.");
            }
            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 a UserListRuleInfo object containing a rule targeting any user that visited the
        /// provided URL.
        /// </summary>
        private UserListRuleInfo CreateUserListRuleInfoFromUrl(string urlString)
        {
            // Creates a rule targeting any user that visited a URL that equals the given urlString.
            UserListRuleItemInfo userVisitedSiteRule = new UserListRuleItemInfo
            {
                Name = URL_STRING,
                StringRuleItem = new UserListStringRuleItemInfo
                {
                    Operator = UserListStringRuleItemOperator.Equals,
                    Value = urlString
                }
            };

            // Returns a UserListRuleInfo object containing the rule.
            UserListRuleInfo userListRuleInfo = new UserListRuleInfo();
            UserListRuleItemGroupInfo userListRuleItemGroupInfo = new UserListRuleItemGroupInfo();
            userListRuleItemGroupInfo.RuleItems.Add(userVisitedSiteRule);
            userListRuleInfo.RuleItemGroups.Add(userListRuleItemGroupInfo);

            return userListRuleInfo;
        }
    }
}
      

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\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\V17\Common\FlexibleRuleOperandInfo;
use Google\Ads\GoogleAds\V17\Common\FlexibleRuleUserListInfo;
use Google\Ads\GoogleAds\V17\Common\RuleBasedUserListInfo;
use Google\Ads\GoogleAds\V17\Common\UserListRuleInfo;
use Google\Ads\GoogleAds\V17\Common\UserListRuleItemGroupInfo;
use Google\Ads\GoogleAds\V17\Common\UserListRuleItemInfo;
use Google\Ads\GoogleAds\V17\Common\UserListStringRuleItemInfo;
use Google\Ads\GoogleAds\V17\Enums\UserListFlexibleRuleOperatorEnum\UserListFlexibleRuleOperator;
use Google\Ads\GoogleAds\V17\Enums\UserListMembershipStatusEnum\UserListMembershipStatus;
use Google\Ads\GoogleAds\V17\Enums\UserListPrepopulationStatusEnum\UserListPrepopulationStatus;
use Google\Ads\GoogleAds\V17\Enums\UserListStringRuleItemOperatorEnum\UserListStringRuleItemOperator;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\UserList;
use Google\Ads\GoogleAds\V17\Services\MutateUserListsRequest;
use Google\Ads\GoogleAds\V17\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 AddFlexibleRuleUserList
{
    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'.
        $userVisitedSite1RuleInfo = self::createUserListRuleFromUrl('http://example.com/example1');
        // Creates a rule targeting any user that visited a url that equals
        // http://example.com/example2'.
        $userVisitedSite2RuleInfo = self::createUserListRuleFromUrl('http://example.com/example2');
        // Creates a rule targeting any user that visited a url that equals
        // http://example.com/example3'.
        $userVisitedSite3RuleInfo = self::createUserListRuleFromUrl('http://example.com/example3');

        // Create the user list "Visitors of page 1 AND page 2, but not page 3".
        // To create the user list "Visitors of page 1 *OR* page 2, but not page 3",
        // change the UserListFlexibleRuleOperator from PBAND to OR.
        $flexibleRuleUserListInfo = new FlexibleRuleUserListInfo([
            'inclusive_rule_operator' => UserListFlexibleRuleOperator::PBAND,
            'inclusive_operands' => [
                new FlexibleRuleOperandInfo([
                    'rule' => $userVisitedSite1RuleInfo,
                    // Optionally add a lookback window for this rule, in days.
                    'lookback_window_days' => 7
                ]),
                new FlexibleRuleOperandInfo([
                    'rule' => $userVisitedSite2RuleInfo,
                    // Optionally add a lookback window for this rule, in days.
                    'lookback_window_days' => 7
                ])
            ],
            // Exclusive operands are joined together with OR. This represents the set of users to
            // be excluded from the user list.
            'exclusive_operands' => [
                new FlexibleRuleOperandInfo(['rule' => $userVisitedSite3RuleInfo])
            ]
        ]);

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

        // Creates a user list.
        $userList = new UserList([
            'name' => 'All visitors to http://example.com/example1 AND ' .
                'http://example.com/example2 but NOT http://example.com/example3 #'
                . Helper::getPrintableDatetime(),
            'description' => 'Visitors of both http://example.com/example1 AND ' .
                'http://example.com/example2 but NOT http://example.com/example3',
            'membership_status' => UserListMembershipStatus::OPEN,
            '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(
            MutateUserListsRequest::build($customerId, [$operation])
        );
        printf(
            "Created user list with resource name '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }

    /**
     * Creates a UserListRuleInfo object containing a rule targeting any user that visited the
     * provided URL.
     *
     * @param string $url the URL to create a UserListStringRuleItemInfo
     * @return UserListRuleInfo the created UserListRuleInfo
     */
    private static function createUserListRuleFromUrl(string $url): UserListRuleInfo
    {
        // Create a rule targeting any user that visited a URL that equals the given URL.
        $userVisitedSiteRule = 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' => $url
            ])
        ]);

        // Returns a UserListRuleInfo object containing the rule.
        return new UserListRuleInfo([
            'rule_item_groups' => [
                new UserListRuleItemGroupInfo([
                    'rule_items' => [$userVisitedSiteRule]
                ])
            ]
        ]);
    }
}

AddFlexibleRuleUserList::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.
    """
    # Create a UserListRuleInfo object containing the first rule.
    user_visited_site1_rule_info = create_user_list_rule_info_from_url(
        client, "http://example.com/example1"
    )
    # Create a UserListRuleInfo object containing the second rule.
    user_visited_site2_rule_info = create_user_list_rule_info_from_url(
        client, "http://example.com/example2"
    )
    # Create a UserListRuleInfo object containing the third rule.
    user_visited_site3_rule_info = create_user_list_rule_info_from_url(
        client, "http://example.com/example3"
    )

    # Create the user list "Visitors of page 1 AND page 2, but not page 3".
    # To create the user list "Visitors of page 1 *OR* page 2, but not page 3",
    # change the UserListFlexibleRuleOperator from AND to OR.
    flexible_rule_user_list_info = client.get_type("FlexibleRuleUserListInfo")
    flexible_rule_user_list_info.inclusive_rule_operator = (
        client.enums.UserListFlexibleRuleOperatorEnum.AND
    )

    # Inclusive operands are joined together with the specified
    # inclusive_rule_operator. This represents the set of users that should be
    # included in the user list.
    operand_1 = client.get_type("FlexibleRuleOperandInfo")
    operand_1.rule = user_visited_site1_rule_info
    # Optionally add a lookback window for this rule, in days.
    operand_1.lookback_window_days = 7
    flexible_rule_user_list_info.inclusive_operands.append(operand_1)

    operand_2 = client.get_type("FlexibleRuleOperandInfo")
    operand_2.rule = user_visited_site2_rule_info
    # Optionally add a lookback window for this rule, in days.
    operand_2.lookback_window_days = 7
    flexible_rule_user_list_info.inclusive_operands.append(operand_2)

    # Exclusive operands are joined together with OR.
    # This represents the set of users to be excluded from the user list.
    operand_3 = client.get_type("FlexibleRuleOperandInfo")
    operand_3.rule = user_visited_site3_rule_info
    flexible_rule_user_list_info.exclusive_operands.append(operand_3)

    # 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
    )
    rule_based_user_list_info.flexible_rule_user_list = (
        flexible_rule_user_list_info
    )

    # Create a user list.
    user_list_operation = client.get_type("UserListOperation")
    user_list = user_list_operation.create
    user_list.name = (
        "All visitors to http://example.com/example1 AND "
        "http://example.com/example2 but NOT "
        f"http://example.com/example3 #{uuid4()}"
    )
    user_list.description = (
        "Visitors of both http://example.com/example1 AND "
        "http://example.com/example2 but NOT"
        "http://example.com/example3"
    )
    user_list.membership_status = client.enums.UserListMembershipStatusEnum.OPEN
    user_list.rule_based_user_list = rule_based_user_list_info

    # Issue a mutate request to add the user list, then print the results.
    user_list_service = client.get_service("UserListService")
    response = user_list_service.mutate_user_lists(
        customer_id=customer_id, operations=[user_list_operation]
    )
    print(
        "Created user list with resource name: "
        f"'{response.results[0].resource_name}.'"
    )


def create_user_list_rule_info_from_url(client, url):
    """Create a UserListRuleInfo targeting any user that visited the given URL.

    Args:
        client: The Google Ads client.
        url: a URL string.

    Returns:
        A UserListRuleInfo instance.
    """
    # Create a rule targeting any user that visited a URL that equals
    # the given url_string.
    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

    group_info = client.get_type("UserListRuleItemGroupInfo")
    group_info.rule_items.append(user_visited_site_rule)

    # Return a UserListRuleInfo object containing the rule.
    info = client.get_type("UserListRuleInfo")
    info.rule_item_groups.append(group_info)

    return info


if __name__ == "__main__":
    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()

    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v17")

    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

  user_visited_site1_rule_info = create_user_list_rule_info_from_url(
    client,
    'http://example.com/example1',
  )
  user_visited_site2_rule_info = create_user_list_rule_info_from_url(
    client,
    'http://example.com/example2',
  )
  user_visited_site3_rule_info = create_user_list_rule_info_from_url(
    client,
    'http://example.com/example3',
  )

  # Creates a user list.
  operation = client.operation.create_resource.user_list do |u|
    u.name = "Flexible rule user list for example.com ##{(Time.new.to_f * 1000).to_i}"
    u.description = "Visitors of both http://example.com/example1 AND " \
      "http://example.com/example2 but NOT http://example.com/example3"
    u.membership_status = :OPEN
    # 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
      r.flexible_rule_user_list = client.resource.flexible_rule_user_list_info do |frul|
        frul.inclusive_rule_operator = :AND
        frul.inclusive_operands += [
          client.resource.flexible_rule_operand_info do |froi|
            froi.rule = user_visited_site1_rule_info
            # Optionally add a lookback window for this rule, in days.
            froi.lookback_window_days = 7
          end,
          client.resource.flexible_rule_operand_info do |froi|
            froi.rule = user_visited_site2_rule_info
            # Optionally add a lookback window for this rule, in days.
            froi.lookback_window_days = 7
          end,
        ]
        frul.exclusive_operands << client.resource.flexible_rule_operand_info do |froi|
          froi.rule = user_visited_site3_rule_info
        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

def create_user_list_rule_info_from_url(client, url)
  client.resource.user_list_rule_info do |rule|
    rule.rule_item_groups << client.resource.user_list_rule_item_group_info do |group|
      group.rule_items << client.resource.user_list_rule_item_info do |item|
        item.name = URL_STRING
        item.string_rule_item = client.resource.user_list_string_rule_item_info do |string|
          string.operator = :EQUALS
          string.value = url
        end
      end
    end
  end
end

if __FILE__ == $0
  URL_STRING = "url__"

  options = {}

  # Running the example with -h will print the command line usage.

  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::V17::Resources::UserList;
use Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo;
use Google::Ads::GoogleAds::V17::Common::UserListStringRuleItemInfo;
use Google::Ads::GoogleAds::V17::Common::UserListRuleInfo;
use Google::Ads::GoogleAds::V17::Common::UserListRuleItemGroupInfo;
use Google::Ads::GoogleAds::V17::Common::FlexibleRuleUserListInfo;
use Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo;
use Google::Ads::GoogleAds::V17::Common::RuleBasedUserListInfo;
use Google::Ads::GoogleAds::V17::Enums::UserListFlexibleRuleOperatorEnum
  qw(AND);
use Google::Ads::GoogleAds::V17::Enums::UserListStringRuleItemOperatorEnum
  qw(EQUALS);
use Google::Ads::GoogleAds::V17::Enums::UserListPrepopulationStatusEnum
  qw(REQUESTED);
use Google::Ads::GoogleAds::V17::Enums::UserListMembershipStatusEnum qw(OPEN);
use Google::Ads::GoogleAds::V17::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__";

sub add_combined_rule_user_list {
  my ($api_client, $customer_id) = @_;

  # Create a UserListRuleInfo object containing the first rule.
  my $user_visited_site1_rule_info =
    create_user_list_rule_info_from_url("http://example.com/example1");

  # Create a UserListRuleInfo object containing the second rule.
  my $user_visited_site2_rule_info =
    create_user_list_rule_info_from_url("http://example.com/example2");

  # Create a UserListRuleInfo object containing the third rule.
  my $user_visited_site3_rule_info =
    create_user_list_rule_info_from_url("http://example.com/example3");

  # Create the user list "Visitors of page 1 AND page 2, but not page 3".
  # To create the user list "Visitors of page 1 *OR* page 2, but not page 3",
  # change the UserListFlexibleRuleOperator from AND to OR.
  my $flexible_rule_user_list_info =
    Google::Ads::GoogleAds::V17::Common::FlexibleRuleUserListInfo->new({
      inclusiveRuleOperator => AND,
      # Inclusive operands are joined together with the specified inclusiveRuleOperator.
      # This represents the set of users that should be included in the user list.
      inclusiveOperands => [
        Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo->new({
            rule => $user_visited_site1_rule_info,
            # Optionally add a lookback window for this rule, in days.
            lookbackWindowDays => 7
          }
        ),
        Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo->new({
            rule => $user_visited_site2_rule_info,
            # Optionally add a lookback window for this rule, in days.
            lookbackWindowDays => 7
          })
      ],
      # Exclusive operands are joined together with OR.
      # This represents the set of users to be excluded from the user list.
      exclusiveOperands => [
        Google::Ads::GoogleAds::V17::Common::FlexibleRuleOperandInfo->new({
            rule => $user_visited_site3_rule_info
          })
      ],
    });

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

  # Create a user list.
  my $user_list = Google::Ads::GoogleAds::V17::Resources::UserList->new({
    name        => "Flexible rule user list for example.com #" . uniqid(),
    description => "Visitors of both http://example.com/example1 AND " .
      "http://example.com/example2 but NOT http://example.com/example3",
    membershipStatus  => OPEN,
    ruleBasedUserList => $rule_based_user_list_info
  });

  # Create the operation.
  my $user_list_operation =
    Google::Ads::GoogleAds::V17::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;
}

# Create a UserListRuleInfo object containing a rule targeting any user
# that visited the provided URL.
sub create_user_list_rule_info_from_url {
  my ($url_string) = @_;

  # Create a rule targeting any user that visited a URL that equals
  # the given url_string.
  my $user_visited_site_rule =
    Google::Ads::GoogleAds::V17::Common::UserListRuleItemInfo->new({
      # Use a built-in parameter to create a domain URL rule.
      name           => URL_STRING,
      stringRuleItem =>
        Google::Ads::GoogleAds::V17::Common::UserListStringRuleItemInfo->new({
          operator => EQUALS,
          value    => $url_string
        })});

  # Return a UserListRuleInfo object containing the rule.
  return Google::Ads::GoogleAds::V17::Common::UserListRuleInfo->new({
      ruleItemGroups =>
        Google::Ads::GoogleAds::V17::Common::UserListRuleItemGroupInfo->new({
          ruleItems => [$user_visited_site_rule]})});

}

# 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);

my $customer_id = undef;

# 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