Skip to content

martyzz1/python-intercom

Repository files navigation

python-intercom

PyPI VersionPyPI DownloadsTravis CI BuildCoverage Status

Python bindings for the Intercom API (https://api.intercom.io).

API Documentation.

Package Documentation.

Upgrading information

Version 2 of python-intercom is not backwards compatible with previous versions.

One change you will need to make as part of the upgrade is to set Intercom.app_api_key and not set Intercom.api_key.

Installation

pip install python-intercom 

Basic Usage

Configure your access credentials

Intercom.app_id="my_app_id"Intercom.app_api_key="my-super-crazy-api-key"

Resources

Resources this API supports:

https://api.intercom.io/users https://api.intercom.io/companies https://api.intercom.io/tags https://api.intercom.io/notes https://api.intercom.io/segments https://api.intercom.io/events https://api.intercom.io/conversations https://api.intercom.io/messages https://api.intercom.io/counts https://api.intercom.io/subscriptions 

Additionally, the library can handle incoming webhooks from Intercom and convert to intercom models.

Examples

Users

fromintercomimportUser# Find user by emailuser=User.find(email="[email protected]") # Find user by user_iduser=User.find(user_id="1") # Find user by iduser=User.find(id="1") # Create a useruser=User.create(email="[email protected]", name="Bob Smith") # Delete a userdeleted_user=User.find(id="1").delete() # Update custom_attributes for a useruser.custom_attributes["average_monthly_spend"] =1234.56user.save() # Perform incrementinguser.increment('karma') user.save() # Iterate over all usersforuserinUser.all(): ...

Admins

fromintercomimportAdmin# Iterate over all adminsforadmininAdmin.all(): ...

Companies

fromintercomimportCompanyfromintercomimportUser# Add a user to one or more companiesuser=User.find(email="[email protected]") user.companies= [{"company_id": 6, "name": "Intercom"},{"company_id": 9, "name": "Test Company"} ] user.save() # You can also pass custom attributes within a company as you do thisuser.companies= [{"id": 6, "name": "Intercom", "custom_attributes":{"referral_source": "Google" } } ] user.save() # Find a company by company_idcompany=Company.find(company_id="44") # Find a company by namecompany=Company.find(name="Some company") # Find a company by idcompany=Company.find(id="41e66f0313708347cb0000d0") # Update a companycompany.name='Updated company name'company.save() # Iterate over all companiesforcompanyinCompany.all(): ... # Get a list of users in a companycompany.users

Tags

fromintercomimportTag# Tag userstag=Tag.tag_users('blue', ["42ea2f1b93891f6a99000427"]) # Untag usersTag.untag_users('blue', ["42ea2f1b93891f6a99000427"]) # Iterate over all tagsfortaginTag.all(): ... # Iterate over all tags for userTag.find_all_for_user(id='53357ddc3c776629e0000029') Tag.find_all_for_user(email='[email protected]') Tag.find_all_for_user(user_id='3') # Tag companiestag=Tag.tag_companies('red', ["42ea2f1b93891f6a99000427"]) # Untag companiesTag.untag_companies('blue', ["42ea2f1b93891f6a99000427"]) # Iterate over all tags for companyTag.find_all_for_company(id='43357e2c3c77661e25000026') Tag.find_all_for_company(company_id='6')

Segments

fromintercomimportSegment# Find a segmentsegment=Segment.find(id=segment_id) # Update a segmentsegment.name='Updated name'segment.save() # Iterate over all segmentsforsegmentinSegment.all(): ...

Notes

# Find a note by idnote=Note.find(id=note) # Create a note for a usernote=Note.create( body="<p>Text for the note</p>", email='[email protected]') # Iterate over all notes for a user via their email addressfornoteinNote.find_all(email='[email protected]'): ... # Iterate over all notes for a user via their user_idfornoteinNote.find_all(user_id='123'): ...

Conversations

fromintercomimportConversation# FINDING CONVERSATIONS FOR AN ADMIN# Iterate over all conversations (open and closed) assigned to an adminforconvoinConversation.find_all(type='admin', id='7'): ... # Iterate over all open conversations assigned to an adminforconvoConversation.find_all(type='admin', id=7, open=True): ... # Iterate over closed conversations assigned to an adminforconvoConversation.find_all(type='admin', id=7, open=False): ... # Iterate over closed conversations for assigned an admin, before a certain# moment in timeforconvoinConversation.find_all( type='admin', id=7, open=False, before=1374844930): ... # FINDING CONVERSATIONS FOR A USER# Iterate over all conversations (read + unread, correct) with a user based on# the users emailforconvoinConversation.find_all(email='[email protected]',type='user'): ... # Iterate over through all conversations (read + unread) with a user based on# the users emailforconvoinConversation.find_all( email='[email protected]', type='user', unread=False): ... # Iterate over all unread conversations with a user based on the users emailforconvoinConversation.find_all( email='[email protected]', type='user', unread=true): ... # FINDING A SINGLE CONVERSATIONconversation=Conversation.find(id='1') # INTERACTING WITH THE PARTS OF A CONVERSATION# Getting the subject of a part (only applies to email-based conversations)conversation.rendered_message.subject# Get the part_type of the first partconversation.conversation_parts[0].part_type# Get the body of the second partconversation.conversation_parts[1].body# REPLYING TO CONVERSATIONS# User (identified by email) replies with a commentconversation.reply( type='user', email='[email protected]', message_type=comment', body='foo') # Admin (identified by email) replies with a commentconversation.reply( type='admin', email='[email protected]', message_type='comment', body='bar') # Admin (identified by id) opens a conversationconversation.open_conversation(admin_id=7) # Admin (identified by id) closes a conversationconversation.close_conversation(admin_id=7) # Admin (identified by id) assigns a conversation to an assigneeconversation.assign(assignee_id=8, admin_id=7) # MARKING A CONVERSATION AS READconversation.read=Trueconversation.save()

Counts

fromintercomimportCount# Get Conversation per Adminconversation_counts_for_each_admin=Count.conversation_counts_for_each_admin() forcountinconversation_counts_for_each_admin: print"Admin: %s (id: %s) Open: %s Closed: %s"% ( count.name, count.id, count.open, count.closed) # Get User Tag Count ObjectCount.user_counts_for_each_tag() # Get User Segment Count ObjectCount.user_counts_for_each_segment() # Get Company Segment Count ObjectCount.company_counts_for_each_segment() # Get Company Tag Count ObjectCount.company_counts_for_each_tag() # Get Company User Count ObjectCount.company_counts_for_each_user() # Get total count of companies, users, segments or tags across appCompany.count() User.count() Segment.count() Tag.count()

Full loading of and embedded entity

# Given a converation with a partial user, load the full user. This can be done for any entityconversation.user.load()

Sending messages

# InApp message from admin to userMessage.create(**{"message_type": "inapp", "body": "What's up :)", "from":{"type": "admin", "id": "1234" }, "to":{"type": "user", "id": "5678" } }) # Email message from admin to userMessage.create(**{"message_type": "email", "subject": "Hey there", "body": "What's up :)", "template": "plain", # or "personal","from":{"type": "admin", "id": "1234" }, "to":{"type": "user", "id": "536e564f316c83104c000020" } }) # Message from a userMessage.create(**{"from":{"type": "user", "id": "536e564f316c83104c000020" }, "body": "halp" })

Events

fromintercomimportEventEvent.create( event_name="invited-friend", created_at=time.mktime(), email=user.email, metadata={"invitee_email": "[email protected]", "invite_code": "ADDAFRIEND", "found_date": 12909364407 } )

Metadata Objects support a few simple types that Intercom can present on your behalf

Event.create( event_name="placed-order", email=current_user.email, created_at=1403001013metadata={"order_date": time.mktime(), "stripe_invoice": 'inv_3434343434', "order_number":{"value": '3434-3434', "url": 'https://example.org/orders/3434-3434' }, "price":{"currency": 'usd', "amount": 2999 } } )

The metadata key values in the example are treated as follows-

  • order_date: a Date (key ends with '_date').
  • stripe_invoice: The identifier of the Stripe invoice (has a 'stripe_invoice' key)
  • order_number: a Rich Link (value contains 'url' and 'value' keys)
  • price: An Amount in US Dollars (value contains 'amount' and 'currency' keys)

Subscriptions

Subscribe to events in Intercom to receive webhooks.

fromintercomimportSubscription# create a subscriptionSubscription.create(url="http://example.com", topics=["user.created"]) # fetch a subscriptionSubscription.find(id="nsub_123456789") # list subscriptionsSubscription.all():

Webhooks

fromintercomimportNotification# create a payload from the notification hash (from json).payload=Intercom::Notification.new(notification_hash) payload.type# 'user.created'payload.model_type# Useruser=payload.model# Instance of User

Note that models generated from webhook notifications might differ slightly from models directly acquired via the API. If this presents a problem, calling payload.load will load the model from the API using the id field.

Errors

You do not need to deal with the HTTP response from an API call directly. If there is an unsuccessful response then an error that is a subclass of intercom.Error will be raised. If desired, you can get at the http_code of an Error via it's http_code method.

The list of different error subclasses are listed below. As they all inherit off IntercomError you can choose to except IntercomError or the more specific error subclass:

AuthenticationErrorServerErrorServiceUnavailableErrorResourceNotFoundBadGatewayErrorBadRequestErrorRateLimitExceededMultipleMatchingUsersErrorHttpErrorUnexpectedError

Rate Limiting

Calling Intercom.rate_limit_details returns a dict that contains details about your app's current rate limit.

Intercom.rate_limit_details#{'limit': 500, 'reset_at': datetime.datetime(2015, 3, 28, 13, 22), 'remaining': 497}

Running the Tests

Unit tests:

nosetests tests/unit

Integration tests:

INTERCOM_APP_ID=xxx INTERCOM_APP_API_KEY=xxx nosetests tests/integration

About

Python wrapper for the Intercom API.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python100.0%