Add Sitelinks

Java

// 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.

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.v5.common.AdScheduleInfo;
import com.google.ads.googleads.v5.common.KeywordInfo;
import com.google.ads.googleads.v5.common.SitelinkFeedItem;
import com.google.ads.googleads.v5.enums.DayOfWeekEnum.DayOfWeek;
import com.google.ads.googleads.v5.enums.ExtensionTypeEnum.ExtensionType;
import com.google.ads.googleads.v5.enums.FeedItemTargetDeviceEnum.FeedItemTargetDevice;
import com.google.ads.googleads.v5.enums.KeywordMatchTypeEnum.KeywordMatchType;
import com.google.ads.googleads.v5.enums.MinuteOfHourEnum.MinuteOfHour;
import com.google.ads.googleads.v5.errors.GoogleAdsError;
import com.google.ads.googleads.v5.errors.GoogleAdsException;
import com.google.ads.googleads.v5.resources.CampaignExtensionSetting;
import com.google.ads.googleads.v5.resources.ExtensionFeedItem;
import com.google.ads.googleads.v5.services.CampaignExtensionSettingOperation;
import com.google.ads.googleads.v5.services.CampaignExtensionSettingServiceClient;
import com.google.ads.googleads.v5.services.ExtensionFeedItemOperation;
import com.google.ads.googleads.v5.services.ExtensionFeedItemServiceClient;
import com.google.ads.googleads.v5.services.MutateCampaignExtensionSettingResult;
import com.google.ads.googleads.v5.services.MutateCampaignExtensionSettingsResponse;
import com.google.ads.googleads.v5.services.MutateExtensionFeedItemResult;
import com.google.ads.googleads.v5.services.MutateExtensionFeedItemsResponse;
import com.google.ads.googleads.v5.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;

/** Adds sitelinks to a campaign. To create a campaign, run AddCampaigns.java. */
public class AddSitelinks {

  private static class AddSitelinksParams extends CodeSampleParams {

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

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

  public static void main(String[] args) throws IOException {
    AddSitelinksParams params = new AddSitelinksParams();
    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");
    }

    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 AddSitelinks().runExample(googleAdsClient, params.customerId, params.campaignId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignId the campaign ID.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
    String campaignResourceName = ResourceNames.campaign(customerId, campaignId);

    List<StringValue> extensionFeedItems =
        createExtensionFeedItems(googleAdsClient, customerId, campaignResourceName);

    // Creates a CampaignExtensionSetting.
    CampaignExtensionSetting campaignExtensionSetting =
        CampaignExtensionSetting.newBuilder()
            .setCampaign(StringValue.of(campaignResourceName))
            .setExtensionType(ExtensionType.SITELINK)
            .addAllExtensionFeedItems(extensionFeedItems)
            .build();

    // Creates the operation.
    CampaignExtensionSettingOperation operation =
        CampaignExtensionSettingOperation.newBuilder().setCreate(campaignExtensionSetting).build();

    // Creates the CampaignExtensionSettingServiceClient.
    try (CampaignExtensionSettingServiceClient campaignExtensionSettingServiceClient =
        googleAdsClient.getLatestVersion().createCampaignExtensionSettingServiceClient()) {
      // Adds the CampaignExtensionSettingServiceClient.
      MutateCampaignExtensionSettingsResponse response =
          campaignExtensionSettingServiceClient.mutateCampaignExtensionSettings(
              Long.toString(customerId), ImmutableList.of(operation));
      for (MutateCampaignExtensionSettingResult result : response.getResultsList()) {
        System.out.printf(
            "Created CampaignExtensionSetting with resource name '%s'.%n",
            result.getResourceName());
      }
    }
  }

  /**
   * Creates a list of ExtensionFeedItems.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignResourceName the resource name of the campaign to target.
   */
  private static List<StringValue> createExtensionFeedItems(
      GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) {
    SitelinkFeedItem sitelinkFeedItem1 =
        createSitelinkFeedItem("Store Hours", "http://www.example.com/storehours");

    // Creates an ExtensionFeedItem from the SitelinkFeedItem.
    ExtensionFeedItem extensionFeedItem1 =
        ExtensionFeedItem.newBuilder()
            .setExtensionType(ExtensionType.SITELINK)
            .setSitelinkFeedItem(sitelinkFeedItem1)
            .setTargetedCampaign(StringValue.of(campaignResourceName))
            .build();

    List<ExtensionFeedItemOperation> operations = new ArrayList<>();
    // Creates an ExtensionFeedItemOperation and adds it to the operations List.
    operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem1).build());

    SitelinkFeedItem sitelinkFeedItem2 =
        createSitelinkFeedItem("Thanksgiving Specials", "http://www.example.com/thanksgiving");

    DateTime startTime = new DateTime(DateTime.now().getYear(), 11, 20, 0, 0, 0);
    if (startTime.isBeforeNow()) {
      // Move the startTime to next year if the current date is past November 20th.
      startTime = startTime.plusYears(1);
    }
    // Converts to a string in the required format.
    String startTimeString = startTime.toString("yyyy-MM-dd hh:mm:ss");

    // Use the same year as startTime when creating endTime.
    DateTime endTime = new DateTime(startTime.getYear(), 11, 27, 23, 59, 59);
    String endTimeString = endTime.toString("yyyy-MM-dd hh:mm:ss");

    // Targets this sitelink for United States only.
    // A list of country codes can be referenced here:
    // https://developers.google.com/adwords/api/docs/appendix/geotargeting
    String unitedStates = ResourceNames.geoTargetConstant(2840);

