Handle Expanded Text Ad Policy Violations

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.errorhandling;

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.v5.common.PolicyTopicEntry;
import com.google.ads.googleads.v5.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v5.errors.ErrorCode.ErrorCodeCase;
import com.google.ads.googleads.v5.errors.GoogleAdsError;
import com.google.ads.googleads.v5.errors.GoogleAdsException;
import com.google.ads.googleads.v5.errors.PolicyFindingDetails;
import com.google.ads.googleads.v5.resources.AdGroupAd;
import com.google.ads.googleads.v5.services.AdGroupAdOperation;
import com.google.ads.googleads.v5.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v5.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v5.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Demonstrates how to request an exemption for policy violations of an expanded text ad. If the
 * request somehow fails with exceptions that are not policy finding errors, the example will stop
 * instead of trying sending an exemption request.
 */
public class HandleExpandedTextAdPolicyViolations {

  private static class HandleExpandedTextAdPolicyViolationsParams extends CodeSampleParams {

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

    @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
    private Long adGroupId;
  }

  public static void main(String[] args) {
    HandleExpandedTextAdPolicyViolationsParams params =
        new HandleExpandedTextAdPolicyViolationsParams();
    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");
      params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID");
    }
    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 HandleExpandedTextAdPolicyViolations()
          .runExample(googleAdsClient, params.customerId, params.adGroupId);
    } 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 client to use.
   * @param customerId the customer ID.
   * @param adGroupId the ad group ID.
   */
  public void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {
    // Creates an ad group ad for the specified ad group.
    AdGroupAd.Builder adGroupAdBuilder =
        AdGroupAd.newBuilder()
            .setAdGroup(ResourceNames.adGroup(customerId, adGroupId))
            .setStatus(AdGroupAdStatus.PAUSED);

    adGroupAdBuilder
        .getAdBuilder()
        // Sets the final URLS.
        .addFinalUrls("http://www.example.com")
        // Adds an expanded text ad.
        .getExpandedTextAdBuilder()
        .setHeadlinePart1("Cruise to Mars #" + System.currentTimeMillis())
        .setHeadlinePart2("Best Space Cruise Line")
        // Adds a description with too much punctuation. This will fail policy.
        .setDescription("Buy your tickets now!!!!!!!");

    // Constructs an operation to send to the API.
    AdGroupAdOperation operation =
        AdGroupAdOperation.newBuilder().setCreate(adGroupAdBuilder.build()).build();

    // Connects to the API. Note that we could use try-with-resources, however doing so would
    // require that we either (1) need to reconnect to the API for requesting the exemption, or (2)
    // introduce a doubly nested try-catch structure here.
    AdGroupAdServiceClient client =
        googleAdsClient.getLatestVersion().createAdGroupAdServiceClient();

    try {
      // Sends the request which we expect to fail with policy violations.
      client.mutateAdGroupAds(String.valueOf(customerId), ImmutableList.of(operation));
    } catch (GoogleAdsException ex) {
      // Retrieves the ignorable policy topics.
      List<String> ignorablePolicyTopics = fetchIgnorablePolicyTopics(ex);
      // Requests an exemption to add the creative with the known violations.
      requestExemption(ignorablePolicyTopics, client, operation, customerId);
    } finally {
      // Disconnects the API connection. Very important!
      client.close();
    }
  }

  /**
   * Collects all ignorable policy topics that will be sent for exemption request later.
   *
   * @param gae the Google Ads exception.
   * @return the ignorable policy topics.
   */
  private List<String> fetchIgnorablePolicyTopics(GoogleAdsException gae) {
    System.out.println("Google Ads failure details:");

    // Creates a list to store the result.
    List<String> ignorableTopics = new ArrayList<>();

    // Searches all errors for ignorable policy topics.
    for (GoogleAdsError error : gae.getGoogleAdsFailure().getErrorsList()) {
      // Supports sending exemption request for the policy finding error only.
      if (error.getErrorCode().getErrorCodeCase() != ErrorCodeCase.POLICY_FINDING_ERROR) {
        throw gae;
      }

      // Shows some information about the error encountered.
      System.out.printf("\t%s: %s%n", error.getErrorCode().getErrorCodeCase(), error.getMessage());

      // Checks policy finding details for ignorable policy topics.
      if (error.getDetails() != null) {
        PolicyFindingDetails policyFindingDetails = error.getDetails().getPolicyFindingDetails();
        if (policyFindingDetails != null) {
          System.out.println("\tPolicy finding details:");
          // Shows all the policy topics for the current error.
          for (PolicyTopicEntry policyTopicEntry :
              policyFindingDetails.getPolicyTopicEntriesList()) {
            // Adds this topic to the result.
            ignorableTopics.add(policyTopicEntry.getTopic());
            System.out.printf("\t\tPolicy topic name: '%s'%n", policyTopicEntry.getTopic());
            System.out.printf("\t\tPolicy topic entry type: '%s'%n", policyTopicEntry.getType());
            // For the sake of brevity, we exclude printing "policy topic evidences" and
            // "policy topic constraints" here. You can fetch those data by calling:
            // - policyTopicEntry.getEvidences()
            // - policyTopicEntry.getConstraints()
          }
        }
      }
    }
    return ignorableTopics;
  }

  /**
   * Sends exemption requests for creating an expanded text ad.
   *
   * @param ignorablePolicyTopics topics to request exemption for.
   * @param client client to use for API access.
   * @param operation operation which generated original violations.
   * @param customerID the customer ID to operate on.
   */
  private void requestExemption(
      List<String> ignorablePolicyTopics,
      AdGroupAdServiceClient client,
      AdGroupAdOperation operation,
      long customerID) {
    System.out.println(
        "Trying to add an expanded text ad again by requesting exemption for its policy"
            + " violations.");
    // Converts the operation back to a builder.
    AdGroupAdOperation.Builder operationBuilder = operation.toBuilder();

    // Adds the exemption request.
    operationBuilder
        .getPolicyValidationParameterBuilder()
        .addAllIgnorablePolicyTopics(ignorablePolicyTopics);

    // Sends the request back to the API.
    MutateAdGroupAdsResponse response =
        client.mutateAdGroupAds(
            String.valueOf(customerID), ImmutableList.of(operationBuilder.build()));

    // Shows the newly added ad resource name.
    System.out.printf(
        "Successfully added an expanded text ad with resource name '%s' by requesting a policy"
            + " violation exemption.%n",
        response.getResults(0).getResourceName());
  }
}

