intercom

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 27 Imported by: 0

README

intercom-go-sdk

CI

Go SDK for the Intercom REST API v2.15.

  • Minimal dependencies (stdlib + google/go-querystring)
  • 167 endpoints across 34 services organized in 17 domain-scoped sub-packages
  • Generic auto-pagination iterator
  • Search filter builder

Requirements

Go 1.26.1 or later.

Installation

go get github.com/rassakhatsky/intercom-go-sdk

Quick Start

import (
    "context"
    "fmt"

    intercom "github.com/rassakhatsky/intercom-go-sdk"
)

client := intercom.NewClient("your-bearer-token")
ctx := context.Background()

contact, err := client.Contacts().Get(ctx, "contact-id")
Client Options
client := intercom.NewClient("token",
    intercom.WithHTTPClient(customHTTPClient),
    intercom.WithLogger(myLogger),
    intercom.WithBaseURL("https://custom.url/"),
)

CRUD

import "github.com/rassakhatsky/intercom-go-sdk/contacts"

// Create
contact, err := client.Contacts().Create(ctx, &contacts.CreateRequest{
    Role:  "user",
    Email: "alice@example.com",
    Name:  "Alice",
})

// Update
contact, err = client.Contacts().Update(ctx, contact.ID, &contacts.UpdateRequest{
    Name: "Alice Smith",
})

// Delete
deleted, err := client.Contacts().Delete(ctx, contact.ID)

Pagination

import "github.com/rassakhatsky/intercom-go-sdk/api"

// Auto-paginate with iterator
iter := client.Contacts().ListAll(ctx, &api.ListOptions{PerPage: 50})
for iter.Next() {
    fmt.Println(iter.Current().Email)
}
if err := iter.Err(); err != nil {
    log.Fatal(err)
}

// Or collect all at once
contacts, err := client.Contacts().ListAll(ctx, &api.ListOptions{PerPage: 50}).Collect()

// Callback-based iteration
err := client.Contacts().ListAll(ctx, nil).ForEach(func(c contacts.Contact) error {
    fmt.Println(c.Name)
    return nil // return non-nil error to stop early
})

Companies use scroll-based pagination via client.Companies().Scroll(ctx, scrollParam).

import "github.com/rassakhatsky/intercom-go-sdk/api"

// Single filter — using typed operator constants
result, err := client.Contacts().Search(ctx, &api.SearchRequest{
    Query: api.SingleFilterOf("email", api.OpEquals, "alice@example.com"),
})

// Compound filter
result, err = client.Contacts().Search(ctx, &api.SearchRequest{
    Query: api.And(
        api.SingleFilterOf("role", api.OpEquals, "user"),
        api.SingleFilterOf("email", api.OpContains, "example.com"),
    ),
})

Error Handling

import "github.com/rassakhatsky/intercom-go-sdk/api"

contact, err := client.Contacts().Get(ctx, "nonexistent")
if err != nil {
    if api.IsNotFound(err) {
        fmt.Println("Contact not found")
    } else if api.IsRateLimited(err) {
        fmt.Println("Rate limited")
    } else if api.IsServerError(err) {
        fmt.Println("Server error, retry with backoff")
    } else {
        fmt.Printf("Error: %v\n", err)
    }
}

Additional status helpers: api.IsUnauthorized (401), api.IsBadRequest (400), api.IsForbidden (403), api.IsConflict (409), api.IsUnprocessableEntity (422).

Rate Limit Details

Rate-limited (429) responses include parsed rate limit metadata:

import "github.com/rassakhatsky/intercom-go-sdk/api"

if api.IsRateLimited(err) {
    var apiErr *api.ErrorResponse
    if errors.As(err, &apiErr) && apiErr.RateLimit != nil {
        fmt.Printf("Retry after %v\n", apiErr.RateLimit.RetryAfter)
        time.Sleep(apiErr.RateLimit.RetryAfter)
    }
}
Error Code Matching