    ExtensionFeedItem extensionFeedItem2 =
        ExtensionFeedItem.newBuilder()
            .setExtensionType(ExtensionType.SITELINK)
            .setSitelinkFeedItem(sitelinkFeedItem2)
            .setTargetedCampaign(StringValue.of(campaignResourceName))
            .setStartDateTime(StringValue.of(startTimeString))
            .setEndDateTime(StringValue.of(endTimeString))
            .setTargetedGeoTargetConstant(StringValue.of(unitedStates))
            .build();

    operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem2).build());

    SitelinkFeedItem sitelinkFeedItem3 =
        createSitelinkFeedItem("Wifi available", "http://www.example.com/mobile/wifi");

    ExtensionFeedItem extensionFeedItem3 =
        ExtensionFeedItem.newBuilder()
            .setExtensionType(ExtensionType.SITELINK)
            .setSitelinkFeedItem(sitelinkFeedItem3)
            .setTargetedCampaign(StringValue.of(campaignResourceName))
            .setDevice(FeedItemTargetDevice.MOBILE)
            .setTargetedKeyword(
                KeywordInfo.newBuilder()
                    .setText("free wifi")
                    .setMatchType(KeywordMatchType.BROAD)
                    .build())
            .build();

    operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem3).build());

    SitelinkFeedItem sitelinkFeedItem4 =
        createSitelinkFeedItem("Happy hours", "http://www.example.com/happyhours");

    ExtensionFeedItem extensionFeedItem4 =
        ExtensionFeedItem.newBuilder()
            .setExtensionType(ExtensionType.SITELINK)
            .setSitelinkFeedItem(sitelinkFeedItem4)
            .setTargetedCampaign(StringValue.of(campaignResourceName))
            .addAdSchedules(
                createAdScheduleInfo(
                    DayOfWeek.MONDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO))
            .addAdSchedules(
                createAdScheduleInfo(
                    DayOfWeek.TUESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO))
            .addAdSchedules(
                createAdScheduleInfo(
                    DayOfWeek.WEDNESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO))
            .addAdSchedules(
                createAdScheduleInfo(
                    DayOfWeek.THURSDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO))
            .addAdSchedules(
                createAdScheduleInfo(
                    DayOfWeek.FRIDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO))
            .build();

    operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem4).build());

    // Creates the ExtensionFeedItemServiceClient.
    try (ExtensionFeedItemServiceClient extensionFeedItemServiceClient =
        googleAdsClient.getLatestVersion().createExtensionFeedItemServiceClient()) {
      // Adds the ExtensionFeedItem.
      MutateExtensionFeedItemsResponse response =
          extensionFeedItemServiceClient.mutateExtensionFeedItems(
              Long.toString(customerId), operations);
      System.out.printf("Added %d ExtensionFeedItems:%n", response.getResultsCount());
      List<StringValue> resourceNames = new ArrayList<>();
      for (MutateExtensionFeedItemResult result : response.getResultsList()) {
        System.out.printf(
            "Created ExtensionFeedItems with resource name '%s'.%n", result.getResourceName());
        resourceNames.add(StringValue.of(result.getResourceName()));
      }
      return resourceNames;
    }
  }

  /**
   * Creates a new SitelinkFeedItem with the specified attributes.
   *
   * @param sitelinkText the text of the sitelink feed item.
   * @param sitelinkUrl the URL of the sitelink feed item.
   */
  private static SitelinkFeedItem createSitelinkFeedItem(String sitelinkText, String sitelinkUrl) {
    return SitelinkFeedItem.newBuilder()
        .setLinkText(StringValue.of(sitelinkText))
        .addFinalUrls(StringValue.of(sitelinkUrl))
        .build();
  }

  /**
   * Creates a new AdScheduleInfo with the specified attributes.
   *
   * @param day day of the week of the AdScheduleInfo.
   * @param startHour the starting hour of the AdScheduleInfo.
   * @param startMinute the starting minute of the AdScheduleInfo.
   * @param endHour the ending hour of the AdScheduleInfo.
   * @param endMinute ending minute of the AdScheduleInfo.
   */
  private static AdScheduleInfo createAdScheduleInfo(
      DayOfWeek day, int startHour, MinuteOfHour startMinute, int endHour, MinuteOfHour endMinute) {
    return AdScheduleInfo.newBuilder()
        .setDayOfWeek(day)
        .setStartHour(startHour)
        .setStartMinute(startMinute)
        .setEndHour(endHour)
        .setEndMinute(endMinute)
        .build();
  }
}

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 Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V5.Common;
using Google.Ads.GoogleAds.V5.Enums;
using Google.Ads.GoogleAds.V5.Errors;
using Google.Ads.GoogleAds.V5.Resources;
using Google.Ads.GoogleAds.V5.Services;

using System;
using System.Collections.Generic;

