เพิ่มรายการผู้ใช้เชิงตรรกะ

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.LogicalUserListInfo;
import com.google.ads.googleads.v17.common.LogicalUserListOperandInfo;
import com.google.ads.googleads.v17.common.UserListLogicalRuleInfo;
import com.google.ads.googleads.v17.enums.UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator;
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.ads.googleads.v17.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Creates a combination user list containing users that are present on any one of the provided user
 * lists.
 */
public class AddLogicalUserList {

  private static class AddLogicalUserListParams extends CodeSampleParams {

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

    @Parameter(names = ArgumentNames.USER_LIST_IDS, required = true)
    private List<Long> userListIds;
  }

  public static void main(String[] args) {
    AddLogicalUserListParams params = new AddLogicalUserListParams();
    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");
      params.userListIds =
          Arrays.asList(
              Long.parseLong("INSERT_USER_LIST_ID_HERE"),
              Long.parseLong("INSERT_USER_LIST_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 AddLogicalUserList().runExample(googleAdsClient, params.customerId, params.userListIds);
    } 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.
   * @param userListIds the IDs of the lists to be used for the new combination user list.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient, long customerId, List<Long> userListIds) {
    // Adds each of the provided list IDs to a list of rule operands specifying which lists the
    // operator should target.
    List<LogicalUserListOperandInfo> logicalUserListOperandInfoList = new ArrayList<>();
    for (long userListId : userListIds) {
      String userListResourceName = ResourceNames.userList(customerId, userListId);
      logicalUserListOperandInfoList.add(
          LogicalUserListOperandInfo.newBuilder().setUserList(userListResourceName).build());
    }

    // Creates the UserListLogicalRuleInfo specifying that a user should be added to the new list if
    // they are present in any of the provided lists.
    UserListLogicalRuleInfo userListLogicalRuleInfo =
        UserListLogicalRuleInfo.newBuilder()
            // Using ANY means that a user should be added to the combined list if they are present
            // on any of the lists targeted in the LogicalUserListOperandInfo. Use ALL to add users
            // present on all of the provided lists or NONE to add users that aren't present on any
            // of the targeted lists.
            .setOperator(UserListLogicalRuleOperator.ANY)
            .addAllRuleOperands(logicalUserListOperandInfoList)
            .build();

    // Creates the new combination user list.
    UserList userList =
        UserList.newBuilder()
            .setName("My combination list of other user lists #" + getPrintableDateTime())
            .setLogicalUserList(
                LogicalUserListInfo.newBuilder().addRules(userListLogicalRuleInfo).build())
            .build();

    // Creates the operation.
    UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();

    // Creates the service client.
    try (UserListServiceClient userListServiceClient =
        googleAdsClient.getLatestVersion().createUserListServiceClient()) {
      // Adds the user list.
      MutateUserListsResponse response =
          userListServiceClient.mutateUserLists(
              Long.toString(customerId), ImmutableList.of(operation));
      // Prints the response.
      System.out.printf(
          "Created combination user list with resource name, '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }
}

      

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.V17.Common;
using Google.Ads.GoogleAds.V17.Enums;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// This code example creates a combination user list containing users that are present on any
    /// one of the provided user lists.
    /// </summary>
    public class AddLogicalUserList : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddLogicalUserList"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// The IDs of the lists to be used for the new combination user list.
            /// </summary>
            [Option("userListIds", Required = true, HelpText =
                "The IDs of the lists to be used for the new combination user list.")]
            public IEnumerable<long> UserListIds { 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);

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example creates a combination user list containing users that are present " +
            "on any one of the provided user lists.";

        /// <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 call is made.</param>
        /// <param name="userListIds">The IDs of the lists to be used for the new combination user
        /// list.</param>
        public void Run(GoogleAdsClient client, long customerId, long[] userListIds)
        {
            // Gets the UserListService client.
            UserListServiceClient userListServiceClient =
                client.GetService(Services.V17.UserListService);

            // Adds each of the provided list IDs to a list of rule operands specifying which lists
            // the operator should target.
            List<LogicalUserListOperandInfo> logicalUserListOperandInfoList =
                userListIds.Select(userListId => new LogicalUserListOperandInfo
                { UserList = ResourceNames.UserList(customerId, userListId) }).ToList();

            // Creates the UserListLogicalRuleInfo specifying that a user should be added to the new
            // list if they are present in any of the provided lists.
            UserListLogicalRuleInfo userListLogicalRuleInfo = new UserListLogicalRuleInfo
            {
                // Using ANY means that a user should be added to the combined list if they are
                // present on any of the lists targeted in the LogicalUserListOperandInfo. Use ALL
                // to add users present on all of the provided lists or NONE to add users that
                // aren't present on any of the targeted lists.
                Operator = UserListLogicalRuleOperatorEnum.Types.UserListLogicalRuleOperator.Any,
            };
            userListLogicalRuleInfo.RuleOperands.Add(logicalUserListOperandInfoList);

            LogicalUserListInfo logicalUserListInfo = new LogicalUserListInfo();
            logicalUserListInfo.Rules.Add(userListLogicalRuleInfo);

            // Creates the new combination user list.
            UserList userList = new UserList
            {
                Name = "My combination list of other user lists " +
                       $"#{ExampleUtilities.GetRandomString()}",
                LogicalUserList = logicalUserListInfo
            };

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

            try
            {
                // Sends the request to add the user list and prints the response.
                MutateUserListsResponse response = userListServiceClient.MutateUserLists
                    (customerId.ToString(), new[] { operation });
                Console.WriteLine("Created combination 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;
            }
        }
    }
}

      

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\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Common\LogicalUserListInfo;
use Google\Ads\GoogleAds\V17\Common\LogicalUserListOperandInfo;
use Google\Ads\GoogleAds\V17\Common\UserListLogicalRuleInfo;
use Google\Ads\GoogleAds\V17\Enums\UserListLogicalRuleOperatorEnum\UserListLogicalRuleOperator;
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 combination user list containing users that are present on any one of the provided user
 * lists.
 */
class AddLogicalUserList
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const USER_LIST_ID_1 = 'INSERT_USER_LIST_ID_1_HERE';
    private const USER_LIST_ID_2 = 'INSERT_USER_LIST_ID_2_HERE';

    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,
            ArgumentNames::USER_LIST_IDS => GetOpt::MULTIPLE_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)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::USER_LIST_IDS] ?:
                    [self::USER_LIST_ID_1, self::USER_LIST_ID_2]
            );
        } 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
     * @param array $userListIds the IDs of the lists to be used for the new combination user list
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        array $userListIds
    ) {
        // Adds each of the provided list IDs to a list of rule operands specifying which lists the
        // operator should target.
        $logicalUserListOperandInfoList = [];
        foreach ($userListIds as $userListId) {
            $logicalUserListOperandInfoList[] = new LogicalUserListOperandInfo([
                'user_list' => ResourceNames::forUserList($customerId, $userListId)
            ]);
        }

        // Creates the UserListLogicalRuleInfo specifying that a user should be added to the new
        // list if they are present in any of the provided lists.
        $userListLogicalRuleInfo = new UserListLogicalRuleInfo([
            // Using ANY means that a user should be added to the combined list if they are present
            // on any of the lists targeted in the LogicalUserListOperandInfo. Use ALL to add users
            // present on all of the provided lists or NONE to add users that aren't present on any
            // of the targeted lists.
            'operator' => UserListLogicalRuleOperator::ANY,
            'rule_operands' => $logicalUserListOperandInfoList
        ]);

        // Creates the new combination user list.
        $userList = new UserList([
            'name' => 'My combination list of other user lists #' . Helper::getPrintableDatetime(),
            'logical_user_list' => new LogicalUserListInfo([
                'rules' => [$userListLogicalRuleInfo]
            ])
        ]);

        // 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 combination user list with resource name '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }
}

AddLogicalUserList::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 combination user list.

The list will contain users that are present on any one of the provided user
lists.
"""

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, user_list_ids):
    """Creates a combination user list.

    Args:
        client: The Google Ads client.
        customer_id: The customer ID for which to add the user list.
        user_list_ids: A list of user list IDs to logically combine.
    """
    # Get the UserListService client.
    user_list_service = client.get_service("UserListService")

    # Add each of the provided list IDs to a list of rule operands specifying
    # which lists the operator should target.
    logical_user_list_operand_info_list = []
    for user_list_id in user_list_ids:
        logical_user_list_operand_info = client.get_type(
            "LogicalUserListOperandInfo"
        )
        logical_user_list_operand_info.user_list = (
            user_list_service.user_list_path(customer_id, user_list_id)
        )
        logical_user_list_operand_info_list.append(
            logical_user_list_operand_info
        )

    # Create a UserListOperation and populate the UserList.
    user_list_operation = client.get_type("UserListOperation")
    user_list = user_list_operation.create
    user_list.name = f"My combination list of other user lists #{uuid4()}"
    # Create a UserListLogicalRuleInfo specifying that a user should be added to
    # the new list if they are present in any of the provided lists.
    user_list_logical_rule_info = client.get_type("UserListLogicalRuleInfo")
    # Using ANY means that a user should be added to the combined list if they
    # are present on any of the lists targeted in the
    # LogicalUserListOperandInfo. Use ALL to add users present on all of the
    # provided lists or NONE to add users that aren't present on any of the
    # targeted lists.
    user_list_logical_rule_info.operator = (
        client.enums.UserListLogicalRuleOperatorEnum.ANY
    )
    user_list_logical_rule_info.rule_operands.extend(
        logical_user_list_operand_info_list
    )
    user_list.logical_user_list.rules.append(user_list_logical_rule_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 logical user list with resource name "
        f"'{response.results[0].resource_name}.'"
    )


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.",
    )
    parser.add_argument(
        "-l",
        "--user_list_ids",
        nargs="+",
        type=str,
        required=True,
        help="The user list IDs logically combine.",
    )
    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, args.user_list_ids)
    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 combination user list containing users that are present on any one
# of the provided user lists.

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

def add_logical_user_list(customer_id, user_list_ids)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  # Creates the UserListLogicalRuleInfo specifying that a user should be added
  # to the new list if they are present in any of the provided lists.
  user_list_logical_rule_info = client.resource.user_list_logical_rule_info do |info|
    # Using ANY means that a user should be added to the combined list if they
    # are present on any of the lists targeted in the logical_user_list_operand_info.
    # Use ALL to add users present on all of the provided lists or NONE to add
    # users that aren't present on any of the targeted lists.
    info.operator = :ANY
    user_list_ids.each do |list_id|
      info.rule_operands << client.resource.logical_user_list_operand_info do |op|
        op.user_list = client.path.user_list(customer_id, list_id)
      end
    end
  end

  # Creates the new combination user list operation.
  operation = client.operation.create_resource.user_list do |ul|
    ul.name = "My combination list of other user lists #{(Time.new.to_f * 1000).to_i}"
    ul.logical_user_list = client.resource.logical_user_list_info do |info|
      info.rules << user_list_logical_rule_info
    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 combination user list with resource name "\
    "'#{response.results.first.resource_name}'"
end

if __FILE__ == $0
  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'
  options[:user_list_ids] = [
    'INSERT_USER_LIST_ID_1_HERE',
    'INSERT_USER_LIST_ID_2_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.on('-U', '--user-list-ids USER-LIST-IDS', String,
        'User List IDs (comma separated)') do |v|
      options[:user_list_ids] = v.split(',')
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_logical_user_list(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:user_list_ids),
    )
  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 combination user list containing users that are present on any one of
# the provided user lists.

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::LogicalUserListOperandInfo;
use Google::Ads::GoogleAds::V17::Common::UserListLogicalRuleInfo;
use Google::Ads::GoogleAds::V17::Common::LogicalUserListInfo;
use Google::Ads::GoogleAds::V17::Enums::UserListLogicalRuleOperatorEnum qw(ANY);
use Google::Ads::GoogleAds::V17::Services::UserListService::UserListOperation;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd          qw(abs_path);
use Data::Uniqid qw(uniqid);

# 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";
my $user_list_id1 = "INSERT_USER_LIST_ID_1_HERE";
my $user_list_id2 = "INSERT_USER_LIST_ID_2_HERE";
my $user_list_ids = [];

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

  # Add each of the provided list IDs to a list of rule operands specifying which
  # lists the operator should target.
  my $logical_user_list_operand_info_list = [];
  foreach my $user_list_id (@$user_list_ids) {
    push @$logical_user_list_operand_info_list,
      Google::Ads::GoogleAds::V17::Common::LogicalUserListOperandInfo->new({
        userList =>
          Google::Ads::GoogleAds::V17::Utils::ResourceNames::user_list(
          $customer_id, $user_list_id
          )});
  }

  # Create the UserListLogicalRuleInfo specifying that a user should be added to
  # the new list if they are present in any of the provided lists.
  my $user_list_logical_rule_info =
    Google::Ads::GoogleAds::V17::Common::UserListLogicalRuleInfo->new({
      # Using ANY means that a user should be added to the combined list if they
      # are present on any of the lists targeted in the LogicalUserListOperandInfo.
      # Use ALL to add users present on all of the provided lists or NONE to add
      # users that aren't present on any of the targeted lists.
      operator     => ANY,
      ruleOperands => $logical_user_list_operand_info_list
    });

  # Create the new combination user list.
  my $user_list = Google::Ads::GoogleAds::V17::Resources::UserList->new({
      name            => "My combination list of other user lists #" . uniqid(),
      logicalUserList =>
        Google::Ads::GoogleAds::V17::Common::LogicalUserListInfo->new({
          rules => [$user_list_logical_rule_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 combination 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,
  "user_list_ids=s" => \@$user_list_ids,
);
$user_list_ids = [$user_list_id1, $user_list_id2] unless @$user_list_ids;

# 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, $user_list_ids);

# Call the example.
add_logical_user_list($api_client, $customer_id =~ s/-//gr, $user_list_ids);

=pod

=head1 NAME

add_logical_user_list

=head1 DESCRIPTION

Creates a combination user list containing users that are present on any one of
the provided user lists

=head1 SYNOPSIS

add_logical_user_list.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -user_list_ids              The IDs of the lists to be used for the new
                                combination user list.

=cut