Intercom Node.js & TypeScript Library

repository·master·Indexed 18 days ago

https://github.com/intercom/intercom-node

Official Node bindings to the Intercom API (version 7.0.3). This type-safe TypeScript library provides the IntercomClient for interacting with Intercom APIs, featuring support for managing admins, AI content import sources, external pages, articles, internal articles, and help centers. It includes built-in functionality for paginated list endpoints, automatic retries with exponential backoff, and data export job management.

Tokens
71.6K
Snippets
346
Records
407
Agent score
62%

What's inside intercom-client

  1. Iterate over large company datasets using the Scroll API

    master

    For datasets exceeding 10,000 companies, use client.companies.scroll instead of list. The Scroll API is more efficient for deep paging but has specific operational constraints.

    Operational Rules:

    • Concurrency: Only 1 scroll can be open per app at a time. Attempting to open a second will result in an error.
    • Expiration: A scroll expires if it is not used for 1 minute. Subsequent calls with an expired scroll will fail.
    • Completion: When the end of the dataset is reached, the companies array will be empty and the scroll parameter will expire.
    • Error Handling: If you encounter an HTTP 500 error with the message "Request failed due to an internal network error. Please restart the scroll operation." (often due to network timeouts on large datasets), you must restart the scroll operation from the beginning. You cannot resume from a specific point.
    // Get the first page by sending an empty scroll_param or omitting it
    const pageableResponse = await client.companies.scroll({
        scroll_param: "scroll_param"
    });
    for await (const item of pageableResponse) {
        console.log(item);
    }
  2. Manage Help Center collections

    master
    The client.unstable.helpCenter namespace provides methods to manage Help Center collections. Note that collections are returned in descending order by their updated_at attribute, meaning the most recently updated collections appear first.
  3. Iterate through paginated list endpoints

    master

    List endpoints return a paginated response. You can iterate through all items using an async iterator, or manually navigate pages using hasNextPage() and getNextPage().

    import { IntercomClient } from "intercom-client";
    
    const client = new IntercomClient({ token: "YOUR_TOKEN" });
    
    // Option 1: Using an async iterator (recommended)
    const pageableResponse = await client.articles.list();
    for await (const item of pageableResponse) {
        console.log(item);
    }
    
    // Option 2: Manual page-by-page iteration
    let page = await client.articles.list();
    while (page.hasNextPage()) {
        page = page.getNextPage();
    }
    
    // Access the underlying response object
    const response = page.response;
  4. Manage Custom Object Instances

    master

    The unstable.customObjectInstances namespace provides methods to manage custom object instances.

    Available Operations:

    • getCustomObjectInstancesByExternalId: Fetch an instance using its external_id.
    • getCustomObjectInstancesById: Fetch an instance using its Intercom-defined id.
    • createCustomObjectInstances: Create or update a custom object instance.
    • deleteCustomObjectInstancesById: Delete an instance using its Intercom-defined id.
    • deleteCustomObjectInstancesByExternalId: Delete an instance using its external_id.
  5. Initialize the IntercomClient

    master

    To use the SDK, instantiate IntercomClient by providing your Intercom API token in the configuration object.

    import { IntercomClient } from "intercom-client";
    
    const client = new IntercomClient({ token: "YOUR_TOKEN" });
    
    // Example API call
    await client.aiContent.createContentImportSource({
        url: "https://www.example.com"
    });
  6. Explore Intercom API resources

    master

    The src/api/resources/index.ts file serves as the central entrypoint for all Intercom API resources. It exports both request methods (client requests) and type definitions for various Intercom entities.

    Resources are organized by domain. Most domains provide two main ways to interact:

    1. Namespace exports: Using export * as [name] allows you to access resource-specific methods via a namespace (e.g., articles.get(), contacts.create()).
    2. Type exports: Using export * from "./[name]/types/index.js" provides the TypeScript types required for request payloads and response objects.

    Commonly used resource namespaces include:

    • admins: Administrative client requests and types.
    • aiAgent: AI Agent functionality.
    • aiContent: AI-generated content management.
    • articles: Help Center articles.
    • companies: Company/Organization data.
    • contacts: User/Contact data.
    • conversations: Conversation/Chat data.
    • customObjectInstances: Data for custom objects.
    • events: User activity events.
    • tickets: Support ticket management.
    • visitors: Website visitor data.
  7. Use the CustomChannelEventsClient to integrate custom channels

    master

    The CustomChannelEventsClient allows you to bring Fin and Intercom capabilities to your own platform via API. By treating your integration like an Intercom channel, you can exchange events seamlessly, enabling users to interact with Fin directly within your own application's UI.

    Note: This feature is currently under managed availability. You must reach out to your Intercom accounts team to discuss access and support.

    import { CustomChannelEventsClient } from 'intercom-client';
    
    const client = new CustomChannelEventsClient({
      // ... client options
    });
    
    // Use client.customChannelEvents to access event notification methods
    await client.customChannelEvents.notifyNewConversation({
        event_id: "event_id",
        external_conversation_id: "external_conversation_id",
        contact: {
            type: "user",
            external_id: "external_id"
        }
    });
  8. Manage Fin Content Library with AiContentClient

    master

    The AiContentClient allows you to manage your Fin Content Library by creating and managing External Pages and Content Import Sources.

    • External Pages: Pages you want Fin to use for answering questions. This is useful for ingesting content that is not publicly accessible and cannot be crawled by Intercom. When creating an external page, you can provide an external_id to link it to a specific identifier from your source; if a page with that external_id and source_id already exists, the API will update it instead of creating a new one.
    • Content Import Sources: These represent the origins of your External Pages and are used to determine the default audience for those pages in the Intercom UI. You should create a unique Content Import Source for each distinct source of pages you intend to ingest.
    import Intercom from 'intercom-client';
    
    // Access the aiContent client via your main Intercom client instance
    // const client = new Intercom.Client({ ... });
    // await client.aiContent.createExternalPage({ ... });
  9. Manage Custom Object Instances with CustomObjectInstancesClient

    master

    The CustomObjectInstancesClient provides methods to interact with your Custom Object instances in Intercom.

    Note on Permissions: Accessing these endpoints requires additional permissions. You must configure the required permissions in your Developer Hub app package authentication settings.

    Key capabilities include:

    • Fetching instances by external_id or Intercom-defined id.
    • Creating or updating instances.
    • Deleting instances using either external_id or the Intercom-defined id.
    // Example of creating or updating a custom object instance
    await client.customObjectInstances.createCustomObjectInstances({
        custom_object_type_identifier: "Order",
        external_id: "123",
        external_created_at: 1392036272,
        external_updated_at: 1392036272,
        custom_attributes: {
            "order_number": "ORDER-12345",
            "total_amount": "custom_attributes"
        }
    });
  10. Manage IP allowlist settings with IpAllowlistClient

    master

    The IpAllowlistClient allows you to configure which IP addresses are permitted to access the Intercom API and web application for your workspace. This is used to restrict access to specific corporate networks or VPNs.

    Important Requirements:

    • This endpoint requires the manage_ip_allowlist OAuth scope.
    • Lockout Protection: The API will reject updates that would lock out the caller's IP address. Always ensure your current IP address is included in the allowlist when enabling this feature.

    Common Errors:

    • Intercom.UnauthorizedError: Thrown if authentication fails (401).
    • Intercom.UnprocessableEntityError: Thrown if the update request is invalid (422), such as when an update would cause a lockout.
  11. Configure logging and custom loggers

    master

    The SDK supports logging via the logging configuration object in the IntercomClient constructor. By default, logging is silent (silent: true) and uses logging.LogLevel.Info with a logging.ConsoleLogger.

    To use a custom logger, implement the logging.ILogger interface.

    import { IntercomClient, logging } from "intercom-client";
    
    const client = new IntercomClient({
        logging: {
            level: logging.LogLevel.Debug,
            logger: new logging.ConsoleLogger(),
            silent: false,
        }
    });
    
    // Example: Custom logger using Winston
    const logger: logging.ILogger = {
        debug: (msg, ...args) => winstonLogger.debug(msg, ...args),
        info: (msg, ...args) => winstonLogger.info(msg, ...args),
        warn: (msg, ...args) => winstonLogger.warn(msg, ...args),
        error: (msg, ...args) => winstonLogger.error(msg, ...args),
    };