using static Google.Ads.GoogleAds.V5.Enums.ExtensionTypeEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.FeedItemTargetDeviceEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.KeywordMatchTypeEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.MinuteOfHourEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V5
{
    /// <summary>
    /// This code example adds sitelinks to a campaign. To create a campaign, run AddCampaigns.cs.
    /// </summary>
    public class AddSitelinks : ExampleBase
    {
        /// <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)
        {
            AddSitelinks codeExample = new AddSitelinks();
            Console.WriteLine(codeExample.Description);

            // The customer ID for which the call is made.
            int customerId = int.Parse("INSERT_CUSTOMER_ID_HERE");

            // ID of the campaign to which sitelinks are added.
            long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");

            codeExample.Run(new GoogleAdsClient(), customerId, campaignId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example adds sitelinks to a campaign. To create a campaign, run " +
            "AddCampaigns.cs.";

        /// <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>
        /// <param name="campaignId">ID of the campaign to which sitelinks are added.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the CampaignExtensionSettingServiceClient.
            CampaignExtensionSettingServiceClient campaignExtensionSettingService =
                client.GetService(Services.V5.CampaignExtensionSettingService);

            string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);

            List<string> extensionFeedItems =
                CreateExtensionFeedItems(client, customerId, campaignResourceName);

            // Creates a CampaignExtensionSetting.
            CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting()
            {
                Campaign = campaignResourceName,
                ExtensionType = ExtensionType.Sitelink,
                ExtensionFeedItems = { extensionFeedItems }
            };

            // Creates the operation.
            CampaignExtensionSettingOperation operation = new CampaignExtensionSettingOperation()
            {
                Create = campaignExtensionSetting
            };

            try
            {
                MutateCampaignExtensionSettingsResponse response =
                    campaignExtensionSettingService.MutateCampaignExtensionSettings(
                        customerId.ToString(), new[] { operation });
                foreach (MutateCampaignExtensionSettingResult result in response.Results)
                {
                    Console.WriteLine($"Created CampaignExtensionSetting with resource" +
                        $" name '{result.ResourceName}'.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Creates a list of ExtensionFeedItems.
        /// </summary>
        ///<param name="client">The Google Ads API client.</param>
        ///<param name="customerId">The client customer ID.</param>
        ///<param name="campaignResourceName">The resource name of the campaign to target.</param>
        private static List<string> CreateExtensionFeedItems(GoogleAdsClient client,
            long customerId, string campaignResourceName)
        {
            // Get the ExtensionFeedItemServiceClient.
            ExtensionFeedItemServiceClient extensionFeedItemService =
                client.GetService(Services.V5.ExtensionFeedItemService);

            SitelinkFeedItem sitelinkFeedItem1 = CreateSitelinkFeedItem(
                "Store Hours", "http://www.example.com/storehours");

            // Creates an ExtensionFeedItem from the SitelinkFeedItem.
            ExtensionFeedItem extensionFeedItem1 = new ExtensionFeedItem()
            {
                ExtensionType = ExtensionType.Sitelink,
                SitelinkFeedItem = sitelinkFeedItem1,
                TargetedCampaign = campaignResourceName
            };

            List<ExtensionFeedItemOperation> operations = new List<ExtensionFeedItemOperation>();

            // Creates an ExtensionFeedItemOperation and adds it to the operations List.
            operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem1 });

            SitelinkFeedItem sitelinkFeedItem2 = CreateSitelinkFeedItem(
                "Thanksgiving Specials", "http://www.example.com/thanksgiving");

            DateTime startTime = new DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0);
            if (startTime < DateTime.Now)
            {
                // Move the startTime to next year if the current date is past November 20th.
                startTime = startTime.AddYears(1);
            }

            // Converts to a string in the required format.
            string startTimeString = startTime.ToString("yyyy-MM-dd hh:mm:ss");

            // Use the same year as startTime when creating endTime.
            DateTime endTime = new DateTime(startTime.Year, 11, 27, 23, 59, 59);

            string unitedStates = ResourceNames.GeoTargetConstant(2840);

            ExtensionFeedItem extensionFeedItem2 = new ExtensionFeedItem()
            {
                ExtensionType = ExtensionType.Sitelink,
                SitelinkFeedItem = sitelinkFeedItem2,
                TargetedCampaign = campaignResourceName,

                // StartDateTime should be formatted in "yyyy-MM-dd hh:mm:ss" format.
                StartDateTime = startTime.ToString("yyyy-MM-dd hh:mm:ss"),

                // EndDateTime should be formatted in "yyyy-MM-dd hh:mm:ss" format.
                EndDateTime = endTime.ToString("yyyy-MM-dd hh:mm:ss"),

                // Targets this sitelink for United States only.
                // A list of country codes can be referenced here:
                // https://developers.google.com/adwords/api/docs/appendix/geotargeting
                TargetedGeoTargetConstant = ResourceNames.GeoTargetConstant(2840)
            };

            operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem2 });

            SitelinkFeedItem sitelinkFeedItem3 = CreateSitelinkFeedItem(
                "Wifi available", "http://www.example.com/mobile/wifi");

            ExtensionFeedItem extensionFeedItem3 = new ExtensionFeedItem()
            {
                ExtensionType = ExtensionType.Sitelink,
                SitelinkFeedItem = sitelinkFeedItem3,
                TargetedCampaign = campaignResourceName,
                Device = FeedItemTargetDevice.Mobile,
                TargetedKeyword = new KeywordInfo()
                {
                    Text = "free wifi",
                    MatchType = KeywordMatchType.Broad
                }
            };

            operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem3 });

            SitelinkFeedItem sitelinkFeedItem4 = CreateSitelinkFeedItem(
                "Happy hours", "http://www.example.com/happyhours");

            ExtensionFeedItem extensionFeedItem4 = new ExtensionFeedItem()
            {
                ExtensionType = ExtensionType.Sitelink,
                SitelinkFeedItem = sitelinkFeedItem4,
                TargetedCampaign = campaignResourceName,
                AdSchedules = {
                    CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Monday, 18,
                        MinuteOfHour.Zero, 21, MinuteOfHour.Zero),
                    CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Tuesday, 18,
                        MinuteOfHour.Zero, 21, MinuteOfHour.Zero),
                    CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Wednesday, 18,
                        MinuteOfHour.Zero, 21, MinuteOfHour.Zero),
                    CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Thursday, 18,
                        MinuteOfHour.Zero, 21, MinuteOfHour.Zero),
                    CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Friday, 18,
                        MinuteOfHour.Zero, 21, MinuteOfHour.Zero),
                }
            };

            operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem4 });

            // Adds the ExtensionFeedItem.
            MutateExtensionFeedItemsResponse response =
                extensionFeedItemService.MutateExtensionFeedItems(customerId.ToString(),
                    operations);
            Console.WriteLine($"Added {response.Results.Count}:");

            List<string> resourceNames = new List<string>();
            foreach (MutateExtensionFeedItemResult result in response.Results)
            {
                Console.WriteLine($"Created ExtensionFeedItems with " +
                    $"resource name '{result.ResourceName}'.");
                resourceNames.Add(result.ResourceName);
            }
            return resourceNames;
        }


        /// <summary>
        /// Creates a new SitelinkFeedItem with the specified attributes.
        /// </summary>
        /// <param name="sitelinkText">The text of the sitelink feed item.</param>
        /// <param name="sitelinkUrl">The URL of the sitelink feed item.</param>
        /// <returns>The sitelink feed item.</returns>
        private static SitelinkFeedItem CreateSitelinkFeedItem(string sitelinkText,
        string sitelinkUrl)
        {
            return new SitelinkFeedItem()
            {
                LinkText = sitelinkText,
                FinalUrls = { sitelinkUrl }
            };
        }

        /// <summary>
        /// Creates a new AdScheduleInfo with the specified attributes.
        /// </summary>
        /// <param name="day">Day of the week of the AdScheduleInfo.</param>
        /// <param name="startHour">The starting hour of the AdScheduleInfo.</param>
        /// <param name="startMinute">The starting minute of the AdScheduleInfo.</param>
        /// <param name="endHour">The ending hour of the AdScheduleInfo.</param>
        /// <param name="endMinute">The ending minute of the AdScheduleInfo.</param>
        /// <returns>The ad schedule info.</returns>
        private static AdScheduleInfo CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek day,
                    int startHour, MinuteOfHour startMinute, int endHour, MinuteOfHour endMinute)
        {
            return new AdScheduleInfo()
            {
                DayOfWeek = day,
                StartHour = startHour,
                StartMinute = startMinute,
                EndHour = endHour,
                EndMinute = endMinute
            };
        }
    }
}

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\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\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\AdScheduleInfo;
use Google\Ads\GoogleAds\V5\Common\KeywordInfo;
use Google\Ads\GoogleAds\V5\Common\SitelinkFeedItem;
use Google\Ads\GoogleAds\V5\Enums\DayOfWeekEnum\DayOfWeek;
use Google\Ads\GoogleAds\V5\Enums\ExtensionTypeEnum\ExtensionType;
use Google\Ads\GoogleAds\V5\Enums\FeedItemTargetDeviceEnum\FeedItemTargetDevice;
use Google\Ads\GoogleAds\V5\Enums\KeywordMatchTypeEnum\KeywordMatchType;
use Google\Ads\GoogleAds\V5\Enums\MinuteOfHourEnum\MinuteOfHour;
use Google\Ads\GoogleAds\V5\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V5\Resources\CampaignExtensionSetting;
use Google\Ads\GoogleAds\V5\Resources\ExtensionFeedItem;
use Google\Ads\GoogleAds\V5\Services\CampaignExtensionSettingOperation;
use Google\Ads\GoogleAds\V5\Services\ExtensionFeedItemOperation;
use Google\ApiCore\ApiException;
use Google\Protobuf\StringValue;