PHP

<?php

/**
 * Copyright 2019 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\ErrorHandling;

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\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V5\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V5\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V5\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V5\ResourceNames;
use Google\Ads\GoogleAds\V5\Common\ExpandedTextAdInfo;
use Google\Ads\GoogleAds\V5\Common\PolicyTopicEntry;
use Google\Ads\GoogleAds\V5\Common\PolicyValidationParameter;
use Google\Ads\GoogleAds\V5\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V5\Enums\PolicyTopicEntryTypeEnum\PolicyTopicEntryType;
use Google\Ads\GoogleAds\V5\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V5\Resources\Ad;
use Google\Ads\GoogleAds\V5\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V5\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V5\Services\AdGroupAdServiceClient;
use Google\ApiCore\ApiException;

/**
 * This example demonstrates how to request an exemption for policy violations of an expanded text
 * ad. If the request somehow fails with exceptions that are not policy finding errors, the example
 * will stop instead of trying sending an exemption request.
 */
class HandleExpandedTextAdPolicyViolations
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_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::AD_GROUP_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,
                $options[ArgumentNames::AD_GROUP_ID] ?: self::AD_GROUP_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
     * @param int $adGroupId the ad group ID to add an expanded text ad to
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $adGroupId
    ) {
        // Creates an expanded text ad info object.
        $expandedTextAdInfo = new ExpandedTextAdInfo([
            'headline_part1' => 'Cruise to Mars #' . uniqid(),
            'headline_part2' => 'Best Space Cruise Line',
            // Intentionally use an ad text that violates policy -- having too many exclamation
            // marks.
            'description' => 'Buy your tickets now!!!!!!!'
        ]);

        // Creates an ad group ad to hold the above ad.
        $adGroupAd = new AdGroupAd([
            'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
            // Set the ad group ad to PAUSED to prevent it from immediately serving.
            // Set to ENABLED once you've added targeting and the ad are ready to serve.
            'status' => AdGroupAdStatus::PAUSED,
            // Sets the expanded text ad info on an Ad.
            'ad' => new Ad([
                'expanded_text_ad' => $expandedTextAdInfo,
                'final_urls' => ['http://www.example.com']
            ])
        ]);

        // Creates an ad group ad operation.
        $adGroupAdOperation = new AdGroupAdOperation();
        $adGroupAdOperation->setCreate($adGroupAd);
        $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();

        $ignorablePolicyTopics = [];
        try {
            // Try sending a mutate request to add the ad group ad.
            $adGroupAdServiceClient->mutateAdGroupAds($customerId, [$adGroupAdOperation]);
        } catch (GoogleAdsException $googleAdsException) {
            // The request will always fail because of the policy violation in the description of
            // the ad.
            $ignorablePolicyTopics = self::fetchIgnorablePolicyTopics($googleAdsException);
        }

        // Try sending exemption requests for creating an expanded text ad.
        self::requestExemption(
            $customerId,
            $adGroupAdServiceClient,
            $adGroupAdOperation,
            $ignorablePolicyTopics
        );
    }

    /**
     * Collects all ignorable policy topics that will be sent for exemption request later.
     *
     * @param GoogleAdsException $googleAdsException the Google Ads exception
     * @return string[] the ignorable policy topics
     */
    private static function fetchIgnorablePolicyTopics(GoogleAdsException $googleAdsException)
    {
        $ignorablePolicyTopics = [];

        printf("Google Ads failure details:%s", PHP_EOL);
        foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
            /** @var GoogleAdsError $error */
            if ($error->getErrorCode()->getErrorCode() !== 'policy_finding_error') {
                // This example supports sending exemption request for the policy finding error
                // only.
                throw $googleAdsException;
            }

            printf(
                "\t%s: %s%s",
                $error->getErrorCode()->getErrorCode(),
                $error->getMessage(),
                PHP_EOL
            );
            if (
                !is_null($error->getDetails())
                && !is_null($error->getDetails()->getPolicyFindingDetails())
            ) {
                $policyFindingDetails = $error->getDetails()->getPolicyFindingDetails();
                printf("\tPolicy finding details:%s", PHP_EOL);

                foreach ($policyFindingDetails->getPolicyTopicEntries() as $policyTopicEntry) {
                    /** @var PolicyTopicEntry $policyTopicEntry */
                    $ignorablePolicyTopics[] = $policyTopicEntry->getTopic();
                    printf(
                        "\t\tPolicy topic name: '%s'%s",
                        $policyTopicEntry->getTopic(),
                        PHP_EOL
                    );
                    printf(
                        "\t\tPolicy topic entry type: '%s'%s",
                        PolicyTopicEntryType::name($policyTopicEntry->getType()),
                        PHP_EOL
                    );
                    // For the sake of brevity, we exclude printing "policy topic evidences" and
                    // "policy topic constraints" here. You can fetch those data by calling:
                    // - $policyTopicEntry->getEvidences()
                    // - $policyTopicEntry->getConstraints()
                }
            }
        }
        return $ignorablePolicyTopics;
    }

    /**
     * Sends exemption requests for creating an expanded text ad.
     *
     * @param int $customerId
     * @param AdGroupAdServiceClient $adGroupAdServiceClient
     * @param AdGroupAdOperation $adGroupAdOperation
     * @param string[] $ignorablePolicyTopics
     */
    private static function requestExemption(
        int $customerId,
        AdGroupAdServiceClient $adGroupAdServiceClient,
        AdGroupAdOperation $adGroupAdOperation,
        array $ignorablePolicyTopics
    ) {
        print "Try adding an expanded text ad again by requesting exemption for its policy"
            . " violations." . PHP_EOL;
        $adGroupAdOperation->setPolicyValidationParameter(
            new PolicyValidationParameter(['ignorable_policy_topics' => $ignorablePolicyTopics])
        );
        $response = $adGroupAdServiceClient->mutateAdGroupAds(
            $customerId,
            [$adGroupAdOperation]
        );
        printf(
            "Successfully added an expanded text ad with resource name '%s' by requesting"
            . " for policy violation exemption.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }
}

HandleExpandedTextAdPolicyViolations::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.
"""Requests an exemption for policy violations of an expanded text ad.

If the request somehow fails with exceptions that are not policy finding
errors, the example will stop instead of trying sending an exemption request.
"""

import argparse
import sys
import uuid

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


def main(client, customer_id, ad_group_id):
    """Uses Customer Match to create and add users to a new user list.

    Args:
        client: The Google Ads client.
        customer_id: The customer ID for which to add the expanded text ad.
        ad_group_id: The ad group ID to which to add an expanded text ad.
    """

    ad_group_ad_service_client = client.get_service(
        "AdGroupAdService", version="v5"
    )

    ad_group_ad_operation, ignorable_policy_topics = _create_expanded_text_ad(
        client, ad_group_ad_service_client, customer_id, ad_group_id
    )

    try:
        _request_exemption(
            customer_id,
            ad_group_ad_service_client,
            ad_group_ad_operation,
            ignorable_policy_topics,
        )
    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)


