Example Intercom client

Home   »   Example Intercom client

class ResponseErrorException(Exception):
    def __init__(self, response, message='Response is not 200 OK'):
        self.response = response
        super().__init__(message)


class IntercomClient:
    def __list_all_contacts(self, contacts, starting_after=None):
        url = self.__base_url + '/contacts?page_size=150'
        if starting_after:
            url += f'&starting_after={starting_after}'

        try:
            response = self.__call_requests('get', url)
        except ResponseErrorException as e:
            raise ResponseErrorException(e.response, 'List all contacts error.')

        contacts += response['data']

        has_next_page = 'next' in response['pages']
        if has_next_page:
            starting_after = response['pages']['next']['starting_after']
            return self.__list_all_contacts(contacts, starting_after)
        else:
            return contacts

    def __list_all_companies(self, companies, scroll_param=None):
        url = self.__base_url + '/companies/scroll'
        if scroll_param:
            url += f'&scroll_param={scroll_param}'

        try:
            response = self.__call_requests('get', url)
        except ResponseErrorException as e:
            raise ResponseErrorException(e.response, 'List all companies error.')

        companies += response['data']

        has_next_page = response['data']
        if has_next_page:
            scroll_param = resposne['scroll_param']
            return self.__list_all_companies(companies, scroll_param)
        else:
            return companies


    def __call_requests(self, *args, **kwargs):
        # override headers from kwargs
        kwargs['headers'] = self.__get_headers()
        response = requests.request(*args, **kwargs)

        if response.status_code == status.HTTP_429_TOO_MANY_REQUESTS:
            self.__wait_until_reset_rate_limit(response.headers['X-RateLimit-Reset'])
            return self.__call_requests(*args, **kwargs)

        if response.ok:
            return response.json()
        else:
            raise ResponseErrorException(response)

Leave a Reply

Your email address will not be published. Required fields are marked *