Intercom Ruby SDK

Intercom Ruby SDK Examples

πŸ“˜

Installation and Configuration Steps

For information on how to install and configure the Intercom Ruby SDK please see the intercom-ruby github page. For general code examples please see below.

Configure your client

for more info on access tokens or OAuth please see here

# With an OAuth or Personal Access token:
intercom = Intercom::Client.new(token: 'my_token')

Users

Update, create and archive users

user = intercom.users.create(:email => "[email protected]", :name => "Bob Smith", :signed_up_at => Time.now.to_i)
user.custom_attributes["average_monthly_spend"] = 1234.56
intercom.users.save(user)
#Increment a cusomt attribute
user.increment('subscription_page')
intercom.users.save(user)
#Decrement it
user = intercom.users.find(:id => "56e1e5d4a40df1cc57000101")
intercom.users.delete(user)

Find users by different means

Now lets find the user we just created (note that your, email, user_id or id may be different to those used in the example below)

user = intercom.users.find(:email => "[email protected]")
user = intercom.users.find(:user_id => "1")
user = intercom.users.find(:id => "56e1e5d4a40df1cc57000101")

Iterate over users

There are different ways you can get access to your users, we show some of them below:

intercom.users.all.each {|user| puts %Q(#{user.email} - #{user.custom_attributes["average_monthly_spend"]}) }
intercom.users.all.map {|user| user.email }
intercom.users.find_all(type: 'users', page: 1, per_page: 10, 
  created_since: 2, order: :asc).to_a.each_with_index 
{|usr, i| puts "#{i+1}: #{usr.name}"};
intercom.users.find_all(type: 'users', page: 1, per_page: 10, 
  order: :asc).to_a.each_with_index 
{|usr, i| puts "#{i+1}: #{usr.name}"} #Max 50 per page

Iterating over larger user lists

If you have over 10,000 users then you will need to use the scroll function to list your users. Otherwise you will encounter a page limit with list all your users. You can use the scroll method to list all your users

intercom.users.scroll.each { |user| puts user.name}

Alternatively you can use the scroll.next method to get 100 users with each request. The result object then contains a records attributes that is an array of your user objects and it also contains a scroll_param which you can then use to request the next 100 users.

result = intercom.users.scroll.next
result.scroll_param
=> "0730e341-63ef-44da-ab9c-9113f886326d"
result = intercom.users.scroll.next("0730e341-63ef-44da-ab9c-9113f886326d");

❗️

Scroll Timeout

Note that the scroll parameter will time out after one minute and you will need to make a new request

Admins

Find and iterate through admins

intercom.admins.find(:id => admin_id)
intercom.admins.all.each {|admin| puts admin.email }

Companies

Add users to companies

You can create companies in Intercom without users but in these cases they will not be visible in the Web Console. Companies need to have users added to them to be visible in Intercom

user = intercom.users.find(:email => "[email protected]")
user.companies = [{:company_id => 6, :name => "Intercom"}, {:company_id => 9, :name => "Test Company"}]
intercom.users.save(user)
# You can also pass custom attributes within a company as you do this
user.companies = [{:id => 6, :name => "Intercom", :custom_attributes => {:referral_source => "Google"} } ]
intercom.users.save(user)

Find companies

company = intercom.companies.find(:company_id => "44")
company = intercom.companies.find(:name => "Some company")
company = intercom.companies.find(:id => "41e66f0313708347cb0000d0")

Update companies

company.name = 'Updated company name'
intercom.companies.save(company)

List companies and their users

intercom.companies.all.each {|company| puts %Q(#{company.name} - #{company.custom_attributes["referral_source"]}) }
intercom.companies.all.map {|company| company.name }
intercom.companies.users(company.id)

Tag users and companies

tag = intercom.tags.tag(name: 'blue', users: [{email: "[email protected]"}])
intercom.tags.untag(name: 'blue',  users: [{user_id: "42ea2f1b93891f6a99000427"}])
intercom.tags.all.each {|tag| "#{tag.id} - #{tag.name}" }
#or using map
intercom.tags.all.map {|tag| tag.name }
tag = intercom.tags.tag(name: 'blue', 
  companies: [{id: "42ea2f1b93891f6a99000427"}])

Segments

Find and list segments

segment = intercom.segments.find(:id => segment_id)
intercom.segments.all.each 
{|segment| puts "id: #{segment.id} name: #{segment.name}"}

Notes

Create, find and list notes

note = intercom.notes.find(:id => note)
note = intercom.notes.create(:body => "<p>Text for the note</p>", 
  :email => '[email protected]')
intercom.notes.find_all(:email => '[email protected]').each {|note| puts note.body}
intercom.notes.find_all(:user_id => '123').each {|note| puts note.body}

Conversations

Finding conversations for an admin

intercom.conversations.find_all(:type => 'admin', 
  :id => '7').each {|convo| ... }
intercom.conversations.find_all(:type => 'admin', 
  :id => 7, :open => true).each {|convo| ... }
intercom.conversations.find_all(:type => 'admin', 
  :id => 7, :open => false).each {|convo| ... }
intercom.conversations.find_all(:type => 'admin', 
  :id => 7, :open => false, :before => 1374844930).each {|convo| ... }

Finding conversations for a user

intercom.conversations.find_all(:email => '[email protected]', :type => 'user').each {|convo| ... }
intercom.conversations.find_all(:email => '[email protected]', :type => 'user', 
  :unread => false).each {|convo| ... }
intercom.conversations.find_all(:email => '[email protected]', :type => 'user', 
  :unread => true).each {|convo| ... }

Finding a single conversation

conversation = intercom.conversations.find(:id => '5340037614')

Interacting with the parts of a conversation

conversation.rendered_message.subject
conversation.conversation_parts[0].part_type
#Get the body of the second part
conversation.conversation_parts[1].body

Replying to conversations

intercom.conversations.reply(:id => conversation.id, :type => 'user', 
:email => '[email protected]', :message_type => 'comment', :body => 'foo')
intercom.conversations.reply(:id => conversation.id, :type => 'admin', 
:admin_id => '123', :message_type => 'comment', :body => 'bar')
intercom.conversations.reply(:id => conversation.id, :type => 'user', 
:email => '[email protected]', :message_type => 'comment', 
:body => 'foo', :attachment_urls => ['http://www.example.com/attachment.jpg'])

Open/close or reassign conversations

intercom.conversations.open(id: conversation.id, admin_id: '123')
intercom.conversations.close(id: conversation.id, admin_id: '123')
intercom.conversations.assign(id: conversation.id, admin_id: '123', 
  assignee_id: '124')
intercom.conversations.reply(:id => conversation.id, :type => 'admin', 
:assignee_id => assignee_admin.id, 
:admin_id => admin.id, :message_type => 'assignment')
intercom.conversations.mark_read(conversation.id)

Reply and open/close conversations

intercom.conversations.reply(:id => conversation.id, :type => 'admin', 
:admin_id => '123', :message_type => 'open', :body => 'bar')
intercom.conversations.reply(:id => conversation.id, :type => 'admin', 
:admin_id => '123', :message_type => 'close', :body => 'bar')
# Given a conversation with a partial user, load the full user. This can be
# done for any entity
intercom.users.load(conversation.user)

Sending messages

Sending InApp and email messages from admins, users and contacts

intercom.messages.create({
  :message_type => 'inapp',
  :body => "What's up :)",
  :from => {
    :type => 'admin',
    :id   => "1234"
  },
  :to => {
    :type => "user",
    :user_id   => "5678"
  }
})
intercom.messages.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"
  }
})
intercom.messages.create({
  :from => {
    :type => "user",
    :id => "536e564f316c83104c000020"
  },
  :body => "halp"
})
intercom.messages.create({
  :body     => "How can I help :)",
  :from => {
    :type => "admin",
    :id   => "1234"
  },
  :to => {
    :type => "contact",
    :id => "536e5643as316c83104c400671"
  }
})
intercom.messages.create({
  :from => {
    :type => "contact",
    :id => "536e5643as316c83104c400671"
  },
  :body => "halp"
})

Events

Create events with basic data and metadata

intercom.events.create(
  :event_name => "invited-friend", :created_at => Time.now.to_i,
  :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
intercom.events.create(:event_name => "placed-order", :email => current_user.email,
  :created_at => 1403001013,
  :metadata => {
    :order_date => Time.now.to_i,
    :stripe_invoice => 'inv_3434343434',
    :order_number => {
      :value => '3434-3434',
      :url => 'https://example.org/orders/3434-3434'
    },
    price: {
      :currency => 'usd',
      :amount => 2999
    }
  }
)
=begin
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)

*NB:* This version of the gem reserves the field name `type` in Event data.
=end

Contacts

🚧

What are contacts?

Contacts represent logged out users of your application.

Create, update, find and convert contacts

contact = intercom.contacts.create(email: "[email protected]")
contact.custom_attributes['foo'] = 'bar'
intercom.contacts.save(contact)
contacts = intercom.contacts.find_all(email: "[email protected]")
intercom.contacts.convert(contact, user)
intercom.contacts.delete(contact)

Counts

View counts

intercom.counts.for_app
intercom.counts.for_type(type: 'user', count: 'segment')

Subscriptions

πŸ“˜

Subscription are related to Webhooks

Subscribe to events in Intercom to receive webhooks.

Create, find and list subscriptions

intercom.subscriptions.create(:url => "http://example.com", :topics => ["user.created"])
intercom.subscriptions.find(:id => "nsub_123456789")
intercom.subscriptions.all

Errors

There are different styles for error handling - some people prefer exceptions; some prefer nil and check; some prefer error objects/codes. Balancing these preferences alongside our wish to provide an idiomatic gem has brought us to use the current mechanism of throwing specific exceptions. Our approach in the client is to propagate errors and signal our failure loudly so that erroneous data does not get propagated through our customers' systems - in other words, if you see a Intercom::ServiceUnavailableError you know where the problem is.

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::IntercomError will be raised. If desired, you can get at the http_code of an Intercom::IntercomError via its http_code method.

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

Intercom::AuthenticationError
Intercom::ServerError
Intercom::ServiceUnavailableError
Intercom::ServiceConnectionError
Intercom::ResourceNotFound
Intercom::BadRequestError
Intercom::RateLimitExceeded
Intercom::AttributeNotSetError # Raised when you try to call a getter that does not exist on an object
Intercom::MultipleMatchingUsersError
Intercom::HttpError # Raised when response object is unexpectedly nil

Rate Limiting

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

intercom.rate_limit_details
#=> {:limit=>180, :remaining=>179, :reset_at=>2014-10-07 14:58:00 +0100}