Exportando Associação

Olá,

Bem com um problema para utilizar o associationTypeId nesse codigo que faz uma exportação automatica do HS, já está tudo certo mais preciso que ele imprima também está Associação dentro do meu arquivo (xlsx)
“objectType”: “TICKETS”,

“associationTypeId”: 28, help

“objectProperties”: [

‘subject’,

‘hs_pipeline’,

‘hs_pipeline_stage’,

‘createdate’,

‘hs_lastmodifieddate’,

Olá @TSiilva, obrigada por postar em nossa Comunidade!

Gostaria de convidar nossos colaboradores, @DanielSanchez, @Brenner e @Tesore alguma recomendação para @TSiilva?

Obrigada,

Pam

Olá @TSiilva

Eu infelizmente não tenho acesso rápido ao banco de dados para pegar a informação correta, mas tenta incluir “associationLabel” no code

Obrigado @PamCotton pela menção

Olá @Brenner

Você consegue me dar algum exemplo de como posso usar o “associationLabel”, não consegui localiza-lo no developers.hubspot

Olá @TSiilva ,

Desculpa a demora, estava em viagem. Perguntei aqui para o meu time, e recebi esse tipo de resposta, veja se ajuda, por favor:

>> To export the association label between two different objects in HubSpot using the HubSpot API, you’ll need to make use of the “association label” action to retrieve the label associated with the specified association type ID. Here’s how you can modify your code to achieve this:

```python
import requests

# Define the API endpoint and your API key
url = “https://api.hubspot.com/crm/v3/objects/tickets/export
api_key = “YOUR_API_KEY_HERE”

# Define the association type ID
association_type_id = 28

# Define the payload for the export request
payload = {
“format”: “xlsx”,
“objectType”: “TICKETS”,
“associationTypeId”: association_type_id,
“objectProperties”: [
‘subject’,
‘hs_pipeline’,
‘hs_pipeline_stage’,
‘createdate’,
‘hs_lastmodifieddate’,
]
}

# Define headers with API key
headers = {
“Authorization”: f"Bearer {api_key}",
“Accept”: “application/json”,
“Content-Type”: “application/json”
}

# Make the export request
response = requests.post(url, headers=headers, json=payload)

# Check if the request was successful
if response.status_code == 200:
# Export request successful, retrieve the association label
association_label = response.json().get(“associationLabel”)
print(“Association Label:”, association_label)
else:
# Request failed, print error message
print(“Error:”, response.status_code, response.text)
```

In this code:

  • Replace `“YOUR_API_KEY_HERE”` with your actual HubSpot API key.
  • Set the `association_type_id` variable to the appropriate association type ID you want to export the label for.
  • The export request is made to the HubSpot CRM API endpoint for exporting tickets with the specified association type ID.
  • Upon a successful request (status code 200), the association label is retrieved from the response JSON and printed.
  • If the request fails, an error message with the status code and response text is printed.

This code should allow you to export the association label between two different objects in HubSpot using the specified association type ID.

Espero ter ajudado.

Olá @Brenner,

Bem testei o código acima e infelizmente não funcionou, vou tentar explicar de uma melhor forma o que eu quero fazer com a API do Hub:

Bem, quero pegar a associação e imprimi-la desta maneira, como se fosse feita manualmente na hora de exportar o CRM do Hub, ela deveria ficar assim na planilha:

Imprimindo a coluna no Hub.

Segue abaixo o Codigo ainda em desenvolvimento:

import requests

import os

import time

association_type_id = 1

# Configurações de exportação para diferentes tipos de objetos

export_configs = [

{

    "objectType": "#COMPANY",

    "objectProperties": \[

       'hs\_object\_id',

        'name',

        'cnpj\_string',

        'id\_tba',

        'createdate',

        'hs\_lastmodifieddate',

        'agencia\_logbank',

        'conta\_logbank',

        'status\_conta\_logbank',

        'preenchimento\_data\_conta\_logbank'

    ]

},

{

    "objectType": "#TICKTES",

    "associationCategory": "USER\_DEFINED",

    "associatedObjectType": 28,

    "objectProperties": \[

        'subject',

        'hs\_pipeline',

        'hs\_pipeline\_stage',

        'createdate',

        'hs\_lastmodifieddate',

        'solicitante',

        'cpf\_ou\_cnpj\_do\_beneficiario',

        'valor\_operacao',

        'numero\_de\_parcelas',

        'valor\_da\_parcela',

        'qual\_o\_seu\_relacionamento\_com\_a\_tambasa\_atacadistas\_',

        'tempo\_de\_relacionamento\_\_em\_meses\_'

    ]

},

{

    "objectType": "CONTACT",

    "associationTypeId": association\_type\_id,

    "objectProperties": \[

        'hs\_object\_id',

        'firstname',

        'lastname',

        'cpf',

        'cnpj',

        'ida\_tba',

        'createdate',

        'lastmodifieddate',

        'agencia\_logbank',

        'conta\_logbank',

        'status\_conta\_logbank',

        'preenchimento\_data\_conta\_logbank',

        'email',

        "association\_label"

    ]

}

]

url = “https://api.hubapi.com/crm/v3/exports/export/async

headers = {

"Authorization": "XXXXXXXX",

"Accept": "application/json",

"Content-Type": "application/json"

}

def start_export(config​:disappointed_face:

data = {

    "exportType": "VIEW",

    "exportName": f"Exportação Automática de {config\['objectType']}",

    "format": "xlsx",

    "language": "PT\_BR",

    "objectType": config\["objectType"],

    "objectProperties": config\["objectProperties"],

}

association\_label = response.json().get("associationLabel")

print("Association Label:", association\_label)

response = requests.post(url, headers=headers, json=data)

if response.status\_code in (200, 201, 202😞

    response\_data = response.json()

    export\_id = response\_data.get("id")

    print(f"Exportação para {config\['objectType']} iniciada com sucesso. ID: {export\_id}")

    return export\_id

else:

    print(f"Erro ao iniciar a exportação para {config\['objectType']}: {response.status\_code}, {response.text}")

    return None

def check_download(export_id, config​:disappointed_face:

status\_url = f"https://api.hubapi.com/crm/v3/exports/export/async/tasks/{export\_id}/status"

while True:

    status\_response = requests.get(status\_url, headers=headers)

    if status\_response.status\_code in (200, 201, 202😞

        status\_data = status\_response.json()

        export\_status = status\_data.get("status")

        if export\_status == "COMPLETE":

            export\_url = status\_data.get("result", "")

            if export\_url:

                file\_response = requests.get(export\_url)

                if file\_response.status\_code in (200, 201, 202😞

                    directory = r"C:\Users\xxx\Desktop\Explore\_hub"

                    if not os.path.exists(directory):

                        os.makedirs(directory)

                    file\_path = os.path.join(directory, f"HubSpot\_{config\['objectType']}.xlsx")

                    with open(file\_path, 'wb') as file:

                        file.write(file\_response.content)

                    print(f"Arquivo baixado com sucesso e salvo em: {file\_path}")

                else:

                    print(f"Erro ao baixar o arquivo: {config\['objectType']}, {file\_response.status\_code}")

            else:

                print("URL de download não encontrada.")

            break

        else:

            print(f"Aguardando conclusão da exportação para {config\['objectType']}. Status: {export\_status}")

            time.sleep(30)

            if export\_status == "CANCELED":

                print(f"Exportação cancelada {config\['objectType']}. Status: {export\_status}")

                break

    else:

        print(f"Erro ao verificar o status da exportação para {config\['objectType']}: {status\_response.status\_code}")

        break

# Executar exportação para cada configuração

for config in export_configs:

export\_id = start\_export(config)

if export\_id:

    check\_download(export\_id, config)

O Codigo acima inicia a exportação dos CRM’s e verifica o status do mesmo, apos isso ele baixa o arquivos no diretorio desejado.

Olá @TSiilva , desculpa a demora.

Como ficou muito técnico, estou pedindo para um desenvolvedor me ajudar com isso, não sei se você ainda precisa dessa parte da solução, mas assim que eu conseguir o retorno dele, eu mando aqui.