Hi there, I am creating a new user-list and adding around 1000,000 Mobile 
advertising ids into it, but when we verify customer list from Google ads 
Dashboard it says that size = 0.
Please have a look into this matter and let me know where am I wrong.


Attached files are python code which I am using to create a user-list and 
adding maid-ids to it.

-- 
-- 
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
Also find us on our blog:
https://googleadsdeveloper.blogspot.com/
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~

You received this message because you are subscribed to the Google
Groups "AdWords API and Google Ads API Forum" group.
To post to this group, send email to adwords-api@googlegroups.com
To unsubscribe from this group, send email to
adwords-api+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/adwords-api?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Google Ads API and AdWords API Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to adwords-api+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/adwords-api/0346672f-b04a-4beb-bf3e-eabe3cf930c3n%40googlegroups.com.
import csv
import uuid

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
from common.web import google
import mysql.connector
from common import db_config as config

class UserList:
    def init(self):
        credentials = {
            "developer_token": google['developer_token'],
            "refresh_token": google['refresh_token'],
            "client_id": google['client_id'],
            "client_secret": google['client_secret'],
            "use_proto_plus": google['use_proto_plus'],
            "login_customer_id": google['login_customer_id']
        }

        self.client = GoogleAdsClient.load_from_dict(
            credentials, version="v15")

    def main(self,
             customer_id, name,
             maid_ids,
             run_job,
             user_list_id,
             offline_user_data_job_id,
             ad_user_data_consent,
             ad_personalization_consent,
             ):
        googleads_service = self.client.get_service("GoogleAdsService")
        user_list_resource_name = googleads_service.user_list_path(
            customer_id, user_list_id
        )
        if not offline_user_data_job_id:
            if user_list_id:
                # Uses the specified Customer Match user list.
                user_list_resource_name = googleads_service.user_list_path(
                    customer_id, user_list_id
                )
            else:
                # Creates a Customer Match user list.
                user_list_resource_name = self.create_customer_match_user_list(
                    customer_id, name
                )

        self.add_users_to_customer_match_user_list(
            customer_id,
            maid_ids,
            user_list_resource_name,
            run_job,
            offline_user_data_job_id,
            ad_user_data_consent,
            ad_personalization_consent,
        )
        return user_list_resource_name

    def create_customer_match_user_list(self, customer_id, name):
        user_list_service_client = self.client.get_service("UserListService")
        user_list_operation = self.client.get_type("UserListOperation")
        user_list = user_list_operation.create
        user_list.name = name
        user_list.description = (
            "A list of customers that originated from email and physical addresses"
        )
        # application-id
        user_list.crm_based_user_list.app_id = "io.yarsa.games.ludo"
        user_list.crm_based_user_list.upload_key_type = (
            self.client.enums.CustomerMatchUploadKeyTypeEnum.MOBILE_ADVERTISING_ID
        )
        # Customer Match user lists can set an unlimited membership life span;
        # to do so, use the special life span value 10000. Otherwise, membership
        # life span must be between 0 and 540 days inclusive. See:
        # https://developers.devsite.corp.google.com/google-ads/api/reference/rpc/latest/UserList#membership_life_span
        # Sets the membership life span to 30 days.
        user_list.membership_life_span = 30
        response = user_list_service_client.mutate_user_lists(
            customer_id=customer_id, operations=[user_list_operation]
        )
        user_list_resource_name = response.results[0].resource_name
        print(
            f"User list with resource name '{user_list_resource_name}' was created."
        )

        return user_list_resource_name

    def add_users_to_customer_match_user_list(self,
                                              customer_id,
                                              maid_ids,
                                              user_list_resource_name,
                                              run_job,
                                              offline_user_data_job_id,
                                              ad_user_data_consent,
                                              ad_personalization_consent,
                                              ):
        offline_user_data_job_service_client = self.client.get_service(
            "OfflineUserDataJobService"
        )
        if offline_user_data_job_id:
            # Reuses the specified offline user data job.
            offline_user_data_job_resource_name = (
                offline_user_data_job_service_client.offline_user_data_job_path(
                    customer_id, offline_user_data_job_id
                )
            )
        else:
            # Creates a new offline user data job.
            offline_user_data_job = self.client.get_type("OfflineUserDataJob")
            offline_user_data_job.type_ = (
                self.client.enums.OfflineUserDataJobTypeEnum.CUSTOMER_MATCH_USER_LIST
            )
            offline_user_data_job.customer_match_user_list_metadata.user_list = (
                user_list_resource_name
            )

            # Specifies whether user consent was obtained for the data you are
            # uploading. For more details, see:
            # https://www.google.com/about/company/user-consent-policy
            if ad_user_data_consent:
                offline_user_data_job.customer_match_user_list_metadata.consent.ad_user_data = self.client.enums.ConsentStatusEnum[
                    ad_user_data_consent
                ]
            if ad_personalization_consent:
                offline_user_data_job.customer_match_user_list_metadata.consent.ad_personalization = self.client.enums.ConsentStatusEnum[
                    ad_personalization_consent
                ]

            # Issues a request to create an offline user data job.
            create_offline_user_data_job_response = (
                offline_user_data_job_service_client.create_offline_user_data_job(
                    customer_id=customer_id, job=offline_user_data_job
                )
            )
            offline_user_data_job_resource_name = (
                create_offline_user_data_job_response.resource_name
            )
            print(
                "Created an offline user data job with resource name: "
                f"'{offline_user_data_job_resource_name}'."
            )

        # Issues a request to add the operations to the offline user data job.

        # Best Practice: This example only adds a few operations, so it only sends
        # one AddOfflineUserDataJobOperations request. If your application is adding
        # a large number of operations, split the operations into batches and send
        # multiple AddOfflineUserDataJobOperations requests for the SAME job. See
        # https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations
        # and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data
        # for more information on the per-request limits.
        maid_ids_list = []
        i = 0
        while i < len(maid_ids):
            maid_ids_list.append(maid_ids[i: i + 999999])
            i = i + 999999
        for maid_id in maid_ids_list:
            request = self.client.get_type(
                "AddOfflineUserDataJobOperationsRequest")
            request.resource_name = offline_user_data_job_resource_name
            request.operations = self.build_offline_user_data_job_operations(
                maid_id)
            request.enable_partial_failure = True

            # Issues a request to add the operations to the offline user data job.
            response = offline_user_data_job_service_client.add_offline_user_data_job_operations(
                request=request
            )

            # Prints the status message if any partial failure error is returned.
            # Note: the details of each partial failure error are not printed here.
            # Refer to the error_handling/handle_partial_failure.py example to learn
            # more.
            # Extracts the partial failure from the response status.
            partial_failure = getattr(response, "partial_failure_error", None)
            if getattr(partial_failure, "code", None) != 0:
                error_details = getattr(partial_failure, "details", [])
                for error_detail in error_details:
                    failure_message = self.client.get_type("GoogleAdsFailure")
                    # Retrieve the class definition of the GoogleAdsFailure instance
                    # in order to use the "deserialize" class method to parse the
                    # error_detail string into a protobuf message object.
                    failure_object = type(failure_message).deserialize(
                        error_detail.value
                    )

                    for error in failure_object.errors:
                        print(
                            "A partial failure at index "
                            f"{error.location.field_path_elements[0].index} occurred.\n"
                            f"Error message: {error.message}\n"
                            f"Error code: {error.error_code}"
                        )

            print("The operations are added to the offline user data job.")

        if not run_job:
            print(
                "Not running offline user data job "
                f"'{offline_user_data_job_resource_name}', as requested."
            )
            return

        # Issues a request to run the offline user data job for executing all
        # added operations.
        offline_user_data_job_service_client.run_offline_user_data_job(
            resource_name=offline_user_data_job_resource_name
        )

        # Retrieves and displays the job status.
        status = self.check_job_status(customer_id,
                                       offline_user_data_job_resource_name)
        # [END add_customer_match_user_list]
        self.add_userlist_details_to_db(
            user_list_resource_name, offline_user_data_job_resource_name, status)

    # [START add_customer_match_user_list_2]

    def build_offline_user_data_job_operations(self, maid_ids):
        """Creates a raw input list of unhashed user information.

        Each element of the list represents a single user and is a dict containing a
        separate entry for the keys "email", "phone", "first_name", "last_name",
        "country_code", and "postal_code". In your application, this data might come
        from a file or a database.

        Args:
            client: The Google Ads client.

        Returns:
            A list containing the operations.
        """
        # The first user data has an email address and a phone number.
        raw_records = []
        for maid_id in maid_ids:
            raw_record = {
                "mobile_id": maid_id
            }

            # Adds the raw records to a raw input list.
            raw_records.append(raw_record)

        operations = []
        # Iterates over the raw input list and creates a UserData object for each
        # record.
        for record in raw_records:
            # Creates a UserData object that represents a member of the user list.
            user_data = self.client.get_type("UserData")

            # Checks if the record has email, phone, or address information, and
            # adds a SEPARATE UserIdentifier object for each one found. For example,
            # a record with an email address and a phone number will result in a
            # UserData with two UserIdentifiers.

            # IMPORTANT: Since the identifier attribute of UserIdentifier
            # (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier)
            # is a oneof
            # (https://protobuf.dev/programming-guides/proto3/#oneof-features), you
            # must set only ONE of hashed_email, hashed_phone_number, mobile_id,
            # third_party_user_id, or address-info. Setting more than one of these
            # attributes on the same UserIdentifier will clear all the other members
            # of the oneof. For example, the following code is INCORRECT and will
            # result in a UserIdentifier with ONLY a hashed_phone_number:

            # incorrect_user_identifier = client.get_type("UserIdentifier")
            # incorrect_user_identifier.hashed_email = "..."
            # incorrect_user_identifier.hashed_phone_number = "..."

            # The separate 'if' statements below demonstrate the correct approach
            # for creating a UserData object for a member with multiple
            # UserIdentifiers.

            # Checks if the record has an email address, and if so, adds a
            # UserIdentifier for it.
            user_identifier = self.client.get_type("UserIdentifier")
            user_identifier.mobile_id = record["mobile_id"]
            user_data.user_identifiers.append(user_identifier)

            # If the user_identifiers repeated field is not empty, create a new
            # OfflineUserDataJobOperation and add the UserData to it.
            if user_data.user_identifiers:
                operation = self.client.get_type("OfflineUserDataJobOperation")
                operation.create = user_data
                operations.append(operation)
            # [END add_customer_match_user_list_2]

        return operations

    # [START add_customer_match_user_list_4]

    def check_job_status(self, customer_id, offline_user_data_job_resource_name):
        """Retrieves, checks, and prints the status of the offline user data job.

        If the job is completed successfully, information about the user list is
        printed. Otherwise, a GAQL query will be printed, which can be used to
        check the job status at a later date.

        Offline user data jobs may take 6 hours or more to complete, so checking the
        status periodically, instead of waiting, can be more efficient.

        Args:
            client: The Google Ads client.
            customer_id: The ID for the customer that owns the user list.
            offline_user_data_job_resource_name: The resource name of the offline
                user data job to get the status of.
        """
        query = f"""
            SELECT
            offline_user_data_job.resource_name,
            offline_user_data_job.id,
            offline_user_data_job.status,
            offline_user_data_job.type,
            offline_user_data_job.failure_reason,
            offline_user_data_job.customer_match_user_list_metadata.user_list
            FROM offline_user_data_job
            WHERE offline_user_data_job.resource_name =
            '{offline_user_data_job_resource_name}'
            LIMIT 1"""

        # Issues a search request using streaming.
        google_ads_service = self.client.get_service("GoogleAdsService")
        results = google_ads_service.search(
            customer_id=customer_id, query=query)
        offline_user_data_job = next(iter(results)).offline_user_data_job
        status_name = offline_user_data_job.status.name
        user_list_resource_name = (
            offline_user_data_job.customer_match_user_list_metadata.user_list
        )

        print(
            f"Offline user data job ID '{offline_user_data_job.id}' with type "
            f"'{offline_user_data_job.type_.name}' has status: {status_name}"
        )

        if status_name == "SUCCESS":
            self.print_customer_match_user_list_info(
                customer_id, user_list_resource_name
            )
        elif status_name == "FAILED":
            print(f"\tFailure Reason: {offline_user_data_job.failure_reason}")
        elif status_name in ("PENDING", "RUNNING"):
            print(
                "To check the status of the job periodically, use the following "
                f"GAQL query with GoogleAdsService.Search: {query}"
            )
        return status_name
        # [END add_customer_match_user_list_4]

    def print_customer_match_user_list_info(self,
                                            customer_id, user_list_resource_name
                                            ):
        """Prints information about the Customer Match user list.

        Args:
            client: The Google Ads client.
            customer_id: The ID for the customer that owns the user list.
            user_list_resource_name: The resource name of the user list to which to
                add users.
        """
        # [START add_customer_match_user_list_5]
        googleads_service_client = self.client.get_service("GoogleAdsService")

        # Creates a query that retrieves the user list.
        query = f"""
            SELECT
            user_list.size_for_display,
            user_list.size_for_search
            FROM user_list
            WHERE user_list.resource_name = '{user_list_resource_name}'"""

        # Issues a search request.
        search_results = googleads_service_client.search(
            customer_id=customer_id, query=query
        )
        # [END add_customer_match_user_list_5]

        # Prints out some information about the user list.
        user_list = next(iter(search_results)).user_list
        print(
            "The estimated number of users that the user list "
            f"'{user_list.resource_name}' has is "
            f"{user_list.size_for_display} for Display and "
            f"{user_list.size_for_search} for Search."
        )
        print(
            "Reminder: It may take several hours for the user list to be "
            "populated. Estimates of size zero are possible."
        )

    def add_userlist(self, customer_id, name, maid_ids, run_job=False, user_list_id=None,
                     offline_user_data_job_id=None,
                     ad_user_data_consent=None,
                     ad_personalization_consent=None,
                     ):
        # run_job
        #     "If true, runs the OfflineUserDataJob after adding operations. "
        #     "The default value is False."

        # user_list_id
        #         "The ID of an existing user list. If not specified, this example "
        #         "will create a new user list."

        # offline job id

        #         "The ID of an existing OfflineUserDataJob in the PENDING state. If "
        #         "not specified, this example will create a new job."

        # ad_user_consent
        #             "The data consent status for ad user data for all members in "
        #         "the job."

        # ad_personalization_consent
        #             "The personalization consent status for ad user data for all "
        #         "members in the job."
        self.init()
        try:
            return self.main(
                customer_id,
                name,
                maid_ids,
                run_job,
                user_list_id,
                offline_user_data_job_id,
                ad_user_data_consent,
                ad_personalization_consent,
            )
        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}")

Reply via email to