Match specific Intercom API error codes using HasErrorCode and predefined ErrorCode constants:

import "github.com/rassakhatsky/intercom-go-sdk/api"

var apiErr *api.ErrorResponse
if errors.As(err, &apiErr) {
    if apiErr.HasErrorCode(api.ErrParameterInvalid) {
        fmt.Println("Invalid parameter")
    }
}

Raw Methods

Every method has a *Raw companion returning (*api.Result, error) with raw response bytes and HTTP metadata. API errors (4xx/5xx) populate Result.Error instead of returning a Go error.

import (
    "github.com/rassakhatsky/intercom-go-sdk/api"
    "github.com/rassakhatsky/intercom-go-sdk/contacts"
)

result, err := client.Contacts().GetRaw(ctx, "contact-id")
if err != nil {
    log.Fatal(err) // transport error only
}
if result.Error != nil {
    fmt.Println("API error:", result.Error.Error())
    return
}
contact, err := contacts.ParseGetResult(result)

// Or use the generic Decode helper
contact, err = api.Decode[contacts.Contact](result)

Sub-Packages

Services are organized into domain-scoped sub-packages. Each service is accessed via an accessor method on the client (e.g., client.Contacts(), client.Tags()).

Package Accessor Methods Description
contacts Contacts(), Visitors() Contacts (users/leads) and visitors
conversations Conversations() Conversations, replies, parts
companies Companies() Companies (with scroll pagination)
tickets Tickets(), TicketTypes(), TicketStates() Tickets and ticket configuration
articles Articles(), InternalArticles() Help center and internal articles
helpcenter HelpCenter() Help center collections and centers
news News() News items and newsfeeds
ai AIContent(), FinVoice() AI content and Fin Voice
calls Calls(), PhoneCallRedirects() Calls and phone call redirects
tags Tags() Tags
admins Admins(), Teams(), AwayStatusReasons() Admins, teams, away status
segments Segments() Segments
data DataEvents(), DataAttributes(), CustomObjects() Data events, attributes, custom objects
messaging Messages(), Emails(), SubscriptionTypes() Messages, emails, subscriptions
export DataExport(), ExportReporting() Data and reporting exports
settings Brands(), IPAllowlist(), CustomChannelEvents(), Jobs(), Notes() Account settings
workflows Workflows() Workflow export

Core types (Result, Iter[T], Filter, ErrorResponse, ListOptions, etc.) live in the public api/ package and are imported directly.

Importing Sub-Package Types

When you need request/response types from a specific service, import the sub-package directly:

import (
    intercom "github.com/rassakhatsky/intercom-go-sdk"
    "github.com/rassakhatsky/intercom-go-sdk/api"
    "github.com/rassakhatsky/intercom-go-sdk/contacts"
    "github.com/rassakhatsky/intercom-go-sdk/tags"
)

// Use sub-package types for requests
contact, err := client.Contacts().Create(ctx, &contacts.CreateRequest{
    Role:  "user",
    Email: "alice@example.com",
})

// Use api package for shared types
iter := client.Tags().ListAll(ctx, &api.ListOptions{PerPage: 25})

Documentation

License

MIT

Documentation

Overview

Package intercom provides a Go client for the Intercom API v2.15.

Services are organized into domain-scoped sub-packages (contacts, tickets, tags, etc.) and accessed via accessor methods on the Client.

Usage:

client := intercom.NewClient("your-bearer-token")

// Get a contact
contact, err := client.Contacts().Get(ctx, "contact-id")

// List all contacts with auto-pagination
iter := client.Contacts().ListAll(ctx, nil)
for iter.Next() {
    fmt.Println(iter.Current().Name)
}
if err := iter.Err(); err != nil {
    log.Fatal(err)
}

// Or collect all pages into a slice in one call
contacts, err := client.Contacts().ListAll(ctx, nil).Collect()

// Iterate with a callback using ForEach
err = client.Contacts().ListAll(ctx, nil).ForEach(func(c contacts.Contact) error {
    fmt.Println(c.Name)
    return nil
})

