def main(): parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='Config file') args = parser.parse_args() global config if args.config: with open(args.config) as input: config = json.load(input) else: config = {} if not config.get('disable_collection', False): logger.info('Sending version information to stitchdata.com. ' + 'To disable sending anonymous usage data, set ' + 'the config parameter "disable_collection" to true') threading.Thread(target=send_usage_stats).start() global intercom intercom = Client(personal_access_token=config.get('access_token')) input = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8') state = persist_users(input) emit_state(state) logger.debug("Exiting normally")
def it_returns_a_collection_proxy_for_all_without_making_any_requests( self): # noqa client = Client() # prove a call to send_request_to_path will raise an error with assert_raises(AssertionError): send_request() all = client.admins.all() self.assertIsInstance(all, CollectionProxy)
def setUp(self): # noqa self.client = Client() now = time.mktime(datetime.utcnow().timetuple()) self.user = User(email="*****@*****.**", user_id="12345", created_at=now, name="Jim Bob") self.created_time = now - 300
def __init__(self, instance, data={}, parent=None): JSConfigClient.__init__(self, instance=instance, data=data, parent=parent, template=TEMPLATE) c = self.config.data self.token = c['token'] self.api = Client(personal_access_token=self.token)
def _setup_intercom_client(): try: token = os.environ["CJW_INTERCOM_ACCESS_TOKEN"] return Client(personal_access_token=token) except KeyError: return NullIntercomClient() except Exception as e: logger.info("Error creating Intercom client: " + str(e)) return NullIntercomClient()
def _setup_intercom_client(): try: token = os.environ['CJW_INTERCOM_ACCESS_TOKEN'] return Client(personal_access_token=token) except KeyError: return NullIntercomClient() except Exception as e: log_message('Error creating Intercom client: ' + str(e)) return NullIntercomClient()
def createUser(result): ''' This function connects to intercom Client instance. Creates users. :param result: list of lists which stores output of select query ''' intercom = Client(personal_access_token='my_personal_access_token') for row in result: id = row[0] name = row[1] email = row[2] intercom.users.create(user_id=id, email=email, name=name)
def get_intercom_data(): client = Client(personal_access_token=intercom_token) opts = {'open': True, 'state': 'open'} feedback_counter = 0 conversations = client.conversations.find_all(**opts) current_time = datetime.now(timezone.utc) user_class = "<class 'intercom.utils.User'>" for conversation in conversations: if conversation.assignee.id != billing_user and conversation.assignee.id != crossbrowsertesting_user and conversation.assignee.id != customer_success_user and conversation.assignee.id != security_user and conversation.assignee.id != technical_success_user and conversation.assignee.id != the_crossbrowsertesting_team_user and conversation.assignee.id != cbt_team_user and conversation.assignee.id != jl_user and conversation.assignee.id != nb_user and conversation.assignee.id != rl_user and conversation.assignee.id != za_user and conversation.assignee.id != sh_user and conversation.assignee.id != dg_user and conversation.assignee.id != jt_user: full_conversation = client.conversations.find(id=conversation.id) parts = sorted(full_conversation.conversation_parts, key=lambda p: p.updated_at) if (len(parts) > 0): last_message = parts[-1] diff = current_time - last_message.updated_at if (diff.total_seconds() > 1800 and str(type(last_message.author)) == user_class): feedback_counter += 1 print(conversation.id) else: diff = current_time - full_conversation.created_at if (diff.total_seconds() > 1800): feedback_counter += 1 print(conversation.id) #oauth_headers = {'Authorization': 'Bearer ' + intercom_token} # oauth_headers['Accept'] = 'application/json' # feedback_counter = 0 # current_time = datetime.now(timezone.utc) # make a request for all open conversations # r = requests.get('https://api.intercom.io/conversations?state=open',headers=oauth_headers) # log('status code from request to intercom', r.status_code) # if r.status_code == 200: # log('JSON response from intercom', 'hello') # for each conversation, if the admin_id is feedback, we'll increment # for convo in r.json()['conversations']: # might not be the best pattern here. The "feedback admin_id" # appears to stay constant, but it will be good to check this in the future. #if not Shane, Zach, Nick, Dan, Joan and the waiting since time is less than 4000000000 seconds greater than the created time. # "The times are timestamps and a response from an admin makes the last response is from a user more than 30 minutes ago # user_class = "<class 'intercom.utils.User'>" # if convo['assignee']['id'] != billing_user and convo['assignee']['id'] != crossbrowsertesting_user and convo['assignee']['id'] != customer_success_user and convo['assignee']['id'] != security_user and convo['assignee']['id'] != technical_success_user and convo['assignee']['id'] != the_crossbrowsertesting_team_user and convo['assignee']['id'] != cbt_team_user and convo['assignee']['id'] != jl_user and convo['assignee']['id'] != nb_user and convo['assignee']['id']!= rl_user and convo['assignee']['id'] != za_user and convo['assignee']['id'] != sh_user and convo['assignee']['id'] != dg_user and diff.total_seconds() > 1800 and str(type(last_message.author)) ==user_class:#convo['waiting_since'] < convo['created_at'] + 4000000000: # feedback_counter += 1 # log(convo['id']) return feedback_counter
def get_conn(self): """ Initialize a python-intercom instance. """ if self.intercom: return self.intercom self.connection = self.get_connection(self.conn_id) self.extras = self.connection.extra_dejson intercom = Client( personal_access_token=self.extras['personal_access_token']) self.intercom = intercom return intercom
def setUp(self): # noqa self.client = Client() created_at = datetime.utcnow() params = { 'email': '*****@*****.**', 'user_id': 'i-1224242', 'custom_attributes': { 'mad': 123, 'another': 432, 'other': time.mktime(created_at.timetuple()), 'thing': 'yay' } } self.user = User(**params)
def open(self): if self.client: return self.client = Client(app_id=self.app_id, api_key=self.api_key) try: admin_list = self.client.admins.all() except IntercomError as err: if not self.fail_silently: raise logger.exception(err.message) self.admins = {} for admin in admin_list: admin_dict = admin.to_dict() self.admins[admin_dict['email']] = admin_dict
def __init__(self, cfis): self.settings = cfis self.customer = cfis.customer self.last_requested_at = cfis.last_requested_at or datetime.min.replace( tzinfo=pytz.UTC ) self.api_key = cfis.api_key self.source = cfis.importer self.feedback_tag_name = cfis.feedback_tag_name if self.feedback_tag_name: self.feedback_hashtag = f"#{self.feedback_tag_name}" else: self.feedback_hashtag = "" self.client = Client(personal_access_token=cfis.api_key) self.have_used_scroll = False
def solution_by_client( ): # for this function, using the python intercom module # since I cannot test this, please look at this as pseudo code # 1. connect to the mySQL DB of Monument Labs cnx = mysql.connector.connect(user='******', password='******', host='localhost', database='MonumentLabsDB') # 2. query the db cursor = cnx.cursor() query = ("SELECT id, name, email FROM user ") cursor.execute(query) rows = cursor.fetchall() # 3. load the table to construct list of user element rowarray_list = [] for row in rows: t = (row.id, row.name, row.email) rowarray_list.append(t) ''' rowarray_list [ [ 1123, "John Doh", "*****@*****.**" ], ... ''' cnx.close( ) # disconnect from db, everything about user recorded in a list of list # 5. connect to intercom via python-intercom module... intercom = Client(personal_access_token='my_personal_access_token') # for access token, reference: https://developers.intercom.com/docs/personal-access-tokens # 6. looping through the list based on the Monument labs "user" table # e.g: rowarray_list[1][0] = id, rowarray_list[1][1] = name, rowarray_list[1][2] = email for element in rowarray_list: intercom.users.create(id=element[0], name=element[1], email=element[2]) # since table already specify not NULL, I dont need to worry about null value # ref: https://developers.intercom.com/reference#user-model return True
def setUp(self): # noqa self.client = Client() self.job = { "app_id": "app_id", "id": "super_awesome_job", "created_at": 1446033421, "completed_at": 1446048736, "closing_at": 1446034321, "updated_at": 1446048736, "name": "api_bulk_job", "state": "completed", "links": { "error": "https://api.intercom.io/jobs/super_awesome_job/error", "self": "https://api.intercom.io/jobs/super_awesome_job" }, "tasks": [{ "id": "super_awesome_task", "item_count": 2, "created_at": 1446033421, "started_at": 1446033709, "completed_at": 1446033709, "state": "completed" }] } self.error_feed = { "app_id": "app_id", "job_id": "super_awesome_job", "pages": {}, "items": [] }
def setUp(self): # noqa self.client = Client() self.job = { "app_id": "app_id", "id": "super_awesome_job", "created_at": 1446033421, "completed_at": 1446048736, "closing_at": 1446034321, "updated_at": 1446048736, "name": "api_bulk_job", "state": "completed", "links": { "error": "https://api.intercom.io/jobs/super_awesome_job/error", "self": "https://api.intercom.io/jobs/super_awesome_job" }, "tasks": [{ "id": "super_awesome_task", "item_count": 2, "created_at": 1446033421, "started_at": 1446033709, "completed_at": 1446033709, "state": "completed" }] } self.bulk_request = { "items": [{ "method": "post", "data_type": "event", "data": { "event_name": "ordered-item", "created_at": 1438944980, "user_id": "314159", "metadata": { "order_date": 1438944980, "stripe_invoice": "inv_3434343434" } } }, { "method": "post", "data_type": "event", "data": { "event_name": "invited-friend", "created_at": 1438944979, "user_id": "314159", "metadata": { "invitee_email": "*****@*****.**", "invite_code": "ADDAFRIEND" } } }] } self.events = [{ "event_name": "ordered-item", "created_at": 1438944980, "user_id": "314159", "metadata": { "order_date": 1438944980, "stripe_invoice": "inv_3434343434" } }, { "event_name": "invited-friend", "created_at": 1438944979, "user_id": "314159", "metadata": { "invitee_email": "*****@*****.**", "invite_code": "ADDAFRIEND" } }]
class UserTest(unittest.TestCase): def setUp(self): self.client = Client() @istest def it_to_dict_itself(self): created_at = datetime.utcnow() user = User( email="*****@*****.**", user_id="12345", created_at=created_at, name="Jim Bob") as_dict = user.to_dict() eq_(as_dict["email"], "*****@*****.**") eq_(as_dict["user_id"], "12345") eq_(as_dict["created_at"], calendar.timegm(created_at.utctimetuple())) eq_(as_dict["name"], "Jim Bob") @istest def it_presents_created_at_and_last_impression_at_as_datetime(self): now = datetime.utcnow() now_ts = calendar.timegm(now.utctimetuple()) user = User.from_api( {'created_at': now_ts, 'last_impression_at': now_ts}) self.assertIsInstance(user.created_at, datetime) eq_(now.strftime('%c'), user.created_at.strftime('%c')) self.assertIsInstance(user.last_impression_at, datetime) eq_(now.strftime('%c'), user.last_impression_at.strftime('%c')) @istest def it_throws_an_attribute_error_on_trying_to_access_an_attribute_that_has_not_been_set(self): # noqa with assert_raises(AttributeError): user = User() user.foo_property @istest def it_presents_a_complete_user_record_correctly(self): user = User.from_api(get_user()) eq_('id-from-customers-app', user.user_id) eq_('*****@*****.**', user.email) eq_('Joe Schmoe', user.name) eq_('the-app-id', user.app_id) eq_(123, user.session_count) eq_(1401970114, calendar.timegm(user.created_at.utctimetuple())) eq_(1393613864, calendar.timegm(user.remote_created_at.utctimetuple())) eq_(1401970114, calendar.timegm(user.updated_at.utctimetuple())) Avatar = define_lightweight_class('avatar', 'Avatar') # noqa Company = define_lightweight_class('company', 'Company') # noqa SocialProfile = define_lightweight_class('social_profile', 'SocialProfile') # noqa LocationData = define_lightweight_class('locaion_data', 'LocationData') # noqa self.assertIsInstance(user.avatar.__class__, Avatar.__class__) img_url = 'https://graph.facebook.com/1/picture?width=24&height=24' eq_(img_url, user.avatar.image_url) self.assertIsInstance(user.companies, list) eq_(1, len(user.companies)) self.assertIsInstance(user.companies[0].__class__, Company.__class__) eq_('123', user.companies[0].company_id) eq_('bbbbbbbbbbbbbbbbbbbbbbbb', user.companies[0].id) eq_('the-app-id', user.companies[0].app_id) eq_('Company 1', user.companies[0].name) eq_(1390936440, calendar.timegm( user.companies[0].remote_created_at.utctimetuple())) eq_(1401970114, calendar.timegm( user.companies[0].created_at.utctimetuple())) eq_(1401970114, calendar.timegm( user.companies[0].updated_at.utctimetuple())) eq_(1401970113, calendar.timegm( user.companies[0].last_request_at.utctimetuple())) eq_(0, user.companies[0].monthly_spend) eq_(0, user.companies[0].session_count) eq_(1, user.companies[0].user_count) eq_([], user.companies[0].tag_ids) self.assertIsInstance(user.custom_attributes, FlatStore) eq_('b', user.custom_attributes["a"]) eq_(2, user.custom_attributes["b"]) eq_(4, len(user.social_profiles)) twitter_account = user.social_profiles[0] self.assertIsInstance(twitter_account.__class__, SocialProfile.__class__) eq_('twitter', twitter_account.name) eq_('abc', twitter_account.username) eq_('http://twitter.com/abc', twitter_account.url) self.assertIsInstance(user.location_data.__class__, LocationData.__class__) eq_('Dublin', user.location_data.city_name) eq_('EU', user.location_data.continent_code) eq_('Ireland', user.location_data.country_name) eq_('90', user.location_data.latitude) eq_('10', user.location_data.longitude) eq_('IRL', user.location_data.country_code) ok_(user.unsubscribed_from_emails) eq_("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11", user.user_agent_data) # noqa @istest def it_allows_update_last_request_at(self): payload = { 'user_id': '1224242', 'update_last_request_at': True, 'custom_attributes': {} } with patch.object(Client, 'post', return_value=payload) as mock_method: self.client.users.create( user_id='1224242', update_last_request_at=True) mock_method.assert_called_once_with( '/users/', {'update_last_request_at': True, 'user_id': '1224242'}) @istest def it_allows_easy_setting_of_custom_data(self): now = datetime.utcnow() now_ts = calendar.timegm(now.utctimetuple()) user = User() user.custom_attributes["mad"] = 123 user.custom_attributes["other"] = now_ts user.custom_attributes["thing"] = "yay" attrs = {"mad": 123, "other": now_ts, "thing": "yay"} eq_(user.to_dict()["custom_attributes"], attrs) @istest def it_allows_easy_setting_of_multiple_companies(self): user = User() companies = [ {"name": "Intercom", "company_id": "6"}, {"name": "Test", "company_id": "9"}, ] user.companies = companies eq_(user.to_dict()["companies"], companies) @istest def it_rejects_nested_data_structures_in_custom_attributes(self): user = User() with assert_raises(ValueError): user.custom_attributes["thing"] = [1] with assert_raises(ValueError): user.custom_attributes["thing"] = {1: 2} with assert_raises(ValueError): user.custom_attributes = {1: {2: 3}} user = User.from_api(get_user()) with assert_raises(ValueError): user.custom_attributes["thing"] = [1] @istest def it_fetches_a_user(self): with patch.object(Client, 'get', return_value=get_user()) as mock_method: # noqa user = self.client.users.find(email='*****@*****.**') eq_(user.email, '*****@*****.**') eq_(user.name, 'Joe Schmoe') mock_method.assert_called_once_with( '/users', {'email': '*****@*****.**'}) # noqa @istest def it_gets_users_by_tag(self): with patch.object(Client, 'get', return_value=page_of_users(False)): users = self.client.users.by_tag(124) for user in users: ok_(hasattr(user, 'avatar')) @istest def it_saves_a_user_always_sends_custom_attributes(self): body = { 'email': '*****@*****.**', 'user_id': 'i-1224242', 'custom_attributes': {} } with patch.object(Client, 'post', return_value=body) as mock_method: user = User(email="*****@*****.**", user_id="i-1224242") self.client.users.save(user) eq_(user.email, '*****@*****.**') eq_(user.custom_attributes, {}) mock_method.assert_called_once_with( '/users', {'email': "*****@*****.**", 'user_id': "i-1224242", 'custom_attributes': {}}) @istest def it_saves_a_user_with_a_company(self): body = { 'email': '*****@*****.**', 'user_id': 'i-1224242', 'companies': [{ 'company_id': 6, 'name': 'Intercom' }] } with patch.object(Client, 'post', return_value=body) as mock_method: user = User( email="*****@*****.**", user_id="i-1224242", company={'company_id': 6, 'name': 'Intercom'}) self.client.users.save(user) eq_(user.email, '*****@*****.**') eq_(len(user.companies), 1) mock_method.assert_called_once_with( '/users', {'email': "*****@*****.**", 'user_id': "i-1224242", 'company': {'company_id': 6, 'name': 'Intercom'}, 'custom_attributes': {}}) @istest def it_saves_a_user_with_companies(self): body = { 'email': '*****@*****.**', 'user_id': 'i-1224242', 'companies': [{ 'company_id': 6, 'name': 'Intercom' }] } with patch.object(Client, 'post', return_value=body) as mock_method: user = User( email="*****@*****.**", user_id="i-1224242", companies=[{'company_id': 6, 'name': 'Intercom'}]) self.client.users.save(user) eq_(user.email, '*****@*****.**') eq_(len(user.companies), 1) mock_method.assert_called_once_with( '/users', {'email': "*****@*****.**", 'user_id': "i-1224242", 'companies': [{'company_id': 6, 'name': 'Intercom'}], 'custom_attributes': {}}) @istest def it_can_save_a_user_with_a_none_email(self): user = User( email=None, user_id="i-1224242", companies=[{'company_id': 6, 'name': 'Intercom'}]) body = { 'custom_attributes': {}, 'email': None, 'user_id': 'i-1224242', 'companies': [{ 'company_id': 6, 'name': 'Intercom' }] } with patch.object(Client, 'post', return_value=body) as mock_method: self.client.users.save(user) ok_(user.email is None) eq_(user.user_id, 'i-1224242') mock_method.assert_called_once_with( '/users', {'email': None, 'user_id': "i-1224242", 'companies': [{'company_id': 6, 'name': 'Intercom'}], 'custom_attributes': {}}) @istest def it_deletes_a_user(self): user = User(id="1") with patch.object(Client, 'delete', return_value={}) as mock_method: user = self.client.users.delete(user) eq_(user.id, "1") mock_method.assert_called_once_with('/users/1', {}) @istest def it_can_use_user_create_for_convenience(self): payload = { 'email': '*****@*****.**', 'user_id': 'i-1224242', 'custom_attributes': {} } with patch.object(Client, 'post', return_value=payload) as mock_method: # noqa user = self.client.users.create(email="*****@*****.**", user_id="i-1224242") # noqa eq_(payload, user.to_dict()) mock_method.assert_called_once_with( '/users/', {'email': "*****@*****.**", 'user_id': "i-1224242"}) # noqa @istest def it_updates_the_user_with_attributes_set_by_the_server(self): payload = { 'email': '*****@*****.**', 'user_id': 'i-1224242', 'custom_attributes': {}, 'session_count': 4 } with patch.object(Client, 'post', return_value=payload) as mock_method: # noqa user = self.client.users.create(email="*****@*****.**", user_id="i-1224242") # noqa eq_(payload, user.to_dict()) mock_method.assert_called_once_with( '/users/', {'email': "*****@*****.**", 'user_id': "i-1224242"}) # noqa @istest def it_allows_setting_dates_to_none_without_converting_them_to_0(self): payload = { 'email': '*****@*****.**', 'custom_attributes': {}, 'remote_created_at': None } with patch.object(Client, 'post', return_value=payload) as mock_method: user = self.client.users.create(email="*****@*****.**", remote_created_at=None) # noqa ok_(user.remote_created_at is None) mock_method.assert_called_once_with('/users/', {'email': "*****@*****.**", 'remote_created_at': None}) # noqa @istest def it_gets_sets_rw_keys(self): created_at = datetime.utcnow() payload = { 'email': '*****@*****.**', 'user_id': 'abc123', 'name': 'Bob Smith', 'last_seen_ip': '1.2.3.4', 'last_seen_user_agent': 'ie6', 'created_at': calendar.timegm(created_at.utctimetuple()) } user = User(**payload) expected_keys = ['custom_attributes'] expected_keys.extend(list(payload.keys())) eq_(sorted(expected_keys), sorted(user.to_dict().keys())) for key in list(payload.keys()): eq_(payload[key], user.to_dict()[key]) @istest def it_will_allow_extra_attributes_in_response_from_api(self): user = User.from_api({'new_param': 'some value'}) eq_('some value', user.new_param) @istest def it_returns_a_collectionproxy_for_all_without_making_any_requests(self): with mock.patch('intercom.request.Request.send_request_to_path', new_callable=mock.NonCallableMock): # noqa res = self.client.users.all() self.assertIsInstance(res, CollectionProxy) @istest def it_raises_a_multiple_matching_users_error_when_receiving_a_conflict(self): # noqa payload = { 'type': 'error.list', 'errors': [ { 'code': 'conflict', 'message': 'Multiple existing users match this email address - must be more specific using user_id' # noqa } ] } # create bytes content content = json.dumps(payload).encode('utf-8') # create mock response resp = mock_response(content) with patch('requests.sessions.Session.request') as mock_method: mock_method.return_value = resp with assert_raises(MultipleMatchingUsersError): self.client.get('/users', {}) @istest def it_handles_accented_characters(self): # create a user dict with a name that contains accented characters payload = get_user(name='Jóe Schmö') # create bytes content content = json.dumps(payload).encode('utf-8') # create mock response resp = mock_response(content) with patch('requests.sessions.Session.request') as mock_method: mock_method.return_value = resp user = self.client.users.find(email='*****@*****.**') try: # Python 2 eq_(unicode('Jóe Schmö', 'utf-8'), user.name) except NameError: # Python 3 eq_('Jóe Schmö', user.name)
from intercom.client import Client import pyodbc import os def TakeCareOfQuote(input): return str(input).replace("'", "''") intercom = Client(personal_access_token=os.environ.get('intercom_personal_access_token')) # Find user by email # user = intercom.users.find(email="*****@*****.**") # print(user.id) converations = intercom.conversations.find_all() server = 'tcp:rnd-101' database = 'Conversations' username = '******' password = '******' cnxn = pyodbc.connect( 'DRIVER={ODBC Driver 13 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password) cursor = cnxn.cursor() i = 0 cursor.execute('delete from Conversations') cursor.execute('delete from ConversationParts') cnxn.commit()
import MySQLdb from intercom.client import Client #DROP TABLE IF EXISTS `user`; #CREATE TABLE `user` ( # `id` int(11) NOT NULL AUTO_INCREMENT, # `name` text NOT NULL, # `email` varchar(120) NOT NULL # PRIMARY KEY (`id`), # UNIQUE KEY `email` (`email`) #) ENGINE=InnoDB DEFAULT CHARSET=utf8; #based off table spec db = MySQLdb.connect(host=HOST, user=User, passwd=Passwd, db=DB) #placeholders intercom = Client(personal_access_token = input("Access Token here: ") #according to the api, intercom needs a personal access code cursor = db.cursor() #cursor allows for the data to be selected from the table spec for row in cursor.fetchall(): intercome.users.create(id=row[0], email=row[2], name=row[1]) #allows for user to be created, using API #redundant and repeating users not accounted for, #barebones implemenation
def _init(self, **kwargs): self.token = self.token_ self.api = Client(personal_access_token=self.token)
def get_client(): return Client(personal_access_token=settings.INTERCOM_ACCESS_TOKEN)
from django.conf import settings DT_MIXPANEL_FORWARD = getattr(settings, 'DT_MIXPANEL_FORWARD', False) DT_INTERCOM_FORWARD = getattr(settings, 'DT_INTERCOM_FORWARD', False) DT_LOCAL_SAVE = getattr(settings, 'DT_LOCAL_SAVE', True) DEBUG = getattr(settings, 'DEBUG') DT_MIXPANEL_TOKEN = getattr(settings, 'DT_MIXPANEL_TOKEN', False) if DT_INTERCOM_FORWARD: DT_INTERCOM_APPID = getattr(settings, 'DT_INTERCOM_APPID') DT_INTERCOM_TOKEN = getattr(settings, 'DT_INTERCOM_TOKEN') from intercom.errors import HttpError import intercom intercom.HttpError = HttpError from intercom.client import Client intercom_client = Client(personal_access_token=DT_INTERCOM_TOKEN) # Intercom.app_id = DT_INTERCOM_APPID # Intercom.api_key = DT_INTERCOM_TOKEN # Deprecated intercom client
# -*- coding: utf-8 -*- import os import unittest from intercom.client import Client from . import get_timestamp from . import get_or_create_user from . import delete_user intercom = Client(os.environ.get('INTERCOM_PERSONAL_ACCESS_TOKEN')) class UserTest(unittest.TestCase): @classmethod def setup_class(cls): nowstamp = get_timestamp() cls.user = get_or_create_user(intercom, nowstamp) cls.email = cls.user.email @classmethod def teardown_class(cls): delete_user(intercom, cls.user) def test_find_by_email(self): # Find user by email user = intercom.users.find(email=self.email) self.assertEqual(self.email, user.email) def test_find_by_user_id(self): # Find user by user id user = intercom.users.find(user_id=self.user.user_id)
class RequestTest(unittest.TestCase): def setUp(self): self.client = Client() @istest def it_raises_resource_not_found(self): resp = mock_response(None, status_code=404) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.ResourceNotFound): request = Request('GET', 'notes') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_raises_authentication_error_unauthorized(self): resp = mock_response(None, status_code=401) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.AuthenticationError): request = Request('GET', 'notes') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_raises_authentication_error_forbidden(self): resp = mock_response(None, status_code=403) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.AuthenticationError): request = Request('GET', 'notes') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_raises_server_error(self): resp = mock_response(None, status_code=500) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.ServerError): request = Request('GET', 'notes') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_raises_bad_gateway_error(self): resp = mock_response(None, status_code=502) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.BadGatewayError): request = Request('GET', 'notes') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_raises_service_unavailable_error(self): resp = mock_response(None, status_code=503) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.ServiceUnavailableError): request = Request('GET', 'notes') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_raises_an_unexpected_typed_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'hopper', 'message': 'The first compiler.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp try: self.client.get('/users', {}) self.fail('UnexpectedError not raised.') except (UnexpectedError) as err: ok_("The error of type 'hopper' is not recognized" in err.message) # noqa eq_(err.context['http_code'], 200) eq_(err.context['application_error_code'], 'hopper') @istest def it_raises_an_unexpected_untyped_error(self): payload = { 'type': 'error.list', 'errors': [ { 'message': 'UNIVAC' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp try: self.client.get('/users', {}) self.fail('UnexpectedError not raised.') except (UnexpectedError) as err: ok_("An unexpected error occured." in err.message) eq_(err.context['application_error_code'], None) @istest def it_raises_a_bad_request_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': None, 'message': 'email is required' } ] } for code in ['missing_parameter', 'parameter_invalid', 'bad_request']: payload['errors'][0]['type'] = code content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.BadRequestError): self.client.get('/users', {}) @istest def it_raises_an_authentication_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'unauthorized', 'message': 'Your name\'s not down.' } ] } for code in ['unauthorized', 'forbidden']: payload['errors'][0]['type'] = code content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.AuthenticationError): self.client.get('/users', {}) @istest def it_raises_resource_not_found_by_type(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'not_found', 'message': 'Waaaaally?' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.ResourceNotFound): self.client.get('/users', {}) @istest def it_raises_rate_limit_exceeded(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'rate_limit_exceeded', 'message': 'Fair use please.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.RateLimitExceeded): self.client.get('/users', {}) @istest def it_raises_a_service_unavailable_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'service_unavailable', 'message': 'Zzzzz.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.ServiceUnavailableError): self.client.get('/users', {}) @istest def it_raises_a_multiple_matching_users_error(self): payload = { 'type': 'error.list', 'errors': [ { 'type': 'conflict', 'message': 'Two many cooks.' } ] } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.MultipleMatchingUsersError): self.client.get('/users', {}) @istest def it_handles_no_error_type(self): payload = { 'errors': [ { 'code': 'unique_user_constraint', 'message': 'User already exists.' } ], 'request_id': '00000000-0000-0000-0000-000000000000', 'type': 'error.list' } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.MultipleMatchingUsersError): self.client.get('/users', {}) payload = { 'errors': [ { 'code': 'parameter_not_found', 'message': 'missing data parameter' } ], 'request_id': None, 'type': 'error.list' } content = json.dumps(payload).encode('utf-8') resp = mock_response(content) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(intercom.BadRequestError): self.client.get('/users', {}) @istest def it_handles_empty_responses(self): resp = mock_response('', status_code=202) with patch('requests.request') as mock_method: mock_method.return_value = resp request = Request('GET', 'events') request.send_request_to_path('', ('x', 'y'), resp) resp = mock_response(' ', status_code=202) with patch('requests.request') as mock_method: mock_method.return_value = resp request = Request('GET', 'events') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_handles_no_encoding(self): resp = mock_response( ' ', status_code=200, encoding=None, headers=None) resp.apparent_encoding = 'utf-8' with patch('requests.request') as mock_method: mock_method.return_value = resp request = Request('GET', 'events') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_needs_encoding_or_apparent_encoding(self): payload = '{}' if not hasattr(payload, 'decode'): # python 3 payload = payload.encode('utf-8') resp = mock_response( payload, status_code=200, encoding=None, headers=None) with patch('requests.request') as mock_method: mock_method.return_value = resp with assert_raises(TypeError): request = Request('GET', 'events') request.send_request_to_path('', ('x', 'y'), resp) @istest def it_allows_the_timeout_to_be_changed(self): from intercom.request import Request eq_(10, Request.timeout) Request.timeout = 3 eq_(3, Request.timeout)
def setUp(self): self.client = Client()
import pymysql from intercom.client import Client ''' Grab the data from the user_data table from monlab_db Database. Insert each record as new users in Intercom using Intercom's API ''' intercom = Client(personal_access_token='your_access_token') try: conn = pymysql.connect(user="******", password="******", host="localhost", database="monlab_db") curs = conn.cursor() sql = 'select * from user_data;' rowCount= curs.execute(sql) data = curs.fetchall() credentials = {} bulk_User = [] #getting each user data into a directory and appending that into the bulk_User list for row in data: credentials['user_id']= row[0] credentials['name']= str(row[1]) credentials['email']= str(row[2]) bulk_User.append(credentials) credentials = {} #doing a bulk insert/creation job intercom.users.submit_bulk_job(create_items=bulk_User)
def setUp(self): # noqa self.client = Client()
import os from intercom.client import Client import pickle import matplotlib.pyplot as plt import numpy as np import statistics from pt_utils.utils import send_email #import credentials object mp = Mixpanel(os.environ.get('MIXPANEL_KEY')) mp_user = Mixpanel(os.environ.get('MIXPANEL_KEY_USER')) api_creator_secret = os.getenv('MIXPANEL_CREATOR_KEY') api_user_secret = os.environ.get('MIXPANEL_USER_KEY') hubspot_key = os.environ.get('HUBSPOT_KEY') intercom_key = os.environ.get('INTERCOM_KEY') intercom = Client(personal_access_token=intercom_key) def creator_pull(): """ Pull app creators' info in Mixpanel. Parameters ---------- Global Variables ---------- api_creator_secret: str Client secret used to make calls to Mixpanel Creator Project.
# pandas and python-intercom packages need to be installed via pip import pandas from intercom.client import Client ### USER INPUT INTERCOM_ACCESS_TOKEN = 'dG9rOjQ2MmM2MzlkXzQwNzRfNGVkYl84YjYwXzkwZDVmNzcyMzcyMjoxOjA=' INPUT_FILE = 'emails.csv' OUTPUT_FILE = 'SocialProfiles-out.csv' EMAILS_HEADER = 'Emails' # intercom API extended access token intercom = Client(personal_access_token=INTERCOM_ACCESS_TOKEN) # create dataframe from input CSV which should be in the same directory and have column A listing email addresses with header 'Emails' df = pandas.DataFrame(pandas.read_csv(INPUT_FILE)) sites = [ ['Twitter', 'Twitter Username', [], 'Twitter URL', []], ['Facebook', 'Facebook Username', [], 'Facebook URL', []], ['LinkedIn', 'LinkedIn Username', [], 'LinkedIn URL', []], ['Klout', 'Klout Username', [], 'Klout URL', []], ['Vimeo', 'Vimeo Username', [], 'Vimeo URL', []], ['GooglePlus', 'Google Plus Username', [], 'Google Plus URL', []], ['Flickr', 'Flickr Username', [], 'Flickr URL', []], ['Github', 'GitHub Username', [], 'GitHub URL', []], ['Foursquare', 'FourSquare Username', [], 'FourSquare URL', []], ['YouTube', 'YouTube Username', [], 'YouTube URL', []], ['Myspace', 'MySpace Username', [], 'MySpace URL', []], ['Tumblr', 'Tumblr Username', [], 'Tumblr URL', []] ] others = ['Other Username', [], 'Other URL', [], 'Other Type', []] avatars = ['Avatar URL', []] titles = ['Job Title', []]
#!/usr/bin/python import mysql.connector from intercom.client import Client #Set variables for MySQL connections and Intercom API accesses hostname = 'localhost' username = '******' password = '******' database = 'DATABASE' #Open intercom API and connection to MySQL database intercom = Client(personal_access_token='my_access_token') scriptConnection = mysql.connector.connect(host=hostname, user=username, passwd=password, db=database) cur = scriptConnection.cursor() #Pull all users from the user table cur.execute("SELECT * FROM user") #Generate users from data pulled from database for row in cur: intercom.users.create(user_id=str(row[0]), email=row[2], name=row[1]) #Close database connection once all users are created scriptConnection.close()
from intercom.client import Client # Grab data from form at emailsa.ga/batch.html form = cgi.FieldStorage() # Get filename here fileitem = form['filename'] # Test if the file was uploaded if fileitem.filename: # open the uploaded file from files directory file = "../files/" + fileitem.filename open(file, 'wb').write(fileitem.file.read()) # intercom API extended access token intercom = Client(personal_access_token='#########################') # create dataframe from uploaded CSV - it should have emails in first column and no header is needed df = pandas.read_csv(file, header=None, usecols=[0], names=['Email Address']) # Create arrays for lookup/output data in order to separate by social media platform # 1st object is the lookup value for API call results, to separate by website # 2nd object is CSV column name for the username result, the 3rd is the actual result from API call # 3rd object is CSV column name for the URL result, the 4th is the actual result from API call sites = [['Twitter', 'Twitter Username', [], 'Twitter URL', []], ['Facebook', 'Facebook Username', [], 'Facebook URL', []], ['LinkedIn', 'LinkedIn Username', [], 'LinkedIn URL', []], ['Klout', 'Klout Username', [], 'Klout URL', []],
def connect_to_intercom(self): try: self.intercom = Client(personal_access_token=self.personal_access_token) except: print("Error connecting to Intercom")
def get_workspace_id(token): return Client(personal_access_token=token).contacts.all()[0].workspace_id