/**
 * Adds sitelinks to a campaign. To create a campaign, run AddCampaigns.php.
 */
class AddSitelinks
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_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::CAMPAIGN_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::CAMPAIGN_ID] ?: self::CAMPAIGN_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 client customer ID
     * @param int $campaignId the campaign ID
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId
    ) {
        $campaignResourceName = ResourceNames::forCampaign($customerId, $campaignId);

        // Creates extension feed items as sitelinks.
        $extensionFeedItems =
            self::createExtensionFeedItems($googleAdsClient, $customerId, $campaignResourceName);

        // Creates a campaign extension setting using the previously created extension feed items.
        $campaignExtensionSetting = new CampaignExtensionSetting([
            'campaign' => new StringValue(['value' => $campaignResourceName]),
            'extension_type' => ExtensionType::SITELINK,
            'extension_feed_items' => $extensionFeedItems
        ]);

        // Creates the campaign extension setting operation.
        $campaignExtensionSettingOperation = new CampaignExtensionSettingOperation();
        $campaignExtensionSettingOperation->setCreate($campaignExtensionSetting);

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

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

    /**
     * Creates a list of extension feed items.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string $campaignResourceName the resource name of the campaign to target
     * @return StringValue[] the list of extension feed items' resource names
     */
    private static function createExtensionFeedItems(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $campaignResourceName
    ) {
        // Creates the first sitelink feed item.
        $sitelinkFeedItem1 =
            self::createSitelinkFeedItem('Store Hours', 'http://www.example.com/storehours');

        // Creates an extension feed item from the sitelink feed item.
        $extensionFeedItem1 = new ExtensionFeedItem([
            'extension_type' => ExtensionType::SITELINK,
            'sitelink_feed_item' => $sitelinkFeedItem1,
            'targeted_campaign' => new StringValue(['value' => $campaignResourceName])
        ]);

        // Creates the second sitelink feed item.
        $sitelinkFeedItem2 = self::createSitelinkFeedItem(
            'Thanksgiving Specials',
            'http://www.example.com/thanksgiving'
        );

        // Start date is set to November 20th. If it's already passed that date for this year,
        // use the same date for the next year instead.
        $targetYearString = date('Y');
        if (strtotime('now') > strtotime('20 November')) {
            $targetYearString = date('Y', strtotime('+1 year'));
        }
        $startTimeString = date('Y-m-d H:i:s', mktime(0, 0, 0, 11, 20, intval($targetYearString)));
        // Use the same year as start time when creating end time.
        $endTimeString = date('Y-m-d H:i:s', mktime(23, 59, 59, 11, 27, intval($targetYearString)));

        // Targets this sitelink for United States only.
        // A list of country codes can be referenced here:
        // https://developers.google.com/adwords/api/docs/appendix/geotargeting
        $unitedStates = ResourceNames::forGeoTargetConstant(2840);

        // Creates an extension feed item from the sitelink feed item.
        $extensionFeedItem2 = new ExtensionFeedItem([
            'extension_type' => ExtensionType::SITELINK,
            'sitelink_feed_item' => $sitelinkFeedItem2,
            'targeted_campaign' => new StringValue(['value' => $campaignResourceName]),
            'start_date_time' => new StringValue(['value' => $startTimeString]),
            'end_date_time' => new StringValue(['value' => $endTimeString]),
            'targeted_geo_target_constant' => new StringValue(['value' => $unitedStates])
        ]);

        // Creates the third sitelink feed item.
        $sitelinkFeedItem3 =
            self::createSitelinkFeedItem('Wifi available', 'http://www.example.com/mobile/wifi');

        // Creates an extension feed item from the sitelink feed item.
        $extensionFeedItem3 = new ExtensionFeedItem([
            'extension_type' => ExtensionType::SITELINK,
            'sitelink_feed_item' => $sitelinkFeedItem3,
            'targeted_campaign' => new StringValue(['value' => $campaignResourceName]),
            'device' => FeedItemTargetDevice::MOBILE,
            'targeted_keyword' => new KeywordInfo([
                'text' => 'free wifi',
                'match_type' => KeywordMatchType::BROAD
            ])
        ]);

        // Creates the fourth sitelink feed item.
        $sitelinkFeedItem4 =
            self::createSitelinkFeedItem('Happy hours', 'http://www.example.com/happyhours');

        // Creates an extension feed item from the sitelink feed item.
        $extensionFeedItem4 = new ExtensionFeedItem([
            'extension_type' => ExtensionType::SITELINK,
            'sitelink_feed_item' => $sitelinkFeedItem4,
            'targeted_campaign' => new StringValue(['value' => $campaignResourceName]),
            'ad_schedules' => [
                self::createAdScheduleInfo(
                    DayOfWeek::MONDAY,
                    18,
                    MinuteOfHour::ZERO,
                    21,
                    MinuteOfHour::ZERO
                ),
                self::createAdScheduleInfo(
                    DayOfWeek::TUESDAY,
                    18,
                    MinuteOfHour::ZERO,
                    21,
                    MinuteOfHour::ZERO
                ),
                self::createAdScheduleInfo(
                    DayOfWeek::WEDNESDAY,
                    18,
                    MinuteOfHour::ZERO,
                    21,
                    MinuteOfHour::ZERO
                ),
                self::createAdScheduleInfo(
                    DayOfWeek::THURSDAY,
                    18,
                    MinuteOfHour::ZERO,
                    21,
                    MinuteOfHour::ZERO
                ),
                self::createAdScheduleInfo(
                    DayOfWeek::FRIDAY,
                    18,
                    MinuteOfHour::ZERO,
                    21,
                    MinuteOfHour::ZERO
                )
            ]
        ]);

        // Issues a mutate request to add the extension feed items.
        $extensionFeedItemServiceClient = $googleAdsClient->getExtensionFeedItemServiceClient();
        $response = $extensionFeedItemServiceClient->mutateExtensionFeedItems(
            $customerId,
            [
                new ExtensionFeedItemOperation(['create' => $extensionFeedItem1]),
                new ExtensionFeedItemOperation(['create' => $extensionFeedItem2]),
                new ExtensionFeedItemOperation(['create' => $extensionFeedItem3]),
                new ExtensionFeedItemOperation(['create' => $extensionFeedItem4])
            ]
        );

        // Prints some information about the created extension feed items.
        printf(
            "Created %d extension feed items with the following resource names:%s",
            $response->getResults()->count(),
            PHP_EOL
        );
        $createdExtensionFeedItemsResourceNames = [];
        foreach ($response->getResults() as $addedExtensionFeedItem) {
            /** @var ExtensionFeedItem $addedExtensionFeedItem */
            $addedExtensionFeedItemResourceName = $addedExtensionFeedItem->getResourceName();
            print $addedExtensionFeedItemResourceName . PHP_EOL;
            $createdExtensionFeedItemsResourceNames[] = new StringValue([
                'value' => $addedExtensionFeedItemResourceName
            ]);
        }
        return $createdExtensionFeedItemsResourceNames;
    }

    /**
     * Creates a new sitelink feed item with the specified attributes.
     *
     * @param $sitelinkText string the text of the sitelink feed item
     * @param $sitelinkUrl string the URL of the sitelink feed item
     * @return SitelinkFeedItem the created sitelink feed item
     */
    private static function createSitelinkFeedItem(string $sitelinkText, string $sitelinkUrl)
    {
        return new SitelinkFeedItem([
            'link_text' => new StringValue(['value' => $sitelinkText]),
            'final_urls' => [new StringValue(['value' => $sitelinkUrl])],
        ]);
    }

    /**
     * Creates a new ad schedule info object with the specified attributes.
     *
     * @param int $day the enum value of day of the week of the ad schedule info
     * @param int $startHour the starting hour of the ad schedule info
     * @param int $startMinute the enum value of the starting minute of the ad schedule info
     * @param int $endHour the ending hour of the ad schedule info
     * @param int $endMinute the enum value of ending minute of the ad schedule info
     * @return AdScheduleInfo the created ad schedule info
     */
    private static function createAdScheduleInfo(
        int $day,
        int $startHour,
        int $startMinute,
        int $endHour,
        int $endMinute
    ) {
        return new AdScheduleInfo([
            'day_of_week' => $day,
            'start_hour' => $startHour,
            'start_minute' => $startMinute,
            'end_hour' => $endHour,
            'end_minute' => $endMinute
        ]);
    }
}

