Exemplo n.º 1
0
def main(client, customer_id, feed_id, feed_item_id, feed_item_set_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        feed_id: the ID of the feed associated with the specified feed item set.
        feed_item_id: the ID of the specified feed item.
        feed_item_set_id: the ID of the feed item set to link to the feed item.
    """
    feed_item_set_link_service = client.get_service("FeedItemSetLinkService",
                                                    version="v6")
    feed_item_set_link_operation = client.get_type("FeedItemSetLinkOperation",
                                                   version="v6")

    # Construct an operation that will link the feed item to the feed item set.
    feed_item_set_link = feed_item_set_link_operation.create

    # Construct a resource name for a feed item, which is in the format:
    # customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}
    feed_item_set_link.feed_item = client.get_service(
        "FeedItemService", version="v6").feed_item_path(
            customer_id,
            ResourceName.format_composite(feed_id, feed_item_id),
        )
    # Construct a resource name for a feed item set, which is in the
    # format: customers/{customer_id}/feedItemSets/{feed_id}~{feed_item_set_id}
    feed_item_set_link.feed_item_set = client.get_service(
        "FeedItemSetService", version="v6").feed_item_set_path(
            customer_id,
            ResourceName.format_composite(feed_id, feed_item_set_id),
        )

    # Issue a mutate request to add the feed item set link on the server.
    try:
        response = feed_item_set_link_service.mutate_feed_item_set_links(
            customer_id, [feed_item_set_link_operation])
        print("Created a feed item set link with resource name: "
              f"'{response.results[0].resource_name}'")
    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)
Exemplo n.º 2
0
def main(client, customer_id, ad_group_id, criterion_id):
    agc_service = client.get_service('AdGroupCriterionService', version='v2')

    ad_group_criterion_operation = client.get_type('AdGroupCriterionOperation',
                                                   version='v2')

    ad_group_criterion = ad_group_criterion_operation.update
    ad_group_criterion.resource_name = agc_service.ad_group_criteria_path(
        customer_id, ResourceName.format_composite(ad_group_id, criterion_id))
    ad_group_criterion.status = (client.get_type('AdGroupCriterionStatusEnum',
                                                 version='v2').ENABLED)
    final_url = ad_group_criterion.final_urls.add()
    final_url.value = 'https://www.example.com'
    fm = protobuf_helpers.field_mask(None, ad_group_criterion)
    ad_group_criterion_operation.update_mask.CopyFrom(fm)

    try:
        agc_response = agc_service.mutate_ad_group_criteria(
            customer_id, [ad_group_criterion_operation])
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    print('Updated keyword %s.' % agc_response.results[0].resource_name)
Exemplo n.º 3
0
def main(client, customer_id, ad_group_id, ad_id):
    ad_group_ad_service = client.get_service("AdGroupAdService", version="v6")

    ad_group_ad_operation = client.get_type("AdGroupAdOperation", version="v6")

    ad_group_ad = ad_group_ad_operation.update
    ad_group_ad.resource_name = ad_group_ad_service.ad_group_ad_path(
        customer_id, ResourceName.format_composite(ad_group_id, ad_id)
    )
    ad_group_ad.status = client.get_type(
        "AdGroupStatusEnum", version="v6"
    ).PAUSED
    fm = protobuf_helpers.field_mask(None, ad_group_ad)
    ad_group_ad_operation.update_mask.CopyFrom(fm)

    try:
        ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
            customer_id, [ad_group_ad_operation]
        )
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print(
            'Request with ID "%s" failed with status "%s" and includes the '
            "following errors:" % (ex.request_id, ex.error.code().name)
        )
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print("\t\tOn field: %s" % field_path_element.field_name)
        sys.exit(1)

    print(
        "Paused ad group ad %s." % ad_group_ad_response.results[0].resource_name
    )
def _get_feed_item(client, customer_id, feed_id, feed_item_id):
    """Retrieves a feed item and its attribute values given a resource name.

    Args:
        client: The Google Ads API client.
        customer_id: The client customer ID.
        feed_id: The feed ID that contains the target feed item.
        feed_item_id: The feed item ID that will be updated.
    Returns:
        A FeedItem with the given resource name.
    """
    # Get the GoogleAdsService client.
    google_ads_service = client.get_service("GoogleAdsService", version="v6")

    # Construct the resource name for the feed item.
    feed_item_resource_name = client.get_service(
        "FeedItemService", version="v6").feed_item_path(
            customer_id,
            ResourceName.format_composite(feed_id, feed_item_id),
        )

    # Construct the query.
    query = f"""
        SELECT feed_item.attribute_values
        FROM feed_item
        WHERE feed_item.resource_name = '{feed_item_resource_name}'"""

    # Issue the search request and return the first result, since the query will
    # match only a single feed item.
    return next(iter(google_ads_service.search(customer_id,
                                               query=query))).feed_item
Exemplo n.º 5
0
def main(client, customer_id, ad_group_id, criterion_id):
    agc_service = client.get_service("AdGroupCriterionService", version="v5")
    agc_operation = client.get_type("AdGroupCriterionOperation", version="v5")

    resource_name = agc_service.ad_group_criteria_path(
        customer_id, ResourceName.format_composite(ad_group_id, criterion_id)
    )
    agc_operation.remove = resource_name

    try:
        agc_response = agc_service.mutate_ad_group_criteria(
            customer_id, [agc_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(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

    print(f"Removed keyword {agc_response.results[0].resource_name}.")
def _create_sitelink_campaign_extension_setting_mutate_operation(
        client, customer_id, campaign_id):
    """Creates a MutateOperation for the sitelink campaign extension setting
    that will be removed.

    Args:
        client: an initialized GoogleAdsClient instance
        customer_id: the client customer ID.
        campaign_id: the campaign ID.

    Returns:
        The created MutateOperation for the sitelink campaign extension
            setting.
    """
    extension_type_enum = client.get_type("ExtensionTypeEnum", version="v6")
    composite_id = ResourceName.format_composite(
        campaign_id,
        extension_type_enum.ExtensionType.Name(
            extension_type_enum.ExtensionType.SITELINK),
    )
    # Construct the campaign extension setting resource name, in format:
    # customers/{customer_id}/campaignExtensionSettings/{campaign_id}~{extension_type}
    resource_name = client.get_service(
        "CampaignExtensionSettingService",
        version="v6").campaign_extension_setting_path(customer_id,
                                                      composite_id)

    # Create a MutateOperation for the campaign extension setting.
    mutate_operation = client.get_type("MutateOperation", version="v6")
    mutate_operation.campaign_extension_setting_operation.remove = resource_name
    return mutate_operation
def _create_listing_group_subdivision(
    client,
    customer_id,
    ad_group_id,
    parent_ad_group_criterion_resource_name=None,
    listing_dimension_info=None,
):
    """Creates a new criterion containing a subdivision listing group node.

    If the parent ad group criterion resource name or listing dimension info are
    not specified, this method creates a root node.

    Args:
        client: An initialized Google Ads client.
        customer_id: The Google Ads customer ID.
        ad_group_id: The ad group ID to which the node will be added.
        parent_ad_group_criterion_resource_name: The string resource name of the
            parent node to which this listing will be attached.
        listing_dimension_info: A ListingDimensionInfo object containing details
            for this listing.

    Returns:
        An AdGroupCriterionOperation containing a populated ad group criterion.
    """
    # Create an ad group criterion operation and populate the criterion.
    operation = client.get_type("AdGroupCriterionOperation", version="v6")
    ad_group_criterion = operation.create
    # The resource name the criterion will be created with. This will define
    # the ID for the ad group criterion.
    ad_group_criterion.resource_name = client.get_service(
        "AdGroupCriterionService", version="v6"
    ).ad_group_criteria_path(
        customer_id, ResourceName.format_composite(ad_group_id, next_id())
    )
    ad_group_criterion.status = client.get_type(
        "AdGroupCriterionStatusEnum", version="v6"
    ).ENABLED

    listing_group_info = ad_group_criterion.listing_group
    # Set the type as a SUBDIVISION, which will allow the node to be the
    # parent of another sub-tree.
    listing_group_info.type = client.get_type(
        "ListingGroupTypeEnum", version="v6"
    ).SUBDIVISION
    # If parent_ad_group_criterion_resource_name and listing_dimension_info
    # are not null, create a non-root division by setting its parent and case
    # value.
    if parent_ad_group_criterion_resource_name and listing_dimension_info:
        # Set the ad group criterion resource name for the parent listing group.
        # This can include a temporary ID if the parent criterion is not yet
        # created.
        listing_group_info.parent_ad_group_criterion = (
            parent_ad_group_criterion_resource_name
        )

        # Case values contain the listing dimension used for the node.
        listing_group_info.case_value.CopyFrom(listing_dimension_info)

    return operation
def main(client, customer_id, feed_id, feed_item_set_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        feed_id: the ID for a Feed belonging to the given customer.
        feed_item_set_id: the ID for a FeedItemSet belonging to the given
            customer.
    """
    ga_service = client.get_service("GoogleAdsService", version="v6")
    feed_item_set_service = client.get_service("FeedItemSetService",
                                               version="v6")

    feed_item_set_path = feed_item_set_service.feed_item_set_path(
        customer_id,
        ResourceName.format_composite(feed_id, feed_item_set_id),
    )
    query = f"""
        SELECT
          feed_item_set_link.feed_item
        FROM feed_item_set_link
        WHERE feed_item_set_link.feed_item_set = '{feed_item_set_path}'"""

    # Issues a search request using streaming.
    response = ga_service.search_stream(customer_id, query=query)

    print("The feed items with the following resource names are linked with "
          f"the feed item set with ID {feed_item_set_id}:")
    try:
        for batch in response:
            for row in batch.results:
                print(f"'{row.feed_item_set_link.feed_item}'")
    except GoogleAdsException as ex:
        print(f'Request with ID "{ex.request_id}" failed with status '
              f'"{ex.error.code().name}" and includes the following errors:')
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)
def main(client, customer_id, feed_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.
        feed_id: the ID for a Feed belonging to the given customer.
        feed_item_ids: a list of FeedItem IDs belonging to the given Feed.
    """
    feed_item_service = client.get_service("FeedItemService", version="v6")

    operations = []
    for feed_item_id in feed_item_ids:
        # Constructs an operation that will remove the feed item based on the
        # resource name.
        feed_item_operation = client.get_type("FeedItemOperation", version="v6")
        # Constructs a resource name for a feed_item, which is in the
        # format: customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}
        feed_item_operation.remove = feed_item_service.feed_item_path(
            customer_id, ResourceName.format_composite(feed_id, feed_item_id),
        )
        operations.append(feed_item_operation)

    try:
        response = feed_item_service.mutate_feed_items(customer_id, operations)

        for feed_item in response.results:
            print(
                "Removed feed item with resource name: "
                f"'{feed_item.resource_name}'"
            )
    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)
Exemplo n.º 10
0
def main(client, customer_id, ad_group_id, criterion_id):
    """Demonstrates how to set ad parameters on an ad group criterion.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: A client customer ID str.
        ad_group_id: An ad group ID str.
        criterion_id: A criterion ID str.
    """
    ad_group_criterion_service = client.get_service('AdGroupCriterionService',
                                                    version='v2')
    # Gets the resource name of the ad group criterion to be used.
    resource_name = ad_group_criterion_service.ad_group_criteria_path(
        customer_id, ResourceName.format_composite(ad_group_id, criterion_id))

    operations = []
    operations.append(create_ad_parameter(client, resource_name, 1, '100'))
    operations.append(create_ad_parameter(client, resource_name, 2, '$40'))

    ad_parameter_service = client.get_service('AdParameterService',
                                              version='v2')

    # Add the ad parameter.
    try:
        response = ad_parameter_service.mutate_ad_parameters(
            customer_id, operations)
    except GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)
    else:
        print('Set {} ad parameters:'.format(len(response.results)))

        for result in response.results:
            print('Set ad parameter with resource_name: {}'.format(
                result.resource_name))
Exemplo n.º 11
0
def main(client, customer_id, ad_group_id, criteria_id):
    agc_service = client.get_service('AdGroupCriterionService', version='v1')
    agc_operation = client.get_type('AdGroupCriterionOperation', version='v1')

    resource_name = agc_service.ad_group_criteria_path(
        customer_id, ResourceName.format_composite(ad_group_id, criteria_id))
    agc_operation.remove = resource_name

    try:
        agc_response = agc_service.mutate_ad_group_criteria(
            customer_id, [agc_operation])
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    print('Removed keyword %s.' % agc_response.results[0].resource_name)
def main(
    client,
    customer_id,
    feed_id,
    feed_item_id,
    flight_placeholder_field_name,
    attribute_value,
):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance
        customer_id: a client customer ID
        feed_id: the ID of feed containing the feed item to be updated
        feed_item_id: The ID of the feed item to be updated
        flight_placeholder_field_name: the flight placeholder field name for
            the attribute to be updated
        attribute_value: the new value to set the feed attribute to
    """
    try:
        feed_service = client.get_service("FeedService", version="v6")
        # Gets a map of the placeholder values to feed attributes.
        placeholders_to_feed_attribute_map = _flight_placeholder_fields_map(
            client, customer_id, feed_service.feed_path(customer_id, feed_id))
        # Gets the ID of the feed attribute for the placeholder field. This is
        # needed to specify which feed item attribute value will be updated in
        # the given feed item.
        flight_placeholder_field_enum = client.get_type(
            "FlightPlaceholderFieldEnum", version="v6")
        flight_placeholder_enum_value = getattr(flight_placeholder_field_enum,
                                                flight_placeholder_field_name)
        attribute_id = placeholders_to_feed_attribute_map[
            flight_placeholder_enum_value].id

        # Creates the updated feed item attribute value.
        updated_feed_item_attribute_value = client.get_type(
            "FeedItemAttributeValue", version="v6")
        updated_feed_item_attribute_value.feed_attribute_id = attribute_id
        updated_feed_item_attribute_value.string_value = attribute_value

        # Retrieves the feed item and its associated attributes based on the
        # resource name.
        feed_item_service = client.get_service("FeedItemService", version="v6")
        feed_item = _get_feed_item(
            client,
            customer_id,
            feed_item_service.feed_item_path(
                customer_id,
                ResourceName.format_composite(feed_id, feed_item_id),
            ),
        )

        # Gets the index of the attribute value that will be updated in the
        # feed item.
        attribute_index = _get_attribute_index(
            updated_feed_item_attribute_value, feed_item)
        # Any feed item attribute values that are not included in the updated
        # feed item will be removed from the feed item, which is why you must
        # create the feed item from the existing feed item and its attribute
        # values. Then, update only the attribute that you want.
        feed_item_operation = client.get_type("FeedItemOperation",
                                              version="v6")
        updated_feed_item = feed_item_operation.update
        updated_feed_item.CopyFrom(feed_item)
        updated_feed_item.attribute_values[attribute_index].CopyFrom(
            updated_feed_item_attribute_value)

        # Create a field mask using the old feed_item and the updated_feed_item.
        field_mask = protobuf_helpers.field_mask(feed_item, updated_feed_item)
        feed_item_operation.update_mask.CopyFrom(field_mask)

        response = feed_item_service.mutate_feed_items(customer_id,
                                                       [feed_item_operation])
        print("Feed item with resource name: "
              f"'{response.results[0].resource_name}' was updated.")
    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)
