def main(client, customer_id, ad_group_id):
    ad_group_service = client.get_service("AdGroupService", version="v6")
    ad_group_criterion_service = client.get_service("AdGroupCriterionService",
                                                    version="v6")

    ad_group_resource_name = ad_group_service.ad_group_path(
        customer_id, ad_group_id)
    # Create a positive ad group criterion for the gender MALE.
    gender_ad_group_criterion_operation = client.get_type(
        "AdGroupCriterionOperation", version="v6")
    gender_ad_group_criterion = gender_ad_group_criterion_operation.create
    gender_ad_group_criterion.ad_group = ad_group_resource_name
    gender_ad_group_criterion.gender.type = client.get_type(
        "GenderTypeEnum").MALE

    # Create a negative ad group criterion for age range of 18 to 24.
    age_range_ad_group_criterion_operation = client.get_type(
        "AdGroupCriterionOperation", version="v6")
    age_range_ad_group_criterion = age_range_ad_group_criterion_operation.create
    age_range_ad_group_criterion.ad_group = ad_group_resource_name
    age_range_ad_group_criterion.negative = True
    age_range_ad_group_criterion.age_range.type = client.get_type(
        "AgeRangeTypeEnum").AGE_RANGE_18_24

    # Add two ad group criteria
    try:
        ad_group_criterion_response = ad_group_criterion_service.mutate_ad_group_criteria(
            customer_id,
            [
                gender_ad_group_criterion_operation,
                age_range_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)

    for result in ad_group_criterion_response.results:
        print("Created keyword {}.".format(result.resource_name))
def main(client, customer_id):
    ads_service = client.get_service('GoogleAdsService', version='v1')
    query = ('SELECT change_status.resource_name, '
             'change_status.last_change_date_time, '
             'change_status.resource_type, '
             'change_status.campaign, '
             'change_status.ad_group, '
             'change_status.resource_status, '
             'change_status.ad_group_ad, '
             'change_status.ad_group_criterion, '
             'change_status.campaign_criterion '
             'FROM change_status '
             'WHERE change_status.last_change_date_time DURING LAST_7_DAYS '
             'ORDER BY change_status.last_change_date_time')

    response = ads_service.search(customer_id,
                                  query=query,
                                  page_size=ADS_PAGE_SIZE)

    resource_type_enum = (client.get_type(
        'ChangeStatusResourceTypeEnum', version='v1').ChangeStatusResourceType)
    change_status_operation_enum = (client.get_type(
        'ChangeStatusOperationEnum', version='v1').ChangeStatusOperation)

    try:
        for row in response:
            resource_type = (resource_type_enum.Name(
                row.change_status.resource_type))
            resource_status = (change_status_operation_enum.Name(
                row.change_status.resource_status))
            print('On "%s", change status "%s" shows a resource type of "%s" '
                  'with resource name "%s" was "%s".' %
                  (row.change_status.last_change_date_time.value,
                   row.change_status.resource_name, resource_type,
                   resource_name_for_resource_type(resource_type,
                                                   row), resource_status))
    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)