// Search contacts with filters (types from the api/ package)
result, err := client.Contacts().Search(ctx, &api.SearchRequest{
    Query: api.SingleFilterOf("email", api.OpEquals, "alice@example.com"),
})

Every service method has a Raw companion that returns a *Result with HTTP metadata (status code, headers, raw body bytes). API errors (4xx/5xx) populate Result.Error instead of returning a Go error:

result, err := client.Contacts().GetRaw(ctx, "contact-id")
if err != nil {
    log.Fatal(err) // transport error only
}
if result.Error != nil {
    fmt.Printf("API error %d: %s\n", result.StatusCode, result.Error.Error())
} else {
    contact, _ := contacts.ParseGetResult(result)
    fmt.Println(contact.Name)
    fmt.Println(result.Header.Get("X-RateLimit-Remaining"))
}

The client can be configured with functional options:

client := intercom.NewClient("token",
    intercom.WithHTTPClient(customHTTPClient),
    intercom.WithLogger(myLogger),
    intercom.WithBaseURL("https://custom.url/"),
)

All API methods accept a context.Context as their first parameter for cancellation and timeout control.

Error responses from the Intercom API are returned as *api.ErrorResponse values. Helper functions in the api/ package check for common HTTP status codes:

api.IsNotFound(err)            // 404
api.IsRateLimited(err)         // 429
api.IsUnauthorized(err)        // 401
api.IsBadRequest(err)          // 400
api.IsForbidden(err)           // 403
api.IsConflict(err)            // 409
api.IsUnprocessableEntity(err) // 422
api.IsServerError(err)         // 5xx

For rate-limited responses (429), the ErrorResponse includes parsed rate limit headers:

if api.IsRateLimited(err) {
    var apiErr *api.ErrorResponse
    if errors.As(err, &apiErr) && apiErr.RateLimit != nil {
        fmt.Printf("Retry after %v\n", apiErr.RateLimit.RetryAfter)
        time.Sleep(apiErr.RateLimit.RetryAfter)
    }
}

Intercom API error codes can be matched using HasErrorCode and the predefined ErrorCode constants:

var apiErr *api.ErrorResponse
if errors.As(err, &apiErr) {
    if apiErr.HasErrorCode(api.ErrParameterInvalid) {
        // handle invalid parameter
    }
}

Core types (Result, Iter, Filter, ErrorResponse, ListOptions) live in the public api/ package. Sub-package-specific types (request/response structs, domain models) are imported from their respective packages.

Example (ContactsGetRaw)

ExampleContactsService_GetRaw demonstrates using a Raw method to access HTTP metadata alongside the typed response data.

package main

import (
	"context"
	"fmt"
	"log"

	intercom "github.com/rassakhatsky/intercom-go-sdk"
	"github.com/rassakhatsky/intercom-go-sdk/contacts"
)

func main() {
	client := intercom.NewClient("your-bearer-token")
	ctx := context.Background()

	result, err := client.Contacts().GetRaw(ctx, "contact-id")
	if err != nil {
		log.Fatal(err) // only returned for transport/network errors
	}

	// Check for API errors (4xx/5xx) — no Go error is returned for these
	if result.Error != nil {
		fmt.Printf("API error %d: %s\n", result.StatusCode, result.Error.Error())
		return
	}

	// Decode the typed response data using the Parse function
	contact, err := contacts.ParseGetResult(result)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Contact:", contact.Name)

	// Access HTTP metadata for debugging or advanced logic
	fmt.Println("Status:", result.StatusCode)
	fmt.Println("Rate-Limit-Remaining:", result.Header.Get("X-RateLimit-Remaining"))

	// Access the raw JSON body
	fmt.Println("Raw body length:", len(result.Body))
}
Example (ContactsSearchRaw)

ExampleContactsService_SearchRaw demonstrates using a Raw search method with access to rate-limit headers for custom retry logic.