def _create_expanded_text_ad(
    client, ad_group_ad_service_client, customer_id, ad_group_id
):
    """Create an expanded text ad that includes a policy violation.

    Args:
        client: The GoogleAds client instance.
        ad_group_ad_service_client: The AdGroupAdService client instance.
        customer_id: The customer ID for which to add the expanded text ad.
        ad_group_id: The ad group ID to which to add an expanded text ad.

    Returns:
        The attempted AdGroupAdOperation instance and a list of ignorable
        policy topics.
    """
    ad_group_resource_name = client.get_service(
        "AdGroupService", version="v5"
    ).ad_group_path(customer_id, ad_group_id)

    # Creates an operation and ad group ad to create and hold the above ad.
    ad_group_ad_operation = client.get_type("AdGroupAdOperation", version="v5")
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group = ad_group_resource_name
    # Set the ad group ad to PAUSED to prevent it from immediately serving.
    # Set to ENABLED once you've added targeting and the ad are ready to serve.
    ad_group_ad.status = client.get_type(
        "AdGroupAdStatusEnum", version="v5"
    ).PAUSED
    # Sets the expanded text ad info on an ad.
    expanded_text_ad_info = ad_group_ad.ad.expanded_text_ad
    expanded_text_ad_info.headline_part1 = (
        f"Cruise to Mars #{str(uuid.uuid4())[0:13]}"
    )
    expanded_text_ad_info.headline_part2 = "Best Space Cruise Line"
    # Intentionally use an ad text that violates policy by having too many
    # exclamation marks.
    expanded_text_ad_info.description = "Buy your tickets now!!!!!!!"
    ad_group_ad.ad.final_urls.append("http://www.example.com")

    ignorable_policy_topics = []
    try:
        # Try sending a mutate request to add the ad group ad.
        ad_group_ad_service_client.mutate_ad_group_ads(
            customer_id, [ad_group_ad_operation]
        )
    except GoogleAdsException as google_ads_exception:
        # The request will always fail due to the policy violation in the
        # ad's description.
        ignorable_policy_topics = _fetch_ignorable_policy_topics(
            client, google_ads_exception
        )

    return ad_group_ad_operation, ignorable_policy_topics


