[HubSpot API + Python] HubSpotの会社-コンタクトの関連付けをAPIを使って�一括削除する

Share

[HubSpot API + Python] HubSpotの会社-コンタクトの関連付けをAPIを使って一括削除する

前提

HubSpotには画面からのユーザインタフェースとして、レコード同志の関連付け(association)を一括削除する機能が提供されていません(2024年01月現在)。そのため、一括削除を行うためにはHubSpot APIを使ったプログラム実装が必要になります。

Pythonでの会社-コンタクトの関連付け一括削除の実装例を示します。

解法

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from hubspot import HubSpot
from hubspot.crm.contacts import PublicObjectSearchRequest, ApiException
from hubspot.crm.associations import BatchInputPublicAssociation, BatchInputPublicObjectId, ApiException
import logging


# ロギング設定
logging.basicConfig(format='%(asctime)s - %(threadName)s - %(module)s:%(funcName)s(%(lineno)d) - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# HubSpotクライアントの作成
hubspot = HubSpot(access_token=os.environ["HUBSPOT_ACCESS_TOKEN"])

# 一括削除を実行(company_id、domainはパラメータとして取得しているものとします)
archive_associations(hubspot, company_id, domain)


"""
company_idの会社に紐づく、メールドメインにdomainを持つコンタクトとの紐付けを一括削除する
"""
def archive_associations(hubspot, company_id, domain):
    logger.info("archive associations")

    try:
        associated_contacts = get_associated_contacts(hubspot, company_id, domain)
        if len(contacts) > 0:
            archive_from_company_to_contact_associations(hubspot, company_id, associated_contacts)
            logger.info("ARCHIVED")
        else:
            logger.info("ARCHIVE_TARGET_IS_NOT_FOUND")
    except ApiException as e:
        print("Exception when archive associations: %s\n" % e)
        raise


"""
company_idの会社に紐付き、メールドメインがdomainに等しいコンタクトのリストを取得する
"""
def get_associated_contacts(hubspot, company_id, domain):
    batch_input_public_object_id = BatchInputPublicObjectId(inputs=[{"id":company_id}])
    try:
        # company_idの会社に紐づくコンタクトIDのリストを得る
        contact_ids = []
        api_response = hubspot.crm.associations.batch_api.read(from_object_type="company", to_object_type="contact", batch_input_public_object_id=batch_input_public_object_id)
        for result in api_response.results:
            for to in result.to:
                contact_ids.append(to.id)

        # 取得したコンタクトIDから当該コンタクトのメールドメインを取得する
        contact_id_filter = {
            "filters": [
                {
                    "propertyName": "hs_object_id",
                    "operator": "IN",
                    "values": contact_ids
                }
            ]
        }
        filter_groups = []
        if len(contact_ids) > 0:
            filter_groups.append(contact_id_filter)
        public_object_search_request = PublicObjectSearchRequest(
            filter_groups=filter_groups,
            properties=['hs_object_id', 'hs_email_domain'],
            limit=100
        )
        api_response = hubspot.crm.contacts.search_api.do_search(public_object_search_request=public_object_search_request)

        # メールドメインがdomainと等しいコンタクトだけに絞り込んで返す
        associated_contacts = []
        if len(api_response.results) > 0:
            for result in api_response.results:
                if result.properties.get("hs_email_domain") is not None and result.properties.get("hs_email_domain") != "" and result.properties.get("hs_email_domain") == domain:
                    associated_contacts.append({
                        "id": result.properties.get("hs_object_id"),
                        "domain": result.properties.get("hs_email_domain")
                    })
    except ApiException as e:
        print("Exception when get archive associated contacts: %s\n" % e)

    return associated_contacts


"""
company_idの会社に紐付いているassociated_contactsのコンタクト群との紐付きを一括削除する
"""
def archive_from_company_to_contact_associations(hubspot, company_id, associated_contacts):
    params = {
        "from_object_type": "company",
        "to_object_type": "contact",
        "batch_input_public_association": BatchInputPublicAssociation(
            inputs=[{"from":{"id":company_id},"to":{"id":item["id"]},"type":"company_to_contact"} for item in associated_contacts]
         )
    }
    try:
        api_response = hubspot.crm.associations.batch_api.archive(**params)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling batch_api->archive: %s\n" % e)

archive_associations(hubspot, company_id, domain)に関連付けを一括削除したい会社ID(company_id)とメールドメイン(domain)を指定して実行します。

Batch APIを使っているのでAPIの発行回数も抑えられています。

See Also

Share