package main

import (
	"context"
	"fmt"
	"log"

	intercom "github.com/rassakhatsky/intercom-go-sdk"
	"github.com/rassakhatsky/intercom-go-sdk/api"
	"github.com/rassakhatsky/intercom-go-sdk/contacts"
)

func main() {
	client := intercom.NewClient("your-bearer-token")
	ctx := context.Background()

	result, err := client.Contacts().SearchRaw(ctx, &api.SearchRequest{
		Query: api.SingleFilterOf("email", api.OpEquals, "alice@example.com"),
	})
	if err != nil {
		log.Fatal(err)
	}

	if result.Error != nil {
		fmt.Printf("API error: %s\n", result.Error.Error())
		return
	}

	page, err := contacts.ParseSearchResult(result)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found %d contacts\n", len(page.Data))
	fmt.Printf("Rate limit remaining: %s\n", result.Header.Get("X-RateLimit-Remaining"))
}
Example (ErrorCodeMatching)

Example_errorCodeMatching demonstrates matching specific Intercom API error codes returned in error responses.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	intercom "github.com/rassakhatsky/intercom-go-sdk"
	"github.com/rassakhatsky/intercom-go-sdk/api"
)

func main() {
	client := intercom.NewClient("your-bearer-token")
	ctx := context.Background()

	_, err := client.Contacts().Get(ctx, "contact-id")
	if err != nil {
		var apiErr *api.ErrorResponse
		if errors.As(err, &apiErr) {
			switch {
			case apiErr.HasErrorCode(api.ErrParameterInvalid):
				fmt.Println("Invalid parameter:", apiErr.Error())
			case apiErr.HasErrorCode(api.ErrTokenUnauthorized):
				fmt.Println("Token is unauthorized, check your API key")
			case apiErr.HasErrorCode(api.ErrRateLimitExceeded):
				fmt.Println("Rate limit exceeded, back off and retry")
			default:
				fmt.Println("API error:", apiErr.Error())
			}
		} else {
			log.Fatal(err) // transport error
		}
	}
}
Example (RateLimitHandling)

Example_rateLimitHandling demonstrates handling rate-limited responses with parsed rate limit metadata.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	intercom "github.com/rassakhatsky/intercom-go-sdk"
	"github.com/rassakhatsky/intercom-go-sdk/api"
)

func main() {
	client := intercom.NewClient("your-bearer-token")
	ctx := context.Background()

	_, err := client.Contacts().Get(ctx, "contact-id")
	if api.IsRateLimited(err) {
		var apiErr *api.ErrorResponse
		if errors.As(err, &apiErr) && apiErr.RateLimit != nil {
			fmt.Printf("Rate limited. Limit: %d, Remaining: %d\n",
				apiErr.RateLimit.Limit, apiErr.RateLimit.Remaining)
			fmt.Printf("Retry after: %v\n", apiErr.RateLimit.RetryAfter)
			fmt.Printf("Window resets at: %v\n", apiErr.RateLimit.Reset)
			time.Sleep(apiErr.RateLimit.RetryAfter)
		}
	}
}
Example (ServerErrorRetry)

Example_serverErrorRetry demonstrates checking for server-side errors to implement retry logic.

package main

import (
	"context"
	"fmt"
	"log"

	intercom "github.com/rassakhatsky/intercom-go-sdk"
	"github.com/rassakhatsky/intercom-go-sdk/api"
)