AddSitelinks::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.
"""Adds sitelinks to a campaign.

To create a campaign, run add_campaigns.py.
"""


import argparse
import datetime
import sys
from collections import namedtuple

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


_DateRange = namedtuple("_DateRange", ["start_datetime", "end_datetime"])
_date_format = "%Y-%m-%d %H:%M:%S"


def main(client, customer_id, campaign_id):
    """The main method that creates all necessary entities for the example."""
    # Create an extension setting.
    campaign_service = client.get_service("CampaignService", version="v5")
    campaign_ext_setting_service = client.get_service(
        "CampaignExtensionSettingService", version="v5"
    )

    campaign_resource_name = campaign_service.campaign_path(
        customer_id, campaign_id
    )

    feed_item_resource_names = _create_extension_feed_items(
        client, customer_id, campaign_resource_name
    )

    campaign_ext_setting_operation = client.get_type(
        "CampaignExtensionSettingOperation", version="v5"
    )
    extension_type_enum = client.get_type("ExtensionTypeEnum", version="v5")

    campaign_ext_setting = campaign_ext_setting_operation.create
    campaign_ext_setting.campaign.value = campaign_resource_name
    campaign_ext_setting.extension_type = extension_type_enum.SITELINK

    campaign_ext_setting.extension_feed_items.extend(feed_item_resource_names)

    # Add campaign extension setting with site link feed items.
    try:
        response = campaign_ext_setting_service.mutate_campaign_extension_settings(
            customer_id, [campaign_ext_setting_operation]
        )
    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("\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

    print(
        "Created CampaignExtensionSetting: "
        f'"{response.results[0].resource_name}".'
    )


def _create_extension_feed_items(client, customer_id, campaign_resource_name):
    """Helper method that creates extension feed items.

    Args:
        client: a GoogleAdsClient instance.
        customer_id: a str Google Ads customer ID, that the extension feed items
            will be created for.
        campaign_resource_name: a str resource name for the campaign that will
            be tracked by the created extension feed items.

    Returns:
        A list containing StringValue resource names for the created extension
        feed items.
    """
    extension_feed_item_service = client.get_service(
        "ExtensionFeedItemService", version="v5"
    )
    geo_target_constant_service = client.get_service(
        "GeoTargetConstantService", version="v5"
    )
    extension_type_enum = client.get_type("ExtensionTypeEnum")
    feed_item_target_device_enum = client.get_type("FeedItemTargetDeviceEnum")
    day_of_week_enum = client.get_type("DayOfWeekEnum")
    minute_of_hour_enum = client.get_type("MinuteOfHourEnum")

    extension_feed_item_operation1 = client.get_type(
        "ExtensionFeedItemOperation", version="v5"
    )
    extension_feed_item1 = extension_feed_item_operation1.create
    extension_feed_item1.extension_type = extension_type_enum.SITELINK
    extension_feed_item1.sitelink_feed_item.link_text.value = "Store Hours"
    extension_feed_item1.targeted_campaign.value = campaign_resource_name
    final_url1 = extension_feed_item1.sitelink_feed_item.final_urls.add()
    final_url1.value = "http://www.example.com/storehours"

    extension_feed_item_operation2 = client.get_type(
        "ExtensionFeedItemOperation", version="v5"
    )
    date_range = _get_thanksgiving_string_date_range()
    extension_feed_item2 = extension_feed_item_operation2.create
    extension_feed_item2.extension_type = extension_type_enum.SITELINK
    extension_feed_item2.sitelink_feed_item.link_text.value = (
        "Thanksgiving Specials"
    )
    extension_feed_item2.targeted_campaign.value = campaign_resource_name
    extension_feed_item2.start_date_time.value = date_range.start_datetime
    extension_feed_item2.end_date_time.value = date_range.end_datetime
    # Targets this sitelink for the United States only.
    # A list of country codes can be referenced here:
    # https://developers.google.com/adwords/api/docs/appendix/geotargeting
    united_states = geo_target_constant_service.geo_target_constant_path(2048)
    extension_feed_item2.targeted_geo_target_constant.value = united_states
    final_url2 = extension_feed_item2.sitelink_feed_item.final_urls.add()
    final_url2.value = "http://www.example.com/thanksgiving"

    extension_feed_item_operation3 = client.get_type(
        "ExtensionFeedItemOperation", version="v5"
    )
    extension_feed_item3 = extension_feed_item_operation3.create
    extension_feed_item3.extension_type = extension_type_enum.SITELINK
    extension_feed_item3.sitelink_feed_item.link_text.value = "Wifi available"
    extension_feed_item3.targeted_campaign.value = campaign_resource_name
    extension_feed_item3.device = feed_item_target_device_enum.MOBILE
    final_url3 = extension_feed_item3.sitelink_feed_item.final_urls.add()
    final_url3.value = "http://www.example.com/mobile/wifi"

    extension_feed_item_operation4 = client.get_type(
        "ExtensionFeedItemOperation", version="v5"
    )
    extension_feed_item4 = extension_feed_item_operation4.create
    extension_feed_item4.extension_type = extension_type_enum.SITELINK
    extension_feed_item4.sitelink_feed_item.link_text.value = "Happy hours"
    extension_feed_item4.targeted_campaign.value = campaign_resource_name
    extension_feed_item4.device = feed_item_target_device_enum.MOBILE
    final_url4 = extension_feed_item4.sitelink_feed_item.final_urls.add()
    final_url4.value = "http://www.example.com/happyhours"
    for day_of_week in [
        day_of_week_enum.MONDAY,
        day_of_week_enum.TUESDAY,
        day_of_week_enum.WEDNESDAY,
        day_of_week_enum.THURSDAY,
        day_of_week_enum.FRIDAY,
    ]:
        _populate_ad_schedule(
            extension_feed_item4.ad_schedules.add(),
            day_of_week,
            18,
            minute_of_hour_enum.ZERO,
            21,
            minute_of_hour_enum.ZERO,
        )

    # Add extension feed items
    try:
        feed_response = extension_feed_item_service.mutate_extension_feed_items(
            customer_id,
            [
                extension_feed_item_operation1,
                extension_feed_item_operation2,
                extension_feed_item_operation3,
                extension_feed_item_operation4,
            ],
        )
    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)

    print("Created ExtensionFeedItems:")
    for feed_item in feed_response.results:
        print(f"\tResource name: {feed_item.resource_name}")

    resource_names = [result.resource_name for result in feed_response.results]

    return [
        _to_string_value(client, resource_name)
        for resource_name in resource_names
    ]


