Beispiel #1
0
def test_create_hubspot3_client():
    """attempts to create a hubspot3 client"""
    with pytest.raises(HubspotNoConfig):
        hubspot = Hubspot3()
    with pytest.raises(HubspotBadConfig):
        hubspot = Hubspot3(api_key=TEST_KEY, access_token=TEST_KEY)

    hubspot = Hubspot3(api_key=TEST_KEY)
    assert hubspot

    assert hubspot.usage_limits
    assert isinstance(hubspot.me, dict)
    assert isinstance(hubspot.usage_limits, Hubspot3UsageLimits)
    assert isinstance(hubspot._base, BaseClient)
    assert isinstance(hubspot.blog, BlogClient)
    assert isinstance(hubspot.broadcast, BroadcastClient)
    assert isinstance(hubspot.companies, CompaniesClient)
    assert isinstance(hubspot.contact_lists, ContactListsClient)
    assert isinstance(hubspot.contacts, ContactsClient)
    assert isinstance(hubspot.crm_associations, CRMAssociationsClient)
    assert isinstance(hubspot.crm_pipelines, PipelinesClient)
    assert isinstance(hubspot.deals, DealsClient)
    assert isinstance(hubspot.engagements, EngagementsClient)
    assert isinstance(hubspot.form_submissions, FormSubmissionClient)
    assert isinstance(hubspot.forms, FormsClient)
    assert isinstance(hubspot.keywords, KeywordsClient)
    assert isinstance(hubspot.leads, LeadsClient)
    assert isinstance(hubspot.owners, OwnersClient)
    assert isinstance(hubspot.prospects, ProspectsClient)
    assert isinstance(hubspot.settings, SettingsClient)
Beispiel #2
0
    def __init__(self, **kwargs):
        # If no arguments were supplied at all, the desired outcome is likely
        # the list of operations/clients. Therefore disable authentication to
        # stop the Hubspot3 initializer from raising an exception since there
        # is neither an API key nor an access token.
        if not kwargs:
            kwargs["disable_auth"] = True

        # If a config file was specified, read its settings and merge the CLI
        # options into them.
        config_file = kwargs.pop("config", None)
        if config_file is not None:
            config = get_config_from_file(config_file)
            kwargs = dict(config, **kwargs)

        # Initialize the main client, discover all sub-clients and set them as
        # attributes on this wrapper so Fire can discover them.
        hubspot3 = Hubspot3(**kwargs)
        self._clients = self._discover_clients(hubspot3)
        for attr, client in self._clients.items():
            setattr(self, attr, ClientCLIWrapper(client))
def main():
    hubspot_client = Hubspot3(api_key=os.getenv('HUBSPOT_API_KEY'))
    service_account_info = json.loads(os.getenv('GDRIVE_SERVICE_ACCOUNT'))
    google_credentials = service_account.Credentials.from_service_account_info(
        service_account_info, scopes=['https://www.googleapis.com/auth/drive'])
    authed_session = AuthorizedSession(google_credentials)

    contacts = hubspot_client.contacts.get_all(
        extra_properties=['hs_persona', 'country'])
    download(contacts, 'contacts.json')
    download(hubspot_client.companies.get_all(), 'companies.json')
    download(hubspot_client.engagements.get_all(), 'engagements.json')
    download(hubspot_client.tickets.get_all(), 'tickets.json')

    convertToCSV('contacts.json')
    convertToCSV('companies.json')

    compress('engagements.json')

    folderId = createFolder(authed_session)
    upload('contacts.csv', authed_session, folderId, 'text/csv')
    upload('companies.csv', authed_session, folderId, 'text/csv')
    upload('engagements.zip', authed_session, folderId, 'application/zip')
    upload('tickets.json', authed_session, folderId, 'application/json')
Beispiel #4
0
from hubspot3 import Hubspot3
import os
from dotenv import load_dotenv
load_dotenv()

### HubSpot ###
API_KEY = os.getenv("API_KEY")
client = Hubspot3(api_key=API_KEY)

firstname = "Testy"
lastname = "Buster"
email = "*****@*****.**"
phone = "873-273-8734"