def main(client, customer_id, ad_group_id, keyword):
    ad_group_service = client.get_service('AdGroupService', version='v3')
    ad_group_criterion_service = client.get_service('AdGroupCriterionService',
                                                    version='v3')

    # Create keyword.
    ad_group_criterion_operation = client.get_type('AdGroupCriterionOperation',
                                                   version='v3')
    ad_group_criterion = ad_group_criterion_operation.create
    ad_group_criterion.ad_group.value = ad_group_service.ad_group_path(
        customer_id, ad_group_id)
    ad_group_criterion.status = client.get_type(
        'AdGroupCriterionStatusEnum').ENABLED
    ad_group_criterion.keyword.text.value = keyword
    ad_group_criterion.keyword.match_type = client.get_type(
        'KeywordMatchTypeEnum').EXACT

    # Optional field
    # All fields can be referenced from the protos directly.
    # The protos are located in subdirectories under
    # google/ads/googleads/v0/proto.
    # ad_group_criterion.negative.value = True

    # Optional repeated field
    # final_url = ad_group_criterion.final_urls.add()
    # final_url.value = 'https://www.example.com'

    # Add keyword
    try:
        ad_group_criterion_response = (
            ad_group_criterion_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('Created keyword %s.' %
          ad_group_criterion_response.results[0].resource_name)
def _create_responsive_display_ad(client, customer_id, ad_group_resource_name,
                                  marketing_image_asset_resource_name,
                                  square_marketing_image_asset_resource_name):
    ad_group_ad_operation = client.get_type('AdGroupAdOperation', version='v2')
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group.value = ad_group_resource_name
    ad_group_ad.status = client.get_type('AdGroupAdStatusEnum',
                                         version='v2').PAUSED
    ad = ad_group_ad.ad
    final_url = ad.final_urls.add()
    final_url.value = 'https://www.example.com'
    responsive_display_ad = ad.responsive_display_ad
    headline = responsive_display_ad.headlines.add()
    headline.text.value = 'Travel'
    responsive_display_ad.long_headline.text.value = 'Travel the World'
    description = responsive_display_ad.descriptions.add()
    description.text.value = 'Take to the air!'
    responsive_display_ad.business_name.value = 'Google'
    marketing_image = responsive_display_ad.marketing_images.add()
    marketing_image.asset.value = marketing_image_asset_resource_name
    square_marketing_image = responsive_display_ad.square_marketing_images.add(
    )
    square_marketing_image.asset.value = (
        square_marketing_image_asset_resource_name)
    responsive_display_ad.call_to_action_text.value = 'Shop Now'
    responsive_display_ad.price_prefix.value = 'as low as'
    responsive_display_ad.promo_text.value = 'Free shipping!'

    ad_group_ad_service = client.get_service('AdGroupAdService', version='v2')

    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(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)

    return ad_group_ad_response.results[0].resource_name
def main(client, customer_id, ad_group_id, number_of_ads):
    ad_group_ad_service = client.get_service('AdGroupAdService', version='v2')
    ad_group_service = client.get_service('AdGroupService', version='v2')

    ad_group_ad_operations = []

    for i in range(number_of_ads):

        # Create ad group ad.
        ad_group_ad_operation = client.get_type('AdGroupAdOperation', version='v2')
        ad_group_ad = ad_group_ad_operation.create
        ad_group_ad.ad_group.value = ad_group_service.ad_group_path(
            customer_id, ad_group_id)
        ad_group_ad.status = client.get_type('AdGroupAdStatusEnum',
                                             version='v2').PAUSED

        # Set expanded text ad info
        final_url = ad_group_ad.ad.final_urls.add()
        final_url.value = 'http://www.example.com'
        ad_group_ad.ad.expanded_text_ad.description.value = 'Buy your tickets now!'
        ad_group_ad.ad.expanded_text_ad.headline_part1.value = (
            'Cruise {} to Mars {}'.format(i, str(uuid.uuid4())[:8]))
        ad_group_ad.ad.expanded_text_ad.headline_part2.value = (
            'Best space cruise line')
        ad_group_ad.ad.expanded_text_ad.path1.value = 'all-inclusive'
        ad_group_ad.ad.expanded_text_ad.path2.value = 'deals'

        ad_group_ad_operations.append(ad_group_ad_operation)

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

    for result in ad_group_ad_response.results:
        print('Created ad group ad {}.'.format(result.resource_name))
Exemple #6
0
def create_proximity_op(client, customer_id, campaign_id):
    campaign_service = client.get_service('CampaignService')

    # Create the campaign criterion.
    campaign_criterion_operation = client.get_type(
        'CampaignCriterionOperation')
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign.value = campaign_service.campaign_path(
        customer_id, campaign_id)
    campaign_criterion.proximity.address.street_address.value = '38 avenue de l\'Opera'
    campaign_criterion.proximity.address.city_name.value = 'Paris'
    campaign_criterion.proximity.address.postal_code.value = '75002'
    campaign_criterion.proximity.address.country_code.value = 'FR'
    campaign_criterion.proximity.radius.value = 10
    # Default is kilometers.
    campaign_criterion.proximity.radius_units = client.get_type(
        'ProximityRadiusUnitsEnum').MILES

    return campaign_criterion_operation
def add_shopping_product_ad_group(client, customer_id, campaign_resource_name):
    """Creates a new shopping product ad group in the specified campaign."""
    ad_group_service = client.get_service("AdGroupService", version="v6")

    # Create ad group.
    ad_group_operation = client.get_type("AdGroupOperation", version="v6")
    ad_group = ad_group_operation.create
    ad_group.name = "Earth to Mars cruise %s" % uuid.uuid4()
    ad_group.status = client.get_type("AdGroupStatusEnum", version="v6").ENABLED
    ad_group.campaign = campaign_resource_name
    # Sets the ad group type to SHOPPING_PRODUCT_ADS. This is the only value
    # possible for ad groups that contain shopping product ads.
    ad_group.type = client.get_type(
        "AdGroupTypeEnum", version="v6"
    ).SHOPPING_PRODUCT_ADS
    ad_group.cpc_bid_micros = 10000000

    # Add the ad group.
    try:
        ad_group_response = ad_group_service.mutate_ad_groups(
            customer_id, [ad_group_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)

    ad_group_resource_name = ad_group_response.results[0].resource_name

    print(
        'Added a product shopping ad group with resource name "%s".'
        % ad_group_resource_name
    )

    return ad_group_resource_name
def main(client, customer_id):
    conversion_action_service = client.get_service('ConversionActionService',
                                                   version='v1')

    # Create the operation.
    conversion_action_operation = client.get_type('ConversionActionOperation',
                                                  version='v1')

    # Create conversion action.
    conversion_action = conversion_action_operation.create
    conversion_action.name.value = ('Earth to Mars Cruises Conversion %s' %
                                    uuid.uuid4())
    conversion_action.type = client.get_type(
        'ConversionActionTypeEnum').UPLOAD_CLICKS
    conversion_action.category = client.get_type(
        'ConversionActionCategoryEnum').DEFAULT
    conversion_action.status = client.get_type(
        'ConversionActionStatusEnum').ENABLED
    conversion_action.view_through_lookback_window_days.value = 15

    # Create a value settings object.
    value_settings = conversion_action.value_settings
    value_settings.default_value.value = 15.0
    value_settings.always_use_default_value.value = True

    # Add the conversion action.
    try:
        conversion_action_response = (
            conversion_action_service.mutate_conversion_actions(
                customer_id, [conversion_action_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('Created conversion action "%s".' %
          conversion_action_response.results[0].resource_name)
def add_default_shopping_listing_group(client, customer_id,
                                       ad_group_resource_name):
    """Creates a new default shopping listing group for the specified ad group.

    A listing group is the Google Ads API representation of a "product group"
    described in the Google Ads user interface. The listing group will be added
    to the ad group using an "ad group criterion". The criterion will contain
    the bid for a given listing group.
    """
    ad_group_criterion_service = client.get_service('AdGroupCriterionService',
                                                    version='v2')

    # Creates a new ad group criterion. This will contain the "default" listing
    # group (All products).
    ad_group_criterion_operation = client.get_type('AdGroupCriterionOperation',
                                                   version='v2')
    ad_group_criterion = ad_group_criterion_operation.create
    ad_group_criterion.ad_group.value = ad_group_resource_name
    ad_group_criterion.status = client.get_type(
        'AdGroupCriterionStatusEnum').ENABLED
    ad_group_criterion.listing_group.type = client.get_type(
        'ListingGroupTypeEnum').UNIT
    #  Set the bid for products in this listing group unit.
    ad_group_criterion.cpc_bid_micros.value = 500000

    try:
        ad_group_criterion_response = (
            ad_group_criterion_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('Added an ad group criterion containing a listing group with \
           resource name:  %s.' %
          ad_group_criterion_response.results[0].resource_name)
def add_shopping_product_ad_group_ad(
    client, customer_id, ad_group_resource_name
):
    """Creates a new shopping product ad group ad in the specified ad group."""
    ad_group_ad_service = client.get_service("AdGroupAdService", version="v6")

    # Creates a new ad group ad and sets the product ad to it.
    ad_group_ad_operation = client.get_type("AdGroupAdOperation", version="v6")
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group = ad_group_resource_name
    ad_group_ad.status = client.get_type(
        "AdGroupAdStatusEnum", version="v6"
    ).PAUSED
    ad_group_ad.ad.shopping_product_ad.CopyFrom(
        client.get_type("ShoppingProductAdInfo")
    )

    # Add the ad group ad.
    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)

    ad_group_ad_resource_name = ad_group_ad_response.results[0].resource_name

    print(
        "Created shopping product ad group ad %s." % ad_group_ad_resource_name
    )

    return ad_group_resource_name
def _create_smart_display_campaign(client, customer_id, budget_resource_name):
    campaign_operation = client.get_type('CampaignOperation', version='v2')
    campaign = campaign_operation.create
    campaign.name.value = f'Smart Display Campaign #{uuid4()}'
    advertising_channel_type_enum = client.get_type(
        'AdvertisingChannelTypeEnum', version='v2')
    campaign.advertising_channel_type = advertising_channel_type_enum.DISPLAY
    advertising_channel_sub_type_enum = client.get_type(
        'AdvertisingChannelSubTypeEnum', version='v2')
    # Smart Display campaign requires the advertising_channel_sub_type as
    # "DISPLAY_SMART_CAMPAIGN".
    campaign.advertising_channel_sub_type = (
        advertising_channel_sub_type_enum.DISPLAY_SMART_CAMPAIGN)
    campaign_status_enum = client.get_type('CampaignStatusEnum', version='v2')
    campaign.status = campaign_status_enum.PAUSED
    # Smart Display campaign requires the TargetCpa bidding strategy.
    campaign.target_cpa.target_cpa_micros.value = 5000000
    campaign.campaign_budget.value = budget_resource_name
    # Optional: Set the start and end date.
    start_date = datetime.date.today() + datetime.timedelta(days=1)
    campaign.start_date.value = start_date.strftime(_DATE_FORMAT)
    end_date = start_date + datetime.timedelta(days=365)
    campaign.end_date.value = end_date.strftime(_DATE_FORMAT)

    campaign_service = client.get_service('CampaignService', version='v2')

    try:
        campaign_response = campaign_service.mutate_campaigns(
            customer_id, [campaign_operation])
    except google.ads.google_ads.errors.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)

    return campaign_response.results[0].resource_name
def add_hotel_ad(client, customer_id, ad_group_resource_name):
    ad_group_ad_service = client.get_service("AdGroupAdService", version="v6")

    # Creates a new ad group ad and sets the hotel ad to it.
    ad_group_ad_operation = client.get_type("AdGroupAdOperation", version="v6")
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group = ad_group_resource_name
    # Set the ad group ad to enabled.  Setting this to paused will cause an error
    # for hotel campaigns.  For hotels pausing should happen at either the ad group or
    # campaign level.
    ad_group_ad.status = client.get_type(
        "AdGroupAdStatusEnum", version="v6"
    ).ENABLED
    ad_group_ad.ad.hotel_ad.CopyFrom(
        client.get_type("HotelAdInfo", version="v6")
    )

    # Add the ad group ad.
    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)

    ad_group_ad_resource_name = ad_group_ad_response.results[0].resource_name

    print("Created hotel ad %s." % ad_group_ad_resource_name)

    return ad_group_resource_name
Exemple #13
0
def main(client):
    gtc_service = client.get_service("GeoTargetConstantService", version="v6")

    location_names = client.get_type("SuggestGeoTargetConstantsRequest",
                                     version="v6").LocationNames()

    location_names.names.extend(["Paris", "Quebec", "Spain", "Deutschland"])

    results = gtc_service.suggest_geo_target_constants(
        LOCALE, COUNTRY_CODE, location_names=location_names)

    geo_target_constant_status_enum = client.get_type(
        "GeoTargetConstantStatusEnum").GeoTargetConstantStatus

    try:
        for suggestion in results.geo_target_constant_suggestions:
            geo_target_constant = suggestion.geo_target_constant
            print(
                "%s (%s, %s, %s, %s) is found in locale (%s) with reach (%d) "
                "from search term (%s)." % (
                    geo_target_constant.resource_name,
                    geo_target_constant.name,
                    geo_target_constant.country_code,
                    geo_target_constant.target_type,
                    geo_target_constant_status_enum.Name(
                        geo_target_constant.status),
                    suggestion.locale,
                    suggestion.reach,
                    suggestion.search_term,
                ))
    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)
Exemple #14
0
def main(client, customer_id, ad_group_id, bid_modifier_value):
    ad_group_service = client.get_service('AdGroupService', version='v2')
    ad_group_bm_service = client.get_service('AdGroupBidModifierService',
                                             version='v2')

    # Create ad group bid modifier for mobile devices with the specified ad
    # group ID and bid modifier value.
    ad_group_bid_modifier_operation = client.get_type(
        'AdGroupBidModifierOperation')
    ad_group_bid_modifier = ad_group_bid_modifier_operation.create

    # Set the ad group.
    ad_group_bid_modifier.ad_group.value = ad_group_service.ad_group_path(
        customer_id, ad_group_id)

    # Set the bid modifier.
    ad_group_bid_modifier.bid_modifier.value = bid_modifier_value

    # Sets the device.
    ad_group_bid_modifier.device.type = client.get_type('DeviceEnum',
                                                        version='v2').MOBILE

    # Add the ad group bid modifier.
    try:
        ad_group_bm_response = (
            ad_group_bm_service.mutate_ad_group_bid_modifiers(
                customer_id, [ad_group_bid_modifier_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('Created ad group bid modifier: %s.' %
          ad_group_bm_response.results[0].resource_name)
def add_campaign_budget(client, customer_id):
    """Creates a new campaign budget in the specified client account."""
    campaign_budget_service = client.get_service(
        "CampaignBudgetService", version="v6"
    )

    # Create a budget, which can be shared by multiple campaigns.
    campaign_budget_operation = client.get_type(
        "CampaignBudgetOperation", version="v6"
    )
    campaign_budget = campaign_budget_operation.create
    campaign_budget.name = "Interplanetary Budget %s" % uuid.uuid4()
    campaign_budget.delivery_method = client.get_type(
        "BudgetDeliveryMethodEnum"
    ).STANDARD
    campaign_budget.amount_micros = 500000

    # Add budget.
    try:
        campaign_budget_response = campaign_budget_service.mutate_campaign_budgets(
            customer_id, [campaign_budget_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)

    budget_resource_name = campaign_budget_response.results[0].resource_name

    print("Added a budget with resource name: %s" % budget_resource_name)

    return budget_resource_name
def main(client, customer_id, campaign_id, bid_modifier_value):
    campaign_service = client.get_service('CampaignService', version='v2')
    campaign_bm_service = client.get_service('CampaignBidModifierService',
                                             version='v2')

    # Create campaign bid modifier for call interactions with the specified
    # campaign ID and bid modifier value.
    campaign_bid_modifier_operation = client.get_type(
        'CampaignBidModifierOperation')
    campaign_bid_modifier = campaign_bid_modifier_operation.create

    # Set the campaign.
    campaign_bid_modifier.campaign.value = campaign_service.campaign_path(
        customer_id, campaign_id)

    # Set the bid modifier.
    campaign_bid_modifier.bid_modifier.value = bid_modifier_value

    # Sets the interaction type.
    campaign_bid_modifier.interaction_type.type = (client.get_type(
        'InteractionTypeEnum', version='v2').CALLS)

    # Add the campaign bid modifier.
    try:
        campaign_bm_response = (
            campaign_bm_service.mutate_campaign_bid_modifiers(
                customer_id, [campaign_bid_modifier_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('Created campaign bid modifier: %s.' %
          campaign_bm_response.results[0].resource_name)
Exemple #17
0
def main(client, customer_id, ad_group_id):
    ad_group_ad_service = client.get_service('AdGroupAdService', version='v1')
    ad_group_service = client.get_service('AdGroupService', version='v1')

    # Create ad group ad.
    ad_group_ad_operation = client.get_type('AdGroupAdOperation', version='v1')
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group.value = ad_group_service.ad_group_path(
        customer_id, ad_group_id)
    ad_group_ad.status = client.get_type('AdGroupAdStatusEnum',
                                         version='v1').PAUSED

    # Set expanded text ad info
    final_url = ad_group_ad.ad.final_urls.add()
    final_url.value = 'http://www.example.com'
    ad_group_ad.ad.expanded_text_ad.description.value = 'Buy your tickets now!'
    ad_group_ad.ad.expanded_text_ad.headline_part1.value = (
        'Cruise to Mars %s' % str(uuid.uuid4())[:15])
    ad_group_ad.ad.expanded_text_ad.headline_part2.value = (
        'Best space cruise line')
    ad_group_ad.ad.expanded_text_ad.path1.value = 'all-inclusive'
    ad_group_ad.ad.expanded_text_ad.path2.value = 'deals'

    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('Created ad group ad %s.' %
          ad_group_ad_response.results[0].resource_name)
def add_hotel_ad_group(client, customer_id, campaign_resource_name):
    ad_group_service = client.get_service("AdGroupService", version="v6")

    # Create ad group.
    ad_group_operation = client.get_type("AdGroupOperation", version="v6")
    ad_group = ad_group_operation.create
    ad_group.name = "Earth to Mars cruise %s" % uuid.uuid4()
    ad_group.status = client.get_type("AdGroupStatusEnum", version="v6").ENABLED
    ad_group.campaign = campaign_resource_name
    # Sets the ad group type to HOTEL_ADS. This cannot be set to other types.
    ad_group.type = client.get_type("AdGroupTypeEnum", version="v6").HOTEL_ADS
    ad_group.cpc_bid_micros = 10000000

    # Add the ad group.
    try:
        ad_group_response = ad_group_service.mutate_ad_groups(
            customer_id, [ad_group_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)

    ad_group_resource_name = ad_group_response.results[0].resource_name

    print(
        'Added a hotel ad group with resource name "%s".'
        % ad_group_resource_name
    )

    return ad_group_resource_name
Exemple #19
0
def _print_remarketing_action_attributes(client, remarketing_action):
    tracking_code_type_enum = client.get_type('TrackingCodeTypeEnum',
                                              version='v2').TrackingCodeType
    tracking_code_page_format_enum = client.get_type(
        'TrackingCodePageFormatEnum', version='v2').TrackingCodePageFormat

    print(f'Remarketing action has ID {remarketing_action.id.value} and name '
          f'"{remarketing_action.name.value}". \nIt has the following '
          'generated tag snippets:\n')

    for tag_snippet in remarketing_action.tag_snippets:
        tracking_code_type = tracking_code_type_enum.Name(tag_snippet.type)
        tracking_code_page_format = tracking_code_page_format_enum.Name(
            tag_snippet.page_format)

        print('=' * 80)
        print(
            f'Tag snippet with code type "{tracking_code_type}", and code '
            f'page format "{tracking_code_page_format}" has the following:\n')
        print('-' * 80)
        print(f'Global site tag: \n\n{tag_snippet.global_site_tag.value}')
        print('-' * 80)
        print(f'Event snippet: \n\n{tag_snippet.event_snippet.value}')
Exemple #20
0
def _print_remarketing_action_attributes(client, remarketing_action):
    tracking_code_type_enum = client.get_type("TrackingCodeTypeEnum",
                                              version="v6").TrackingCodeType
    tracking_code_page_format_enum = client.get_type(
        "TrackingCodePageFormatEnum", version="v6").TrackingCodePageFormat

    print(f"Remarketing action has ID {remarketing_action.id} and name "
          f'"{remarketing_action.name}". \nIt has the following '
          "generated tag snippets:\n")

    for tag_snippet in remarketing_action.tag_snippets:
        tracking_code_type = tracking_code_type_enum.Name(tag_snippet.type)
        tracking_code_page_format = tracking_code_page_format_enum.Name(
            tag_snippet.page_format)

        print("=" * 80)
        print(
            f'Tag snippet with code type "{tracking_code_type}", and code '
            f'page format "{tracking_code_page_format}" has the following:\n')
        print("-" * 80)
        print(f"Global site tag: \n\n{tag_snippet.global_site_tag}")
        print("-" * 80)
        print(f"Event snippet: \n\n{tag_snippet.event_snippet}")
def _upload_image_asset(client, customer_id, image_url, image_width,
                        image_height):
    # Download image from URL
    image_content = requests.get(image_url).content

    asset_operation = client.get_type('AssetOperation', version='v2')
    asset = asset_operation.create
    # Optional: Provide a unique friendly name to identify your asset. If you
    # specify the name field, then both the asset name and the image being
    # uploaded should be unique, and should not match another ACTIVE asset in
    # this customer account.
    # asset.name.value = f'Jupiter Trip #{uuid4()}'
    asset_type_enum = client.get_type('AssetTypeEnum', version='v2')
    asset.type = asset_type_enum.IMAGE
    image_asset = asset.image_asset
    image_asset.data.value = image_content
    image_asset.file_size.value = len(image_content)
    image_asset.mime_type = client.get_type('MimeTypeEnum').IMAGE_JPEG
    image_asset.full_size.width_pixels.value = image_width
    image_asset.full_size.height_pixels.value = image_height
    image_asset.full_size.url.value = image_url

    asset_service = client.get_service('AssetService', version='v2')

    try:
        mutate_asset_response = (asset_service.mutate_assets(
            customer_id, [asset_operation]))
        return mutate_asset_response.results[0].resource_name
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print(f'Request with ID "{ex.request_id}" failed with status '
              f'"{ex.error.code().name}" and includes the following errors:')
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f'\t\tOn field: {field_path_element.field_name}')
        sys.exit(1)
def _create_ad_group(client, customer_id, campaign_resource_name):
    ad_group_operation = client.get_type('AdGroupOperation', version='v2')
    ad_group = ad_group_operation.create
    ad_group.name.value = f'Earth to Mars Cruises #{uuid4()}'
    ad_group_status_enum = client.get_type('AdGroupStatusEnum', version='v2')
    ad_group.status = ad_group_status_enum.PAUSED
    ad_group.campaign.value = campaign_resource_name

    ad_group_service = client.get_service('AdGroupService', version='v2')

    try:
        ad_group_response = ad_group_service.mutate_ad_groups(
            customer_id, [ad_group_operation])
    except google.ads.google_ads.errors.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)

    return ad_group_response.results[0].resource_name
def main(client, customer_id, campaign_id, page_size):
    ga_service = client.get_service("GoogleAdsService", version="v5")

    query = (
        "SELECT campaign.id, campaign_criterion.campaign, "
        "campaign_criterion.criterion_id, campaign_criterion.negative, "
        "campaign_criterion.type, campaign_criterion.keyword.text, "
        "campaign_criterion.keyword.match_type "
        "FROM campaign_criterion "
        "WHERE campaign.id = %s"
    ) % campaign_id

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

    try:
        for row in results:
            criterion = row.campaign_criterion
            print(
                'Campaign criterion with ID "%s" was retrieved:'
                % criterion.criterion_id
            )

            if (
                criterion.type
                == client.get_type("CriterionTypeEnum", version="v5").KEYWORD
            ):
                print(
                    '\t%sKeyword with text "%s" and match type %s.'
                    % (
                        "" if criterion.negative else "Negative",
                        criterion.keyword.text,
                        criterion.keyword.match_type,
                    )
                )
            else:
                print("Not a keyword!")
    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)
Exemple #24
0
def main(client, customer_id, page_size):
    ga_service = client.get_service('GoogleAdsService', version='v1')

    query = (
        'SELECT billing_setup.id, billing_setup.status, '
        'billing_setup.payments_account, '
        'billing_setup.payments_account_info.payments_account_id, '
        'billing_setup.payments_account_info.payments_account_name, '
        'billing_setup.payments_account_info.payments_profile_id, '
        'billing_setup.payments_account_info.payments_profile_name, '
        'billing_setup.payments_account_info.secondary_payments_profile_id '
        'FROM billing_setup')

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

    try:
        # Use the enum type to determine the enum name from the value.
        billing_setup_status_enum = (
            client.get_type('BillingSetupStatusEnum', version='v1')
                .BillingSetupStatus)

        print('Found the following billing setup results:')
        for row in results:
            billing_setup = row.billing_setup
            payments_account_info = billing_setup.payments_account_info
            print('Billing setup with ID "%s", status "%s", '
                  'payments_account "%s", payments_account_id "%s", '
                  'payments_account_name "%s", payments_profile_id "%s", '
                  'payments_profile_name "%s", '
                  'secondary_payments_profile_id "%s".'
                  % (billing_setup.id.value,
                     billing_setup_status_enum.Name(billing_setup.status),
                     billing_setup.payments_account.value,
                     payments_account_info.payments_account_id.value,
                     payments_account_info.payments_account_name.value,
                     payments_account_info.payments_profile_id.value,
                     payments_account_info.payments_profile_name.value,
                     payments_account_info.secondary_payments_profile_id.value))
    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)
Exemple #25
0
def create_location_op(client, customer_id, campaign_id, location_id):
    campaign_service = client.get_service('CampaignService')
    geo_target_constant_service = client.get_service(
        'GeoTargetConstantService')

    # Create the campaign criterion.
    campaign_criterion_operation = client.get_type(
        'CampaignCriterionOperation')
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign.value = campaign_service.campaign_path(
        customer_id, campaign_id)

    # Besides using location_id, you can also search by location names from
    # GeoTargetConstantService.suggest_geo_target_constants() and directly
    # apply GeoTargetConstant.resource_name here. An example can be found
    # in get_geo_target_constant_by_names.py.
    campaign_criterion.location.geo_target_constant.value = (
        geo_target_constant_service.geo_target_constant_path(location_id))

    return campaign_criterion_operation
def add_campaigns_to_group(client, customer_id, campaign_group_resource_name,
                           campaign_ids):
    campaign_service = client.get_service('CampaignService')

    campaign_operations = []

    for campaign_id in campaign_ids:
        # Create the campaign operation.
        campaign_operation = client.get_type('CampaignOperation')

        # Create a campaign, and set its resource name and campaign group.
        campaign = campaign_operation.update
        campaign.resource_name = campaign_service.campaign_path(
            customer_id, campaign_id)
        campaign.campaign_group.value = campaign_group_resource_name

        # Retrieve a FieldMask for the fields configured in the campaign.
        fm = protobuf_helpers.field_mask(None, campaign)
        campaign_operation.update_mask.CopyFrom(fm)

        campaign_operations.append(campaign_operation)

    try:
        # Associate the campaigns with the campaign group.
        response = campaign_service.mutate_campaigns(customer_id,
                                                     campaign_operations)
    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('Added %d campaigns to campaign group with resource name "%s":' %
          (len(response.results), campaign_group_resource_name))

    for updated_campaign in response.results:
        print('\t%s' % updated_campaign.resource_name)
def main(client, manager_customer_id):
    customer_service = client.get_service("CustomerService", version="v6")
    customer = client.get_type("Customer", version="v6")
    today = datetime.today().strftime("%Y%m%d %H:%M:%S")
    customer.descriptive_name = (
        "Account created with " "CustomerService on %s" % today
    )
    # For a list of valid currency codes and time zones see this documentation:
    # https://developers.google.com/adwords/api/docs/appendix/codes-formats
    customer.currency_code = "USD"
    customer.time_zone = "America/New_York"
    # The below values are optional. For more information about URL
    # options see: https://support.google.com/google-ads/answer/6305348
    customer.tracking_url_template = "{lpurl}?device={device}"
    customer.final_url_suffix = (
        "keyword={keyword}&matchtype={matchtype}" "&adgroupid={adgroupid}"
    )
    customer.has_partners_badge = False

    try:
        response = customer_service.create_customer_client(
            manager_customer_id, customer
        )
        print(
            (
                'Customer created with resource name "%s" under manager account '
                'with customer ID "%s"'
            )
            % (response.resource_name, manager_customer_id)
        )
    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)
def main(client, customer_id, campaign_id):
    campaign_service = client.get_service('CampaignService')
    campaign_operation = client.get_type('CampaignOperation')

    resource_name = campaign_service.campaign_path(customer_id, campaign_id)
    campaign_operation.remove = resource_name

    try:
        campaign_response = campaign_service.mutate_campaigns(
            customer_id, [campaign_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 campaign %s.' % campaign_response.results[0].resource_name)
Exemple #29
0
def main(client, customer_id, ad_group_id):
    ad_group_service = client.get_service('AdGroupService', version='v3')
    ad_group_operation = client.get_type('AdGroupOperation', version='v3')

    resource_name = ad_group_service.ad_group_path(customer_id, ad_group_id)
    ad_group_operation.remove = resource_name

    try:
        ad_group_response = ad_group_service.mutate_ad_groups(
            customer_id, [ad_group_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 ad group %s.' % ad_group_response.results[0].resource_name)
Exemple #30
0
def main(client, customer_id, page_size, ad_group_id=None):
    ga_service = client.get_service("GoogleAdsService", version="v6")

    query = """
        SELECT
          campaign.id,
          ad_group.id,
          ad_group_bid_modifier.criterion_id,
          ad_group_bid_modifier.bid_modifier,
          ad_group_bid_modifier.device.type
        FROM ad_group_bid_modifier"""

    if ad_group_id:
        query += f" WHERE ad_group.id = {ad_group_id}"

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

    # Use the enum type to determine the enum name from the value.
    device_enum = client.get_type("DeviceEnum", version="v6").Device

    try:
        for row in results:
            print('Ad group bid modifier with criterion ID "%s", bid modifier '
                  'value "%s", device type "%s" was found in ad group ID "%s" '
                  'of campaign with ID "%s".' % (
                      row.ad_group_bid_modifier.criterion_id,
                      row.ad_group_bid_modifier.bid_modifier,
                      device_enum.Name(row.ad_group_bid_modifier.device.type),
                      row.ad_group.id,
                      row.campaign.id,
                  ))
    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)