func main() {
	client := intercom.NewClient("your-bearer-token")
	ctx := context.Background()

	_, err := client.Contacts().Get(ctx, "contact-id")
	if api.IsServerError(err) {
		fmt.Println("Server error, retrying...")
		// implement retry with backoff
	} else if api.IsNotFound(err) {
		fmt.Println("Contact not found")
	} else if err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client manages communication with the Intercom API.

func NewClient

func NewClient(token string, opts ...ClientOption) *Client

NewClient creates a new Intercom API client. It panics if token is empty or contains only whitespace.

func (*Client) AIContent

func (c *Client) AIContent() *aiPkg.ContentService

AIContent returns the AI content service.

func (*Client) Admins

func (c *Client) Admins() *admins.Service

Admins returns the admins service.

func (*Client) Articles

func (c *Client) Articles() *articles.Service

Articles returns the articles service.

func (*Client) AwayStatusReasons

func (c *Client) AwayStatusReasons() *admins.AwayStatusReasonsService

AwayStatusReasons returns the away status reasons service.

func (*Client) Brands

func (c *Client) Brands() *settings.BrandsService

Brands returns the brands service.

func (*Client) Calls

func (c *Client) Calls() *calls.Service

Calls returns the calls service.

func (*Client) Companies

func (c *Client) Companies() *companies.Service

Companies returns the companies service.

func (*Client) Contacts

func (c *Client) Contacts() *contacts.Service

Contacts returns the contacts service.

func (*Client) Conversations

func (c *Client) Conversations() *conversations.Service

Conversations returns the conversations service.

func (*Client) CustomChannelEvents

func (c *Client) CustomChannelEvents() *settings.ChannelEventsService

CustomChannelEvents returns the custom channel events service.

func (*Client) CustomObjects

func (c *Client) CustomObjects() *data.ObjectsService

CustomObjects returns the custom objects service.

func (*Client) DataAttributes

func (c *Client) DataAttributes() *data.AttributesService

DataAttributes returns the data attributes service.

func (*Client) DataEvents

func (c *Client) DataEvents() *data.EventsService

DataEvents returns the data events service.

func (*Client) DataExport

func (c *Client) DataExport() *export.DataService

DataExport returns the data export service.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*api.Response, error)

Do sends an API request and returns the API response. The JSON response body is decoded into v if v is non-nil. API errors (4xx/5xx) are returned as *ErrorResponse errors suitable for inspection with status predicates (IsNotFound, IsBadRequest, etc.).

func (*Client) DoDownload

func (c *Client) DoDownload(ctx context.Context, req *http.Request, w io.Writer) error

DoDownload executes an HTTP request and streams the response body to w. It is intended for binary downloads (e.g., CSV/gzip exports). On 4xx/5xx responses, it reads the error body and returns an *ErrorResponse.

func (*Client) DoRaw

func (c *Client) DoRaw(ctx context.Context, req *http.Request) (*api.Result, error)

DoRaw executes an HTTP request and returns a Result with raw HTTP metadata and body. API errors (4xx/5xx) populate Result.Error instead of returning a Go error; only transport/IO failures return a Go error.

func (*Client) DoRawNoRedirect

func (c *Client) DoRawNoRedirect(ctx context.Context, req *http.Request) (*api.Result, error)

DoRawNoRedirect executes an HTTP request like DoRaw, but does not follow HTTP redirects. This is used when the API returns a redirect (e.g., 302) and the caller needs the Location header rather than the redirect target.

func (*Client) Emails

func (c *Client) Emails() *messaging.EmailsService

Emails returns the emails service.

func (*Client) ExportReporting

func (c *Client) ExportReporting() *export.ReportingService

ExportReporting returns the export reporting service.

func (*Client) FinVoice

func (c *Client) FinVoice() *aiPkg.VoiceService

FinVoice returns the Fin Voice service.

func (*Client) HelpCenter

func (c *Client) HelpCenter() *helpcenter.Service

HelpCenter returns the help center service.

func (*Client) IPAllowlist

func (c *Client) IPAllowlist() *settings.IPAllowlistService

IPAllowlist returns the IP allowlist service.

func (*Client) InternalArticles

func (c *Client) InternalArticles() *articles.InternalService

InternalArticles returns the internal articles service.

func (*Client) Jobs

func (c *Client) Jobs() *settings.JobsService

Jobs returns the jobs service.

func (*Client) Messages

func (c *Client) Messages() *messaging.MessagesService