data = {
    "properties": [{
        "property": "firstname",
        "value": f"{firstname}"
    }, {
        "property": "lastname",
        "value": f"{lastname}"
    }, {
        "property": "email",
        "value": f"{email}"
    }, {
        "property": "phone",
        "value": f"{phone}"
    }]
}
# call this on a button press from a flask app
# contact = client.contacts.create(data=data)
Beispiel #5
0
class JsonHubspot():
    API_KEY = cred.HUBSPOT_API_KEY
    url_base_campaign = cred.HUBSPOT_URL_BASE_CAMPAIGN
    url_base_events = cred.HUBSPOT_URL_BASE_EVENTS
    url_base_marketing_emails = cred.HUBSPOT_URL_BASE_MKT_EMAILS
    events_limit = 1000
    client = Hubspot3(api_key=API_KEY)

    def __init__(self):
        self.API_KEY = cred.HUBSPOT_API_KEY
        self.url_base_campaign = cred.HUBSPOT_URL_BASE_CAMPAIGN
        self.url_base_events = cred.HUBSPOT_URL_BASE_EVENTS
        self.url_base_marketing_emails = cred.HUBSPOT_URL_BASE_MKT_EMAILS

    def getCampaigns(self):
        json_url = urlopen(self.url_json)
        data = json.loads(json_url.read())
        return data['campaigns']

    def getCampaign(self, id_campaign):
        url_campaign = self.url_base_campaign + \
                       str(id_campaign) + \
                       '?hapikey=' + self.API_KEY
        campaign_json_url = urlopen(url_campaign)
        datasetCampaign = pd.read_json(campaign_json_url)
        return datasetCampaign

    def getCampaignEvents(self, id_campaign, time=None):

        continue_while = True
        url_event_base = self.url_base_events + \
                         '?hapikey=' + self.API_KEY + \
                         '&campaignId=' + str(id_campaign) + \
                         '&limit=' + str(self.events_limit)
        if time:
            url_event_base = url_event_base + '&startTimestamp=' + str(time)

        finalDataset = pd.DataFrame(dict())
        records = 0
        while continue_while:
            if records == 0:
                url_event = url_event_base
            else:
                url_event = url_event_base + '&offset=' + datasetEvent[
                    'offset'][0]
            try:
                event_json_url = urlopen(url_event)
                datasetEvent = pd.read_json(event_json_url)
            except HTTPError as e:
                return finalDataset
            records = records + len(datasetEvent)
            if records == 0:
                return finalDataset
            finalDataset = finalDataset.append(self.eventsToDict(datasetEvent))
            continue_while = datasetEvent['hasMore'][0]
        new_dataset = pd.DataFrame(dict())
        # print(finalDataset)
        if len(finalDataset) > 0:
            for field in cred.HUBSPOT_FIEDS:
                # print(finalDataset[field])
                new_dataset[field] = finalDataset[field]
        # print(new_dataset)
        return new_dataset

    def getMarketingEmails(self):
        url_event = self.url_base_marketing_emails + '?hapikey=' + self.API_KEY + '&limit=' + str(
            self.events_limit)
        event_json_url = urlopen(url_event)
        datasetEvent = pd.read_json(event_json_url)
        return datasetEvent['objects']

    def eventsToDict(self, events):
        index = 1
        rows = dict()
        try:
            for row in events['events']:
                row_filtered = dict()
                row_filtered['created'] = row['created']
                row_filtered['id'] = row['id']
                row_filtered['recipient'] = row['recipient']
                row_filtered['type'] = row['type']
                row_filtered['emailCampaignId'] = row['emailCampaignId']
                rows[index] = row_filtered
                index += 1
        except KeyError as e:
            pass
        return pd.DataFrame(rows).transpose()

    def campaignsToDict(self, emailMarketing):
        index = 1
        rows = dict()
        for row in emailMarketing:
            row_filtered = dict()
            row_filtered['ab'] = row['ab']
            row_filtered['analyticsPageType'] = row['analyticsPageType']
            row_filtered['created'] = row['created']
            row_filtered['fromName'] = row['fromName']
            row_filtered['name'] = row['name'].replace('✈', '')
            row_filtered['id'] = row['id']
            # row_filtered = {your_key: row[your_key] for your_key in your_keys}
            try:
                row_filtered['campaign'] = row['campaign']
            except KeyError as e:
                row_filtered['campaign'] = ''
            try:
                row_filtered['campaignName'] = row['campaignName']
            except KeyError as e:
                row_filtered['campaignName'] = ''

            for EmailCampaignId in row['allEmailCampaignIds']:
                row_filtered2 = row_filtered.copy()
                row_filtered2['EmailCampaignId'] = EmailCampaignId
                rows[index] = row_filtered2
                index += 1
        return pd.DataFrame(rows)