def _fetch_ignorable_policy_topics(client, google_ads_exception):
    """Collects all ignorable policy topics to be sent for exemption request.

    Args:
        client: The GoogleAds client instance.
        google_ads_exception: The exception that contains the policy
            violation(s).

    Returns:
        A list of ignorable policy topics.
    """
    ignorable_policy_topics = []

    print("Google Ads failure details:")
    for error in google_ads_exception.failure.errors:
        if (
            error.error_code.policy_finding_error
            != client.get_type(
                "PolicyFindingErrorEnum", version="v5"
            ).POLICY_FINDING
        ):
            print(
                "This example supports sending exemption request for the "
                "policy finding error only."
            )
            raise google_ads_exception

        print(f"\t{error.error_code.policy_finding_error}: {error.message}")

        if (
            error.details is not None
            and error.details.policy_finding_details is not None
        ):
            policy_finding_details = error.details.policy_finding_details
            print("\tPolicy finding details:")

            for (
                policy_topic_entry
            ) in policy_finding_details.policy_topic_entries:
                ignorable_policy_topics.append(policy_topic_entry.topic)
                print(f"\t\tPolicy topic name: '{policy_topic_entry.topic}'")
                print(
                    f"\t\tPolicy topic entry type: '{policy_topic_entry.type}'"
                )
                # For the sake of brevity, we exclude printing "policy topic
                # evidences" and "policy topic constraints" here. You can fetch
                # those data by calling:
                # - policy_topic_entry.evidences
                # - policy_topic_entry.constraints

    return ignorable_policy_topics