def _to_string_value(client, s):
    """Helper method that converts a given str to a StringValue instance."""
    str_val = client.get_type("StringValue")
    str_val.value = s
    return str_val


def _get_thanksgiving_string_date_range():
    """Retrieves a _DateRange with formatted datetime start/end strings."""
    now = datetime.datetime.now()
    start_dt = datetime.datetime(now.year, 11, 20, 0, 0, 0)

    if start_dt < now:
        # Move start_dt to next year if the current date is past November 20th.
        start_dt.year += 1

    end_dt = datetime.datetime(start_dt.year, 11, 27, 23, 59, 59)

    return _DateRange(
        start_dt.strftime(_date_format), end_dt.strftime(_date_format)
    )


def _populate_ad_schedule(
    ad_schedule, day_of_week, start_hour, start_minute, end_hour, end_minute
):
    """Helper method to populate a given AdScheduleInfo instance."""
    ad_schedule.day_of_week = day_of_week
    ad_schedule.start_hour = start_hour
    ad_schedule.start_minute = start_minute
    ad_schedule.end_hour = end_hour
    ad_schedule.end_minute = end_minute


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="Adds sitelinks to the specified campaign."
    )
    # 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 sitelinks will be added to.",
    )
    args = parser.parse_args()

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

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 adds sitelinks to a campaign. To create a campaign, run add_campaigns.pl.

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::CampaignExtensionSetting;
use Google::Ads::GoogleAds::V5::Resources::ExtensionFeedItem;
use Google::Ads::GoogleAds::V5::Common::KeywordInfo;
use Google::Ads::GoogleAds::V5::Common::SitelinkFeedItem;
use Google::Ads::GoogleAds::V5::Common::AdScheduleInfo;
use Google::Ads::GoogleAds::V5::Enums::ExtensionTypeEnum qw(SITELINK);
use Google::Ads::GoogleAds::V5::Enums::FeedItemTargetDeviceEnum qw(MOBILE);
use Google::Ads::GoogleAds::V5::Enums::KeywordMatchTypeEnum qw(BROAD);
use Google::Ads::GoogleAds::V5::Enums::DayOfWeekEnum
  qw(MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY);