Exemplo n.º 13
0
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", version="v6"
    )
    campaign_extension_setting_operation = client.get_type(
        "CampaignExtensionSettingOperation", version="v6"
    )
    extension_feed_item_service = client.get_service(
        "ExtensionFeedItemService", version="v6"
    )

    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.get_type("ExtensionTypeEnum", version="v6")
    composite_id = ResourceName.format_composite(
        campaign_id,
        extension_type_enum.ExtensionType.Name(
            extension_type_enum.ExtensionType.SITELINK
        ),
    )
    resource_name = campaign_extension_setting_service.campaign_extension_setting_path(
        customer_id, composite_id
    )
    campaign_extension_setting.resource_name = resource_name

    # Produce a field mask enumerating the changed fields
    fm = protobuf_helpers.field_mask(None, campaign_extension_setting)
    campaign_extension_setting_operation.update_mask.CopyFrom(fm)

    # Update the campaign extension settings
    try:
        response = campaign_extension_setting_service.mutate_campaign_extension_settings(
            customer_id, [campaign_extension_setting_operation]
        )
        print(
            "Updated campaign extension setting with resource name: "
            f'"{response.results[0].resource_name}".'
        )
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)
def main(client, customer_id, base_campaign_id, draft_id):
    # Create the campaign experiment.
    campaign_experiment = client.get_type('CampaignExperiment', version='v4')
    campaign_draft_service = client.get_service('CampaignDraftService',
                                                version='v4')
    campaign_draft_resource_name = campaign_draft_service.campaign_draft_path(
        customer_id, ResourceName.format_composite(base_campaign_id, draft_id))

    campaign_experiment.campaign_draft.value = campaign_draft_resource_name
    campaign_experiment.name.value = f'Campaign Experiment #{uuid.uuid4()}'
    campaign_experiment.traffic_split_percent.value = 50
    campaign_experiment.traffic_split_type = client.get_type(
        'CampaignExperimentTrafficSplitTypeEnum', version='v4').RANDOM_QUERY

    try:
        campaign_experiment_service = client.get_service(
            'CampaignExperimentService', version='v4')

        # A Long Running Operation (LRO) is returned from this
        # asynchronous request by the API.
        campaign_experiment_lro = (
            campaign_experiment_service.create_campaign_experiment(
                customer_id, campaign_experiment))
    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('Asynchronous request to create campaign experiment with '
          'resource name '
          f'"{campaign_experiment_lro.metadata.campaign_experiment}" started.')
    print('Waiting until operation completes.')

    # Poll until the operation completes.
    campaign_experiment_lro.result()

    # Retrieve the campaign experiment that has been created.
    ga_service = client.get_service('GoogleAdsService', version='v4')
    query = ('SELECT campaign_experiment.experiment_campaign '
             'FROM campaign_experiment '
             'WHERE campaign_experiment.resource_name = '
             f'"{campaign_experiment_lro.metadata.campaign_experiment}"')

    results = ga_service.search(customer_id, query=query, page_size=1)

    try:
        for row in results:
            print('Experiment campaign '
                  f'"{row.campaign_experiment.experiment_campaign.value}" '
                  'creation completed.')
    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)
Exemplo n.º 15
0
 def test_format_composite(self):
     composite = ResourceName.format_composite('test', 'test')
     self.assertEqual(composite, 'test~test')