def _request_exemption(
    customer_id,
    ad_group_ad_service_client,
    ad_group_ad_operation,
    ignorable_policy_topics,
):
    """Sends exemption requests for creating an expanded text ad.

    Args:
        customer_id: The customer ID for which to add the expanded text ad.
        ad_group_ad_service_client: The AdGroupAdService client instance.
        ad_group_ad_operation: The AdGroupAdOperation that returned policy
            violation(s).
        ignorable_policy_topics: The extracted list of policy topic entries.
    """
    print(
        "Attempting to add an expanded text ad again by requesting exemption "
        "for its policy violations."
    )
    ad_group_ad_operation.policy_validation_parameter.ignorable_policy_topics.extend(
        ignorable_policy_topics
    )
    response = ad_group_ad_service_client.mutate_ad_group_ads(
        customer_id, [ad_group_ad_operation]
    )
    print(
        "Successfully added an expanded text ad with resource name "
        f"'{response.results[0].resource_name}' for policy violation "
        "exemption."
    )


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = GoogleAdsClient.load_from_storage()

    parser = argparse.ArgumentParser(
        description="Requests an exemption for expanded text ad policy "
        "violations."
    )
    # 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(
        "-a",
        "--ad_group_id",
        type=str,
        required=True,
        help="The ad group ID to which to add an expanded text ad.",
    )
    args = parser.parse_args()

    main(google_ads_client, args.customer_id, args.ad_group_id)

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.
#
# Requests an exemption for policy violations of an expanded text ad.
#
# If the request somehow fails with exceptions that are not policy finding
# errors, the example will stop instead of trying to send an exemption request.

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

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

  ad_group_ad_operation, ignorable_policy_topics = create_expanded_text_ad(
    client,
    ad_group_ad_service,
    customer_id,
    ad_group_id,
  )

  request_exemption(
    client,
    customer_id,
    ad_group_ad_service,
    ad_group_ad_operation,
    ignorable_policy_topics,
  )
end

def create_expanded_text_ad(client, ad_group_ad_service, customer_id, ad_group_id)
  ad_group_ad_operation = client.operation.create_resource.ad_group_ad do |aga|
    aga.ad_group = client.path.ad_group(customer_id, ad_group_id)
    aga.status = :PAUSED

    aga.ad = client.resource.ad do |ad|
      ad.final_urls << "http://www.example.com"
      ad.expanded_text_ad = client.resource.expanded_text_ad_info do |eta|
        eta.headline_part1 = "Cruise to Mars ##{(Time.new.to_f * 1000).to_i}"
        eta.headline_part2 = "Best space cruise line"
        eta.description = "Buy your tickets now!!!!!!!"
      end
    end
  end

  ignorable_policy_topics = []
  begin
    ad_group_ad_service.mutate_ad_group_ads(
      customer_id: customer_id,
      operations: [ad_group_ad_operation],
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    ignorable_policy_topics = fetch_ignorable_policy_topics(e)
  end

  return ad_group_ad_operation, ignorable_policy_topics
end

def fetch_ignorable_policy_topics(exception)
  ignorable_policy_topics = []

  exception.failure.errors.each do |error|
    if error.error_code.policy_finding_error != :POLICY_FINDING
      puts "Non-policy finding error found. Aborting."
      raise exception
    end
    puts "#{error.error_code.policy_finding_error}: #{error.message}"

    error&.details&.policy_finding_details&.policy_topic_entries.each do |entry|
      ignorable_policy_topics << entry.topic
      puts "\tPolicy topic name: #{entry.topic}"
      puts "\tPolicy topic entry type: #{entry.type}"
    end
  end

  ignorable_policy_topics
end

def request_exemption(
    client, customer_id, ad_group_ad_service, ad_group_ad_operation, ignorable_policy_topics)
  # Add all the found ignorable policy topics to the operation.
  ad_group_ad_operation.policy_validation_parameter =
      client.resource.policy_validation_parameter do |pvp|
    pvp.ignorable_policy_topics.push(
      *ignorable_policy_topics
    )
  end
  response = ad_group_ad_service.mutate_ad_group_ads(
    customer_id: customer_id,
    operations: [ad_group_ad_operation],
  )
  puts "Successfully added an expanded text ad with resource name " \
    "#{response.results.first.resource_name} for policy violation exception."
end

if __FILE__ == $PROGRAM_NAME
  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[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %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('-A', '--ad-group-id AD-GROUP-ID', String, 'Ad Group ID') do |v|
      options[:ad_group_id] = v
    end

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

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

  begin
    handle_expanded_text_ad_policy_violations(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:ad_group_id),
    )
  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 2019, 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.
#
# This example demonstrates how to request an exemption for policy violations
# of an expanded text ad. If the request somehow fails with exceptions that are
# not policy finding errors, the example will stop instead of trying sending an
# exemption request.

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::V5::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V5::Resources::Ad;
use Google::Ads::GoogleAds::V5::Common::ExpandedTextAdInfo;
use Google::Ads::GoogleAds::V5::Common::PolicyValidationParameter;
use Google::Ads::GoogleAds::V5::Enums::AdGroupStatusEnum qw(PAUSED);
use Google::Ads::GoogleAds::V5::Services::AdGroupAdService::AdGroupAdOperation;
use Google::Ads::GoogleAds::V5::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 $ad_group_id = "INSERT_AD_GROUP_ID_HERE";

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

  my $ad_group_resource_name =
    Google::Ads::GoogleAds::V5::Utils::ResourceNames::ad_group($customer_id,
    $ad_group_id);

  # Create an expanded text ad info object.
  my $expanded_text_ad_info =
    Google::Ads::GoogleAds::V5::Common::ExpandedTextAdInfo->new({
      headlinePart1 => "Cruise to Mars #" . uniqid(),
      headlinePart2 => "Best Space Cruise Line",
      # Intentionally use an ad text that violates policy -- having too many
      # exclamation marks.
      description => "Buy your tickets now!!!!!!!"
    });

  # Create an ad group ad to hold the above ad.
  my $ad_group_ad = Google::Ads::GoogleAds::V5::Resources::AdGroupAd->new({
      adGroup => $ad_group_resource_name,
      # Set the ad group ad to PAUSED to prevent it from immediately serving.
      # Set to ENABLED once you've added targeting and the ad are ready to serve.
      status => PAUSED,
      # Set the expanded text ad info on an ad.
      ad => Google::Ads::GoogleAds::V5::Resources::Ad->new({
          expandedTextAd => $expanded_text_ad_info,
          finalUrls      => ["http://www.example.com"]})});

  # Create an ad group ad operation.
  my $ad_group_ad_operation =
    Google::Ads::GoogleAds::V5::Services::AdGroupAdService::AdGroupAdOperation
    ->new({
      create => $ad_group_ad
    });

  # Try sending a mutate request to add the ad group ad.
  my $response = $api_client->AdGroupAdService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_ad_operation]});

  my $ignorable_policy_topics = [];
  if ($response->isa("Google::Ads::GoogleAds::GoogleAdsException")) {
    # The request will always fail because of the policy violation in the
    # description of the ad.
    $ignorable_policy_topics = fetch_ignorable_policy_topics($response);
  }

  # Try sending exemption requests for creating an expanded text ad.
  request_exemption($api_client, $customer_id, $ad_group_ad_operation,
    $ignorable_policy_topics);

  return 1;
}

# Collects all ignorable policy topics that will be sent for exemption request
# later.
sub fetch_ignorable_policy_topics {
  my $google_ads_exception = shift;

  my $ignorable_policy_topics = [];

  printf "Google Ads failure details:\n";
  foreach
    my $error (@{$google_ads_exception->get_google_ads_failure()->{errors}})
  {
    if ([keys %{$error->{errorCode}}]->[0] ne "policyFindingError") {
      # This example supports sending exemption request for the policy finding
      # error only.
      die $google_ads_exception->get_message();
    }

    printf "\t%s: %s\n", [keys %{$error->{errorCode}}]->[0], $error->{message};

    if ($error->{details}{policyFindingDetails}) {
      my $policy_finding_details = $error->{details}{policyFindingDetails};
      printf "\tPolicy finding details:\n";

      foreach my $policy_topic_entry (
        @{$policy_finding_details->{policyTopicEntries}})
      {
        push @$ignorable_policy_topics, $policy_topic_entry->{topic};
        printf
          "\t\tPolicy topic name: '%s'\n",
          $policy_topic_entry->{topic};
        printf "\t\tPolicy topic entry type: '%s'\n",
          $policy_topic_entry->{type};
        # For the sake of brevity, we exclude printing "policy topic evidences" and
        # "policy topic constraints" here. You can fetch those data by calling:
        # - $policy_topic_entry->{evidences}
        # - $policy_topic_entry->{constraints}
      }
    }
  }

  return $ignorable_policy_topics;
}

# Sends exemption requests for creating an expanded text ad.
sub request_exemption {
  my ($api_client, $customer_id, $ad_group_ad_operation,
    $ignorable_policy_topics)
    = @_;

  print
    "Try adding an expanded text ad again by requesting exemption for its " .
    "policy violations.\n";

  $ad_group_ad_operation->{policyValidationParameter} =
    Google::Ads::GoogleAds::V5::Common::PolicyValidationParameter->new(
    {ignorablePolicyTopics => $ignorable_policy_topics});

  my $ad_group_ad_response = $api_client->AdGroupAdService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_ad_operation]});

  printf "Successfully added an expanded text ad with resource name '%s' by " .
    "requesting for policy violation exemption.\n",
    $ad_group_ad_response->{results}[0]{resourceName};
}

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

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s" => \$customer_id,
  "ad_group_id=i" => \$ad_group_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, $ad_group_id);

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

=pod

=head1 NAME

handle_expanded_text_ad_policy_violations

=head1 DESCRIPTION

This example demonstrates how to request an exemption for policy violations of an
expanded text ad. If the request somehow fails with exceptions that are not policy
finding errors, the example will stop instead of trying sending an exemption request.

=head1 SYNOPSIS

handle_expanded_text_ad_policy_violations.pl [options]

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

=cut