Messages returns the messages service.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body any) (*http.Request, error)

NewRequest creates an API request. A relative URL path can be provided in urlStr, in which case it is resolved relative to the BaseURL of the Client. If body is non-nil, it is JSON-encoded and included as the request body.

func (*Client) News

func (c *Client) News() *news.Service

News returns the news service.

func (*Client) Notes

func (c *Client) Notes() *settings.NotesService

Notes returns the notes service.

func (*Client) PhoneCallRedirects

func (c *Client) PhoneCallRedirects() *calls.RedirectsService

PhoneCallRedirects returns the phone call redirects service.

func (*Client) Segments

func (c *Client) Segments() *segments.Service

Segments returns the segments service.

func (*Client) SubscriptionTypes

func (c *Client) SubscriptionTypes() *messaging.SubscriptionsService

SubscriptionTypes returns the subscription types service.

func (*Client) Tags

func (c *Client) Tags() *tags.Service

Tags returns the tags service.

func (*Client) Teams

func (c *Client) Teams() *admins.TeamsService

Teams returns the teams service.

func (*Client) TicketStates

func (c *Client) TicketStates() *tickets.StatesService

TicketStates returns the ticket states service.

func (*Client) TicketTypes

func (c *Client) TicketTypes() *tickets.TypesService

TicketTypes returns the ticket types service.

func (*Client) Tickets

func (c *Client) Tickets() *tickets.Service

Tickets returns the tickets service.

func (*Client) Visitors

func (c *Client) Visitors() *contacts.VisitorsService

Visitors returns the visitors service.

func (*Client) Workflows

func (c *Client) Workflows() *workflows.Service

Workflows returns the workflows service.

type ClientOption

type ClientOption func(*Client)

ClientOption configures the Client.

func WithBaseURL

func WithBaseURL(u string) ClientOption

WithBaseURL sets a custom base URL for API requests.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client for API requests. It panics if hc is nil.

func WithLogger

func WithLogger(l api.Logger) ClientOption

WithLogger sets a custom logger.

Directories

Path Synopsis
Package admins provides services for managing Intercom admins and teams.
Package admins provides services for managing Intercom admins and teams.
Package ai provides services for Intercom AI features.
Package ai provides services for Intercom AI features.
Package api provides the core types and interfaces shared across all sub-packages in the Intercom Go SDK.
Package api provides the core types and interfaces shared across all sub-packages in the Intercom Go SDK.
Package articles provides services for managing Intercom help center articles.
Package articles provides services for managing Intercom help center articles.
Package calls provides services for Intercom phone calls.
Package calls provides services for Intercom phone calls.
Package companies provides a service for managing Intercom companies.
Package companies provides a service for managing Intercom companies.
Package contacts provides services for managing Intercom contacts and visitors.
Package contacts provides services for managing Intercom contacts and visitors.
Package conversations provides a service for managing Intercom conversations.
Package conversations provides a service for managing Intercom conversations.
Package data provides services for Intercom custom data.
Package data provides services for Intercom custom data.
Package export provides services for Intercom data exports.
Package export provides services for Intercom data exports.
Package helpcenter provides a service for managing Intercom Help Centers and their collections.
Package helpcenter provides a service for managing Intercom Help Centers and their collections.
Package messaging provides services for Intercom messaging and email.
Package messaging provides services for Intercom messaging and email.
Package news provides a service for managing Intercom news items and newsfeeds.
Package news provides a service for managing Intercom news items and newsfeeds.
Package segments provides a service for managing Intercom segments.
Package segments provides a service for managing Intercom segments.
Package settings provides services for Intercom workspace configuration.
Package settings provides services for Intercom workspace configuration.
Package tags provides a service for managing Intercom tags.
Package tags provides a service for managing Intercom tags.
Package tickets provides services for managing Intercom tickets.
Package tickets provides services for managing Intercom tickets.
Package workflows provides a service for managing Intercom workflows.
Package workflows provides a service for managing Intercom workflows.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL