サイトリンク キャンペーンの広告表示オプションの設定を更新

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

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.lib.utils.FieldMasks;
import com.google.ads.googleads.v11.enums.ExtensionTypeEnum.ExtensionType;
import com.google.ads.googleads.v11.errors.GoogleAdsError;
import com.google.ads.googleads.v11.errors.GoogleAdsException;
import com.google.ads.googleads.v11.resources.CampaignExtensionSetting;
import com.google.ads.googleads.v11.services.CampaignExtensionSettingOperation;
import com.google.ads.googleads.v11.services.CampaignExtensionSettingServiceClient;
import com.google.ads.googleads.v11.services.MutateCampaignExtensionSettingsResponse;
import com.google.ads.googleads.v11.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Updates the sitelink campaign extension setting to replace its extension feed items. Note that
 * this doesn't completely remove your old extension feed items.
 *
 * <p>See https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview
 * for details.
 */
public class UpdateSitelinkCampaignExtensionSetting {

  private static class UpdateSitelinkCampaignExtensionSettingParams extends CodeSampleParams {
    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
    private long campaignId;

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

  public static void main(String[] args) {
    UpdateSitelinkCampaignExtensionSettingParams params =
        new UpdateSitelinkCampaignExtensionSettingParams();
    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.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
      params.feedItemIds = ImmutableList.of(Long.parseLong("INSERT_FEED_ITEM_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 UpdateSitelinkCampaignExtensionSetting()
          .runExample(googleAdsClient, params.customerId, params.campaignId, params.feedItemIds);
    } 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. */
  private void runExample(
      GoogleAdsClient googleAdsClient, long customerId, long campaignId, List<Long> feedItemIds) {
    // Converts the feed item IDs into resource names.
    List<String> feedItemResourceNames =
        feedItemIds.stream()
            .map(id -> ResourceNames.extensionFeedItem(customerId, id))
            .collect(Collectors.toList());

    // Creates a CampaignExtensionSetting object to update.
    CampaignExtensionSetting campaignExtensionSetting =
        CampaignExtensionSetting.newBuilder()
            .setResourceName(
                ResourceNames.campaignExtensionSetting(
                    customerId, campaignId, ExtensionType.SITELINK))
            .addAllExtensionFeedItems(feedItemResourceNames)
            .build();

    // Creates an operation to update CampaignExtensionSetting.
    CampaignExtensionSettingOperation operation =
        CampaignExtensionSettingOperation.newBuilder()
            .setUpdate(campaignExtensionSetting)
            .setUpdateMask(FieldMasks.allSetFieldsOf(campaignExtensionSetting))
            .build();

    // Connects to the API.
    try (CampaignExtensionSettingServiceClient client =
        googleAdsClient.getLatestVersion().createCampaignExtensionSettingServiceClient()) {
      // Issues the mutate request.
      MutateCampaignExtensionSettingsResponse response =
          client.mutateCampaignExtensionSettings(
              String.valueOf(customerId), ImmutableList.of(operation));

      // Prints some debugging information.
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Updated a campaign extension setting with resource name: '%s'.%n", resourceName);
    }
  }
}

      

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.Gax.Util;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V11.Errors;
using Google.Ads.GoogleAds.V11.Resources;
using Google.Ads.GoogleAds.V11.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V11.Enums.ExtensionTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V11
{
    /// <summary>
    /// Updates the sitelink campaign extension setting to replace its extension feed items. Note
    /// that this doesn't completely remove your old extension feed items. See
    /// https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview
    /// for details.
    /// </summary>
    public class UpdateSitelinkCampaignExtensionSetting : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="UpdateSitelinkCampaignExtensionSetting"/>
        /// 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 campaign ID.
            /// </summary>
            [Option("campaignId", Required = true, HelpText =
                "The campaign ID.")]
            public long CampaignId { get; set; }

            /// <summary>
            /// The extension feed item IDs to replace.
            /// </summary>
            [Option("feedItemIds", Required = true, HelpText =
                "The extension feed item IDs to replace.")]
            public IEnumerable<long> FeedItemIds { 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);

            UpdateSitelinkCampaignExtensionSetting codeExample =
                new UpdateSitelinkCampaignExtensionSetting();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId,
                options.FeedItemIds.ToArray());
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "Updates the sitelink campaign extension setting to replace its extension feed " +
            "items. Note that this doesn't completely remove your old extension feed items. See " +
            "https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview" +
            " for details.";

        /// <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="campaignId">The campaign ID.</param>
        /// <param name="feedItemIds">The extension feed item IDs to replace.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId,
            long[] feedItemIds)
        {
            // Get the CampaignExtensionSettingService.
            CampaignExtensionSettingServiceClient campaignExtensionSettingService =
                client.GetService(Services.V11.CampaignExtensionSettingService);

            // Transform the specified extension feed item IDs to an array of resource names.
            IEnumerable<string> extensionFeedItems = feedItemIds.Select(feedItemId =>
                ResourceNames.ExtensionFeedItem(customerId, feedItemId));

            // Create a campaign extension setting using the specified campaign ID and extension
            // feed item resource names.
            CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting
            {
                ResourceName = ResourceNames.CampaignExtensionSetting(customerId, campaignId,
                    ExtensionType.Sitelink)
            };
            campaignExtensionSetting.ExtensionFeedItems.Add(extensionFeedItems);

            // Construct an operation that will update the extension feed item using the FieldMasks
            // utilities to derive the update mask. This mask tells the Google Ads API which
            // attributes of the extension feed item you want to change.
            CampaignExtensionSettingOperation campaignExtensionSettingOperation =
                new CampaignExtensionSettingOperation
                {
                    Update = campaignExtensionSetting,
                    UpdateMask = FieldMasks.AllSetFieldsOf(campaignExtensionSetting)
                };

            try
            {
                // Issue a mutate request to update the campaign extension setting.
                MutateCampaignExtensionSettingsResponse response =
                    campaignExtensionSettingService.MutateCampaignExtensionSettings
                        (customerId.ToString(), new[] { campaignExtensionSettingOperation });

                // Print the resource name of the updated campaign extension setting.
                Console.WriteLine("Updated a campaign extension setting 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\Extensions;

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\V11\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsException;
use Google\Ads\GoogleAds\Util\FieldMasks;
use Google\Ads\GoogleAds\Util\V11\ResourceNames;
use Google\Ads\GoogleAds\V11\Enums\ExtensionTypeEnum\ExtensionType;
use Google\Ads\GoogleAds\V11\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V11\Resources\CampaignExtensionSetting;
use Google\Ads\GoogleAds\V11\Services\CampaignExtensionSettingOperation;
use Google\ApiCore\ApiException;

/**
 * Updates the sitelink campaign extension setting to replace its extension feed items.
 * Note that this doesn't completely remove your old extension feed items.
 * See https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview
 * for details.
 */
class UpdateSitelinkCampaignExtensionSetting
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
    private const FEED_ITEM_ID1 = 'INSERT_FEED_ITEM_ID1_HERE';
    private const FEED_ITEM_ID2 = 'INSERT_FEED_ITEM_ID2_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::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::FEED_ITEM_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)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID,
                $options[ArgumentNames::FEED_ITEM_IDS] ?:
                    [self::FEED_ITEM_ID1, self::FEED_ITEM_ID2]
            );
        } 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 client customer ID
     * @param int $campaignId the campaign ID
     * @param int[] $feedItemIds the IDs of the feed items to replace
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId,
        array $feedItemIds
    ) {
        // Transforms the specified feed item IDs to resource names as required by the API.
        $extensionFeedItems = array_map(function ($feedItemId) use ($customerId) {
            return ResourceNames::forExtensionFeedItem($customerId, $feedItemId);
        }, $feedItemIds);

        // Creates a campaign extension setting using the specified campaign ID and extension feed
        // item resource names.
        $campaignExtensionSetting = new CampaignExtensionSetting([
            'resource_name' => ResourceNames::forCampaignExtensionSetting(
                $customerId,
                $campaignId,
                ExtensionType::name(ExtensionType::SITELINK)
            ),
            'extension_feed_items' => $extensionFeedItems
        ]);

        // Constructs an operation that will update the campaign extension setting, using the
        // FieldMasks utility to derive the update mask. This mask tells the Google Ads API which
        // attributes of the campaign extension setting you want to change.
        $campaignExtensionSettingOperation = new CampaignExtensionSettingOperation();
        $campaignExtensionSettingOperation->setUpdate($campaignExtensionSetting);
        $campaignExtensionSettingOperation->setUpdateMask(
            FieldMasks::allSetFieldsOf($campaignExtensionSetting)
        );

        // Issues a mutate request to update the campaign extension setting.
        $campaignExtensionSettingServiceClient =
            $googleAdsClient->getCampaignExtensionSettingServiceClient();
        $response = $campaignExtensionSettingServiceClient->mutateCampaignExtensionSettings(
            $customerId,
            [$campaignExtensionSettingOperation]
        );

        // Prints the resource name of the updated campaign extension setting.
        /** @var CampaignExtensionSetting $updatedCampaignExtensionSetting */
        $updatedCampaignExtensionSetting = $response->getResults()[0];
        printf(
            "Updated a campaign extension setting with resource name: '%s'.%s",
            $updatedCampaignExtensionSetting->getResourceName(),
            PHP_EOL
        );
    }
}

UpdateSitelinkCampaignExtensionSetting::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.
"""Updates the sitelink campaign extension setting.

Replaces the extension feed items of the sitelink campaign extension setting
with the given feed item IDs. Note that this doesn't completely remove your
old extension feed items. See
https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview
for details.
"""


import argparse
import sys

from google.api_core import protobuf_helpers

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


def main(client, customer_id, campaign_id, feed_item_ids):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        campaign_id: the campaign ID.
        feed_item_ids: the IDs the feed items to replace.
    """
    campaign_extension_setting_service = client.get_service(
        "CampaignExtensionSettingService"
    )
    campaign_extension_setting_operation = client.get_type(
        "CampaignExtensionSettingOperation"
    )
    extension_feed_item_service = client.get_service("ExtensionFeedItemService")

    campaign_extension_setting = campaign_extension_setting_operation.update
    # Replace the current extension feed items with the given list
    campaign_extension_setting.extension_feed_items.extend(
        [
            extension_feed_item_service.extension_feed_item_path(
                customer_id, feed_item_id
            )
            for feed_item_id in feed_item_ids
        ]
    )

    extension_type_enum = client.enums.ExtensionTypeEnum
    resource_name = (
        campaign_extension_setting_service.campaign_extension_setting_path(
            customer_id, campaign_id, extension_type_enum.SITELINK.name
        )
    )
    campaign_extension_setting.resource_name = resource_name

    # Produce a field mask enumerating the changed fields
    client.copy_from(
        campaign_extension_setting_operation.update_mask,
        protobuf_helpers.field_mask(None, campaign_extension_setting._pb),
    )

    # Update the campaign extension settings
    response = (
        campaign_extension_setting_service.mutate_campaign_extension_settings(
            customer_id=customer_id,
            operations=[campaign_extension_setting_operation],
        )
    )
    print(
        "Updated campaign extension setting with resource name: "
        f'"{response.results[0].resource_name}".'
    )


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=(
            "Updates the sitelink campaign extension setting to replace its "
            "extension feed items."
        )
    )
    # 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(
        "-i",
        "--campaign_id",
        type=str,
        required=True,
        help="The campaign ID",
    )
    parser.add_argument(
        "-f",
        "--feed_item_ids",
        nargs="+",
        type=str,
        required=True,
        help="The IDs of the feed items to replace",
    )
    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.campaign_id,
            args.feed_item_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 2021 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.
#
# Updates the sitelink campaign extension setting.

# Replaces the extension feed items of the sitelink campaign extension setting
# with the given feed item IDs. Note that this doesn't completely remove your
# old extension feed items. See
# https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview
# for details.

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

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

  # Replace the current extension feed items with the given list
  operation = client.operation.update_resource.campaign_extension_setting(
    client.path.campaign_extension_setting(
      customer_id: customer_id,
      campaign_id: campaign_id,
      extension_type: :SITELINK
    )
  ) do |ces|
    feed_item_ids.each do |feed_item_id|
      # Transforms the specified feed item IDs to resource names as required by the API.
      ces.extension_feed_items << client.path.extension_feed_item(customer_id, feed_item_id)
    end
  end

  # Update the campaign extension settings
  response = client.service.campaign_extension_setting.mutate_campaign_extension_settings(
    customer_id: customer_id,
    operations: [operation],
  )

  puts "Updated campaign extension setting 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[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
  options[:feed_item_ids] = 'INSERT_FEED_ITEM_IDS_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('-s', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
      options[:campaign_id] = v
    end

    opts.on('-f', '--feed-item-ids FEED-ITEM-IDS', String, 'Comma separated list of Feed Item IDs') do |v|
      options[:feed_item_ids] = v
    end

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

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

  begin
    update_sitelink_campaign_extension_setting(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:campaign_id),
      options.fetch(:feed_item_ids).split(",").map(&:strip),
    )
  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.
#
# Updates the sitelink campaign extension setting to replace its extension feed
# items. Note that this doesn't completely remove your old extension feed items.
# See https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview
# for details.

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::FieldMasks;
use Google::Ads::GoogleAds::V11::Resources::CampaignExtensionSetting;
use Google::Ads::GoogleAds::V11::Enums::ExtensionTypeEnum qw(SITELINK);
use
  Google::Ads::GoogleAds::V11::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation;
use Google::Ads::GoogleAds::V11::Utils::ResourceNames;

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

# 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 $campaign_id   = "INSERT_CAMPAIGN_ID_HERE";
my $feed_item_id1 = "INSERT_FEED_ITEM_ID1_HERE";
my $feed_item_id2 = "INSERT_FEED_ITEM_ID2_HERE";
my $feed_item_ids = [];

sub update_sitelink_campaign_extension_setting {
  my ($api_client, $customer_id, $campaign_id, $feed_item_ids) = @_;

  # Transform the specified extension feed item IDs to the array of resource names.
  my $extension_feed_items = [
    map {
      Google::Ads::GoogleAds::V11::Utils::ResourceNames::extension_feed_item(
        $customer_id, $_)
    } @$feed_item_ids
  ];

  # Create a campaign extension setting using the specified campaign ID and
  # extension feed item resource names.
  my $campaign_extension_setting =
    Google::Ads::GoogleAds::V11::Resources::CampaignExtensionSetting->new({
      resourceName =>
        Google::Ads::GoogleAds::V11::Utils::ResourceNames::campaign_extension_setting(
        $customer_id, $campaign_id, SITELINK
        ),
      extensionFeedItems => $extension_feed_items
    });

  # Construct an operation that will update the campaign extension setting, using
  # the FieldMasks utility to derive the update mask. This mask tells the Google
  # Ads API which attributes of the campaign extension setting you want to change.
  my $campaign_extension_setting_operation =
    Google::Ads::GoogleAds::V11::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation
    ->new({
      update     => $campaign_extension_setting,
      updateMask => all_set_fields_of($campaign_extension_setting)});

  # Issue a mutate request to update the campaign extension setting.
  my $campaign_extension_settings_response =
    $api_client->CampaignExtensionSettingService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_extension_setting_operation]});

  # Print the resource name of the updated campaign extension setting.
  printf
    "Updated a campaign extension setting with resource name: '%s'.\n",
    $campaign_extension_settings_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,
  "campaign_id=i"   => \$campaign_id,
  "feed_item_ids=s" => \@$feed_item_ids,
);
$feed_item_ids = [$feed_item_id1, $feed_item_id2] unless @$feed_item_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, $campaign_id, $feed_item_ids);

# Call the example.
update_sitelink_campaign_extension_setting($api_client, $customer_id =~ s/-//gr,
  $campaign_id, $feed_item_ids);

=pod

=head1 NAME

update_sitelink_campaign_extension_setting

=head1 DESCRIPTION

Updates the sitelink campaign extension setting to replace its extension feed
items. Note that this doesn't completely remove your old extension feed items.
See https://developers.google.com/google-ads/api/docs/extensions/extension-settings/overview
for details.

=head1 SYNOPSIS

update_sitelink_campaign_extension_setting.pl [options]

    -help                           Show the help message.
    -customer_id                    The Google Ads customer ID.
    -campaign_id                    The campaign ID.
    -feed_item_ids                  The extension feed item IDs to replace.

=cut