Detectar e aplicar recomendações

Java

// Copyright 2022 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.recommendations;

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.errors.GoogleAdsError;
import com.google.ads.googleads.v11.errors.GoogleAdsException;
import com.google.ads.googleads.v11.services.ApplyRecommendationOperation;
import com.google.ads.googleads.v11.services.ApplyRecommendationResponse;
import com.google.ads.googleads.v11.services.ApplyRecommendationResult;
import com.google.ads.googleads.v11.services.GoogleAdsRow;
import com.google.ads.googleads.v11.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v11.services.RecommendationServiceClient;
import com.google.ads.googleads.v11.services.SearchGoogleAdsStreamRequest;
import com.google.ads.googleads.v11.services.SearchGoogleAdsStreamResponse;
import com.google.api.gax.rpc.ServerStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * The auto-apply feature, which automatically applies recommendations as they become eligible, is
 * currently supported by the Google Ads UI but not by the Google Ads API. See
 * https://support.google.com/google-ads/answer/10279006 for more information on using auto-apply in
 * the Google Ads UI.
 *
 * <p>This example demonstrates how an alternative can be implemented with the features that are
 * currently supported by the Google Ads API. It periodically retrieves and applies `KEYWORD`
 * recommendations with default parameters.
 */
public class DetectAndApplyRecommendations {
  // The maximum number of recommendations to periodically retrieve and apply.  In a real
  // application, such a limit would typically not be used.
  private static final int MAX_RESULT_SIZE = 2;
  // The number of times to retrieve and apply recommendations. In a real application, such a
  // limit would typically not be used.
  private static final int NUMBER_OF_RUNS = 3;
  // The time to wait between two runs. In a real application, this would typically be set to
  // minutes or hours instead of seconds.
  private static final int PERIOD_IN_SECONDS = 5;

  private static class DetectAndApplyRecommendationsParams extends CodeSampleParams {

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

  public static void main(String[] args) throws IOException, InterruptedException {
    DetectAndApplyRecommendationsParams params = new DetectAndApplyRecommendationsParams();
    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 DetectAndApplyRecommendations().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)
      throws InterruptedException {
    try (GoogleAdsServiceClient googleAdsServiceClient =
            googleAdsClient.getLatestVersion().createGoogleAdsServiceClient();
        RecommendationServiceClient recommendationServiceClient =
            googleAdsClient.getLatestVersion().createRecommendationServiceClient()) {
      // Creates a query that retrieves keyword recommendations.
      String query =
          "SELECT recommendation.resource_name "
              + "FROM recommendation "
              + "WHERE recommendation.type = KEYWORD "
              + "LIMIT "
              + MAX_RESULT_SIZE;
      for (int i = 0; i < NUMBER_OF_RUNS; i++) {
        // Constructs the SearchGoogleAdsStreamRequest.
        SearchGoogleAdsStreamRequest request =
            SearchGoogleAdsStreamRequest.newBuilder()
                .setCustomerId(Long.toString(customerId))
                .setQuery(query)
                .build();

        // Issues the search stream request.
        ServerStream<SearchGoogleAdsStreamResponse> stream =
            googleAdsServiceClient.searchStreamCallable().call(request);

        // Creates apply operations for all the recommendations found.
        List<ApplyRecommendationOperation> applyRecommendationOperations = new ArrayList<>();
        for (SearchGoogleAdsStreamResponse response : stream) {
          for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
            applyRecommendationOperations.add(
                ApplyRecommendationOperation.newBuilder()
                    .setResourceName(googleAdsRow.getRecommendation().getResourceName())
                    .build());
          }
        }

        if (applyRecommendationOperations.isEmpty()) {
          System.out.println("No recommendations found.");
        } else {
          // Sends the apply recommendation request and prints information.
          ApplyRecommendationResponse applyRecommendationsResponse =
              recommendationServiceClient.applyRecommendation(
                  Long.toString(customerId), applyRecommendationOperations);
          for (ApplyRecommendationResult applyRecommendationResult :
              applyRecommendationsResponse.getResultsList()) {
            System.out.printf(
                "Applied recommendation with resource name: '%s'.%n",
                applyRecommendationResult.getResourceName());
          }
        }

        if (i < NUMBER_OF_RUNS - 1) {
          System.out.printf(
              "Waiting %d seconds before checking for additional recommendations.%n",
              PERIOD_IN_SECONDS);
          Thread.sleep(TimeUnit.SECONDS.toMillis(PERIOD_IN_SECONDS));
        }
      }
    }
  }
}

      

C#

// Copyright 2022 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.Errors;
using Google.Ads.GoogleAds.V11.Services;
using System;
using System.Collections.Generic;
using System.Threading;