use Google::Ads::GoogleAds::V5::Enums::MinuteOfHourEnum qw(ZERO);
use
  Google::Ads::GoogleAds::V5::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation;
use
  Google::Ads::GoogleAds::V5::Services::ExtensionFeedItemService::ExtensionFeedItemOperation;
use Google::Ads::GoogleAds::V5::Utils::ResourceNames;

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

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

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

  my $campaign_resource_name =
    Google::Ads::GoogleAds::V5::Utils::ResourceNames::campaign($customer_id,
    $campaign_id);

  # Create extension feed items as sitelinks.
  my $extension_feed_items =
    create_extension_feed_items($api_client, $customer_id,
    $campaign_resource_name);

  # Create a campaign extension setting.
  my $campaign_extension_setting =
    Google::Ads::GoogleAds::V5::Resources::CampaignExtensionSetting->new({
      campaign           => $campaign_resource_name,
      extensionType      => SITELINK,
      extensionFeedItems => $extension_feed_items
    });

  # Create a campaign extension setting operation.
  my $campaign_extension_setting_operation =
    Google::Ads::GoogleAds::V5::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation
    ->new({
      create => $campaign_extension_setting
    });

  # Add the campaign extension setting.
  my $campaign_extension_setting_response =
    $api_client->CampaignExtensionSettingService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_extension_setting_operation]});

  printf "Created campaign extension setting with resource name '%s'.\n",
    $campaign_extension_setting_response->{results}[0]{resourceName};

  return 1;
}

# Creates a list of extension feed items.
sub create_extension_feed_items {
  my ($api_client, $customer_id, $campaign_resource_name) = @_;

  my $operations = [];

  my $sitelink_feed_item_1 = create_sitelink_feed_item("Store Hours",
    "http://www.example.com/storehours");

  # Create an extension feed item from the sitelink feed item.
  my $extension_feed_item_1 =
    Google::Ads::GoogleAds::V5::Resources::ExtensionFeedItem->new({
      extensionType    => SITELINK,
      sitelinkFeedItem => $sitelink_feed_item_1,
      targetedCampaign => $campaign_resource_name
    });

  # Create an extension feed item operation and add it to the operations list.
  push @$operations,
    Google::Ads::GoogleAds::V5::Services::ExtensionFeedItemService::ExtensionFeedItemOperation
    ->new({
      create => $extension_feed_item_1
    });

  my $sitelink_feed_item_2 = create_sitelink_feed_item("Thanksgiving Specials",
    "http://www.example.com/thanksgiving");

  # Set the start_time and end_time to show the Thanksgiving specials link only
  # from 20 - 27 Nov.
  my ($sec, $min, $hour, $mday, $mon, $year) = localtime(time);
  my $start_time = mktime(0, 0, 0, 20, 10, $year);
  if ($start_time < time) {
    # Move the start_time to next year if the current date is past November 20th.
    $year += 1;
    $start_time = mktime(0, 0, 0, 20, 10, $year);
  }
  # Convert to a string in the required format.
  my $start_time_string = strftime("%Y-%m-%d %H:%M:%S", localtime($start_time));

  # Use the same year as start_time when creating end_time.
  my $end_time        = mktime(59, 59, 23, 27, 10, $year);
  my $end_time_string = strftime("%Y-%m-%d %H:%M:%S", localtime($end_time));

  # Target this sitelink for United States only.
  # A list of country codes can be referenced here:
  # https://developers.google.com/adwords/api/docs/appendix/geotargeting
  my $united_states =
    Google::Ads::GoogleAds::V5::Utils::ResourceNames::geo_target_constant(2840);

  my $extension_feed_item_2 =
    Google::Ads::GoogleAds::V5::Resources::ExtensionFeedItem->new({
      extensionType             => SITELINK,
      sitelinkFeedItem          => $sitelink_feed_item_2,
      targetedCampaign          => $campaign_resource_name,
      startDateTime             => $start_time_string,
      endDateTime               => $end_time_string,
      targetedGeoTargetConstant => $united_states
    });

  push @$operations,
    Google::Ads::GoogleAds::V5::Services::ExtensionFeedItemService::ExtensionFeedItemOperation
    ->new({
      create => $extension_feed_item_2
    });

  my $sitelink_feed_item_3 = create_sitelink_feed_item("Wifi available",
    "http://www.example.com/mobile/wifi");

  # Set the targeted device to show the wifi details primarily for high end
  # mobile users.
  # Target this sitelink for the keyword "free wifi".
  my $extension_feed_item_3 =
    Google::Ads::GoogleAds::V5::Resources::ExtensionFeedItem->new({
      extensionType    => SITELINK,
      sitelinkFeedItem => $sitelink_feed_item_3,
      targetedCampaign => $campaign_resource_name,
      device           => MOBILE,
      targetedKeyword  => Google::Ads::GoogleAds::V5::Common::KeywordInfo->new({
          text      => "free wifi",
          matchType => BROAD
        })});

  push @$operations,
    Google::Ads::GoogleAds::V5::Services::ExtensionFeedItemService::ExtensionFeedItemOperation
    ->new({
      create => $extension_feed_item_3
    });

  my $sitelink_feed_item_4 = create_sitelink_feed_item("Happy hours",
    "http://www.example.com/happyhours");

  # Set the feed item schedules to show the happy hours link only during Mon - Fri
  # 6PM to 9PM.
  my $extension_feed_item_4 =
    Google::Ads::GoogleAds::V5::Resources::ExtensionFeedItem->new({
      extensionType    => SITELINK,
      sitelinkFeedItem => $sitelink_feed_item_4,
      targetedCampaign => $campaign_resource_name,
      adSchedules      => [
        create_ad_schedule_info(MONDAY,    18, ZERO, 21, ZERO),
        create_ad_schedule_info(TUESDAY,   18, ZERO, 21, ZERO),
        create_ad_schedule_info(WEDNESDAY, 18, ZERO, 21, ZERO),
        create_ad_schedule_info(THURSDAY,  18, ZERO, 21, ZERO),
        create_ad_schedule_info(FRIDAY,    18, ZERO, 21, ZERO)]});

  push @$operations,
    Google::Ads::GoogleAds::V5::Services::ExtensionFeedItemService::ExtensionFeedItemOperation
    ->new({
      create => $extension_feed_item_4
    });

  # Add the extension feed item.
  my $extension_feed_item_response =
    $api_client->ExtensionFeedItemService()->mutate({
      customerId => $customer_id,
      operations => $operations
    });

  my $extension_feed_item_results = $extension_feed_item_response->{results};
  printf "Added %d extension feed items:\n",
    scalar @$extension_feed_item_results;

  my $resource_names = [];
  foreach my $extension_feed_item_result (@$extension_feed_item_results) {
    printf "\tCreated extension feed item with resource name '%s'.\n",
      $extension_feed_item_result->{resourceName};
    push @$resource_names, $extension_feed_item_result->{resourceName};
  }

  return $resource_names;
}

# Creates a new sitelink feed item with the specified attributes.
sub create_sitelink_feed_item {
  my ($sitelink_text, $sitelink_url) = @_;

  return Google::Ads::GoogleAds::V5::Common::SitelinkFeedItem->new({
    linkText  => $sitelink_text,
    finalUrls => $sitelink_url
  });
}

# Creates a new ad schedule info with the specified attributes.
sub create_ad_schedule_info {
  my ($day, $start_hour, $start_minute, $end_hour, $end_minute) = @_;

  return Google::Ads::GoogleAds::V5::Common::AdScheduleInfo->new({
    dayOfWeek   => $day,
    startHour   => $start_hour,
    startMinute => $start_minute,
    endHour     => $end_hour,
    endMinute   => $end_minute
  });
}

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

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

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

=pod

=head1 NAME

add_sitelinks

=head1 DESCRIPTION

This example adds sitelinks to a campaign. To create a campaign, run add_campaigns.pl.

=head1 SYNOPSIS

add_sitelinks.pl [options]

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

=cut