namespace Google.Ads.GoogleAds.Examples.V11
{
    /// <summary>
    /// The auto-apply feature, which automatically applies recommendations as they become
    /// eligible, is currently supported by the Google Ads UI but not by the Google Ads API. See
    /// https://support.google.com/google-ads/answer/10279006 for more information on
    /// using auto-apply in the Google Ads UI.
    ///
    /// This code example demonstrates how an alternative can be implemented with the features that
    /// are currently supported by the Google Ads API. It periodically retrieves and applies
    /// <code>KEYWORD</code> recommendations with default parameters.
    /// </summary>
    public class DetectAndApplyRecommendations : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="DetectAndApplyRecommendations"/>
        /// example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The customer ID for which the call is made.")]
            public long CustomerId { get; set; }
        }

        /// <summary>
        /// The maximum number of recommendations to periodically retrieve and apply. In a real
        /// application, such a limit would typically not be used.
        /// </summary>
        private const int MAX_RESULT_SIZE = 2;

        /// <summary>
        /// The number of times to retrieve and apply recommendations. In a real application, such
        /// a limit would typically not be used.
        /// </summary>
        private const int NUMBER_OF_RUNS = 3;

        /// <summary>
        /// The time to wait between two runs. In a real application, this would typically be set
        /// to minutes or hours instead of seconds.
        /// </summary>
        private const int WAIT_TIME_IN_SECONDS = 5;

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

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "The auto-apply feature, which automatically applies recommendations as they become " +
            "eligible, is currently supported by the Google Ads UI but not by the Google Ads " +
            "API. See https://support.google.com/google-ads/answer/10279006 for more " +
            "information on using auto-apply in the Google Ads UI. " +
            "This code example demonstrates how an alternative can be implemented with the " +
            "features that are currently supported by the Google Ads API. It periodically " +
            "retrieves and applies <code>KEYWORD</code> recommendations with default parameters.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the RecommendationServiceClient.
            RecommendationServiceClient recommendationService = client.GetService(
                Services.V11.RecommendationService);

            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V11.GoogleAdsService);

            // Creates a query that retrieves keyword recommendations.
            string query = "SELECT recommendation.resource_name FROM recommendation WHERE " +
                $"recommendation.type = KEYWORD LIMIT {MAX_RESULT_SIZE}";

            try
            {
                // Creates apply operations for all the recommendations found.
                for (int i = 0; i < NUMBER_OF_RUNS; i++)
                {
                    List<ApplyRecommendationOperation> operations =
                        new List<ApplyRecommendationOperation>();
                    // Issue a search request.
                    googleAdsService.SearchStream(customerId.ToString(), query,
                        delegate (SearchGoogleAdsStreamResponse resp)
                        {
                            foreach (GoogleAdsRow googleAdsRow in resp.Results)
                            {
                                operations.Add(new ApplyRecommendationOperation()
                                {
                                    ResourceName = googleAdsRow.Recommendation.ResourceName
                                });
                            }
                        }
                    );

                    // Sends the apply recommendation request and prints information.
                    if (operations.Count > 0)
                    {
                        ApplyRecommendationResponse response =
                            recommendationService.ApplyRecommendation(
                                customerId.ToString(), operations);
                        Console.WriteLine($"Applied {0} recommendation(s):", response.Results.Count);
                        foreach (ApplyRecommendationResult result in response.Results)
                        {
                            Console.WriteLine($"- {result.ResourceName}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No recommendations were found.");
                    }
                    if (i < NUMBER_OF_RUNS - 1)
                    {
                        Console.WriteLine($"Waiting {WAIT_TIME_IN_SECONDS} seconds before " +
                            $"applying recommendations.");
                        Thread.Sleep(WAIT_TIME_IN_SECONDS * 1000);
                    }
                }
            }
            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 2022 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\Recommendations;

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\Lib\V11\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsServerStreamDecorator;
use Google\Ads\GoogleAds\V11\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V11\Services\ApplyRecommendationOperation;
use Google\Ads\GoogleAds\V11\Services\ApplyRecommendationResult;
use Google\Ads\GoogleAds\V11\Services\GoogleAdsRow;
use Google\ApiCore\ApiException;

/**
 * The auto-apply feature, which automatically applies recommendations as they become eligible,
 * is currently supported by the Google Ads UI but not by the Google Ads API. See
 * https://support.google.com/google-ads/answer/10279006 for more information on using auto-apply
 * in the Google Ads UI.
 *
 * This example demonstrates how an alternative can be implemented with the features that are
 * currently supported by the Google Ads API. It periodically retrieves and applies `KEYWORD`
 * recommendations with default parameters.
 */
class DetectAndApplyRecommendations
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    // The maximum number of recommendations to periodically retrieve and apply.  In a real
    // application, such a limit would typically not be used.
    private const MAX_RESULT_SIZE = 2;
    // The number of times to retrieve and apply recommendations. In a real application, such a
    // limit would typically not be used.
    private const NUMBER_OF_RUNS = 3;
    // The time to wait between two runs. In a real application, this would typically be set to
    // minutes or hours instead of seconds.
    private const PERIOD_IN_SECONDS = 5;

    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)
    {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
        // Creates a query that retrieves keyword recommendations.
        $query = 'SELECT recommendation.resource_name '
            . 'FROM recommendation '
            . 'WHERE recommendation.type = KEYWORD '
            . 'LIMIT ' . self::MAX_RESULT_SIZE;

        $recommendationServiceClient = $googleAdsClient->getRecommendationServiceClient();
        for ($i = 0; $i < self::NUMBER_OF_RUNS; $i++) {
            // Issues a search stream request.
            /* @var GoogleAdsServerStreamDecorator $stream */
            $stream = $googleAdsServiceClient->searchStream($customerId, $query);

            // Creates apply operations for all the recommendations found.
            $applyRecommendationOperations = [];
            foreach ($stream->iterateAllElements() as $googleAdsRow) {
                /** @var GoogleAdsRow $googleAdsRow */
                $applyRecommendationOperations[] = new ApplyRecommendationOperation([
                    'resource_name' => $googleAdsRow->getRecommendation()->getResourceName()
                ]);
            }

            if ($applyRecommendationOperations) {
                // Sends the apply recommendation request and prints information.
                $response = $recommendationServiceClient->applyRecommendation(
                    $customerId,
                    $applyRecommendationOperations
                );
                foreach ($response->getResults() as $result) {
                    /** @var ApplyRecommendationResult $result */
                    printf(
                        'Applied recommendation with resource name: "%s".%s',
                        $result->getResourceName(),
                        PHP_EOL
                    );
                }
            } else {
                print 'No recommendations were found.' . PHP_EOL;
            }
            print PHP_EOL;

            if ($i < self::NUMBER_OF_RUNS - 1) {
                printf(
                    "Waiting %d seconds before checking for additional recommendations.%s",
                    self::PERIOD_IN_SECONDS,
                    PHP_EOL
                );
                sleep(self::PERIOD_IN_SECONDS);
            }
        }
    }
}

DetectAndApplyRecommendations::main();

      

Python

#!/usr/bin/env python
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrate how to retrieve and apply recommendations.

The auto-apply feature, which automatically applies recommendations as they
become eligible, is currently supported by the Google Ads UI but not by the
Google Ads API. See https://support.google.com/google-ads/answer/10279006
for more information on using auto-apply in the Google Ads UI.
"""

import argparse
from re import I
import sys
import time

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException

# The maximum number of recommendations to periodically retrieve and apply.  In a real
# application, such a limit would typically not be used.
MAX_RESULT_SIZE = 2

# The number of times to retrieve and apply recommendations. In a real application, such a
# limit would typically not be used.
NUMBER_OF_RUNS = 3

# The time to wait between two runs. In a real application, this would typically be set to
# minutes or hours instead of seconds.
SECONDS_TO_WAIT = 5


def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService")

    query = f"""SELECT recommendation.resource_name
        FROM recommendation
        WHERE recommendation.type = KEYWORD
        LIMIT {MAX_RESULT_SIZE}"""

    recommendation_service = client.get_service("RecommendationService")

    for i in range(NUMBER_OF_RUNS + 1):
        search_request = client.get_type("SearchGoogleAdsStreamRequest")
        search_request.customer_id = customer_id
        search_request.query = query
        stream = ga_service.search_stream(request=search_request)

        apply_recommendation_operations = []

        for batch in stream:
            for row in batch.results:
                recommendation = row.recommendation

                apply_recommendation_operation = client.get_type(
                    "ApplyRecommendationOperation"
                )

                apply_recommendation_operation.resource_name = (
                    recommendation_service.recommendation_path(
                        customer_id, recommendation.id
                    )
                )

                apply_recommendation_operations.append(
                    apply_recommendation_operation
                )

            recommendation_response = (
                recommendation_service.apply_recommendation(
                    customer_id=customer_id,
                    operations=apply_recommendation_operations,
                )
            )

            for resp in recommendation_response:
                for row in resp.results:
                    print(
                        f"Applied recommendation with resource name:  \
                        {recommendation_response.resource_name}"
                    )

        print(
            f"Waiting {SECONDS_TO_WAIT} seconds before checking for additional \
                recommendations."
        )
        time.sleep(float(SECONDS_TO_WAIT))


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=("Detectes and applies a specified recommendation.")
    )
    # 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 2022 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.
#
# The auto-apply feature, which automatically applies recommendations as they
# become eligible, is currently supported by the Google Ads UI but not by the
# Google Ads API. See https://support.google.com/google-ads/answer/10279006 for
# more information on using auto-apply in the Google Ads UI.
#
# This example demonstrates how an alternative can be implemented with the
# features that are currently supported by the Google Ads API. It periodically
# retrieves and applies `KEYWORD` recommendations with default parameters.

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

def detect_and_apply_recommendations(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

  query = <<~QUERY
    SELECT recommendation.resource_name
    FROM recommendation
    WHERE recommendation.type = KEYWORD
    LIMIT #{MAX_RESULT_SIZE}
  QUERY

  reccomendation_service = client.service.recommendation
  google_ads_service = client.service.google_ads
  NUMBER_OF_RUNS.times do |i|
    search_response = google_ads_service.search(
      customer_id: customer_id,
      query: query,
    )
    operations = search_response.map do |row|
      client.operation.apply_recommendation do |aro|
        aro.resource_name = row.recommendation.resource_name
      end
    end

    unless operations.empty?
      response = recommendation_service.apply_recommendation(
        customer_id: customer_id,
        operations: operations,
      )

      response.each do |result|
        puts "Applied recommendation with resource name #{result.resource_name}."
      end
    end

    if i < NUMBER_OF_RUNS - 1
      puts "Waiting #{PERIOD_IN_SECONDS} seconds before applying more recommendations."
      sleep(PERIOD_IN_SECONDS)
    end
  end
end

if __FILE__ == $0
  MAX_RESULT_SIZE = 2
  NUMBER_OF_RUNS = 3
  PERIOD_IN_SECONDS = 5

  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.

  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
    detect_and_apply_recommendations(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 2022, 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.
#
# The auto-apply feature, which automatically applies recommendations as they become eligible,
# is currently supported by the Google Ads UI but not by the Google Ads API. See
# https://support.google.com/google-ads/answer/10279006 for more information on using auto-apply
# in the Google Ads UI.
#
# This example demonstrates how an alternative can be implemented with the features that are
# currently supported by the Google Ads API. It periodically retrieves and applies `KEYWORD`
# recommendations with default parameters.

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::Utils::SearchStreamHandler;
use
  Google::Ads::GoogleAds::V11::Services::RecommendationService::ApplyRecommendationOperation;
use
  Google::Ads::GoogleAds::V11::Services::GoogleAdsService::SearchGoogleAdsStreamRequest;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Time::HiRes qw(sleep);

my $customer_id;

# The maximum number of recommendations to periodically retrieve and apply.
# In a real application, such a limit would typically not be used.
use constant MAX_RESULT_SIZE => 2;

# The number of times to retrieve and apply recommendations. In a real application,
# such a limit would typically not be used.
use constant NUMBER_OF_RUNS => 3;

# The time to wait between two runs. In a real application, this would typically be set to
# minutes or hours instead of seconds.
use constant PERIOD_IN_SECONDS => 5;

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

  # Create the search query.
  my $search_query =
    "SELECT recommendation.resource_name FROM recommendation " .
    "WHERE recommendation.type = KEYWORD LIMIT " . MAX_RESULT_SIZE;

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  for my $i (1 .. NUMBER_OF_RUNS) {
    my $search_stream_handler =
      Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
        service => $google_ads_service,
        request => {
          customerId => $customer_id,
          query      => $search_query
        }});

    # Create apply operations for all the recommendations found.
    my $apply_recommendation_operations = ();
    $search_stream_handler->process_contents(
      sub {
        my $google_ads_row = shift;
        push @$apply_recommendation_operations,
          Google::Ads::GoogleAds::V11::Services::RecommendationService::ApplyRecommendationOperation
          ->new({
            resourceName => $google_ads_row->{recommendation}{resource_name}});
      });

    if (defined $apply_recommendation_operations) {
      # Send the apply recommendation request and print information.
      my $apply_recommendation_response =
        $api_client->RecommendationService()->apply({
          customerId => $customer_id,
          operations => $apply_recommendation_operations
        });

      foreach my $result (@{$apply_recommendation_response->{results}}) {
        printf "Applied recommendation with resource name: '%s'.\n",
          $result->{resourceName};
      }
    }

    if ($i < NUMBER_OF_RUNS) {
      printf
        "Waiting %d seconds before checking for additional recommendations.\n",
        PERIOD_IN_SECONDS;
      sleep(PERIOD_IN_SECONDS);
    }

  }

  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.
detect_and_apply_recommendations($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

detect_and_apply_recommendations

=head1 DESCRIPTION

The auto-apply feature, which automatically applies recommendations as they become eligible,
is currently supported by the Google Ads UI but not by the Google Ads API. See
https://support.google.com/google-ads/answer/10279006 for more information on using auto-apply
in the Google Ads UI.

This example demonstrates how an alternative can be implemented with the features that are
currently supported by the Google Ads API. It periodically retrieves and applies `KEYWORD`
recommendations with default parameters.

=head1 SYNOPSIS

detect_and_apply_recommendations.pl [options]

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

=cut