Platform
APIs & SDKs
Resources

...

LiveChat Node.js SDK

Introduction

LiveChat Node.js SDK was designed to help developers build apps in a quick and easy way. Under the hood, it makes use of the LiveChat Messaging APIs, taking care of this part for you.

By default, this SDK comes with a method for sending plain text messages, which is a great starting point for further development. Based on the method template we provide, you can easily build other methods. Thanks to that, you have the flexibility to cover the functionalities you need for your app, for example sending rich messages.

If Messaging APIs seem too intimidating or you just want to build something real quick, LiveChat Node.js SDK is your way to go.

Versioning

This is the version 0.2.0 of LiveChat Node.js SDK.

Initial configuration

Authorization

To use LiveChat Node.js SDK, you will need to provide an access token authorizing you with the Agent Chat API.

If you don't know how to get one, make sure to check out these resources:

Debugging

A useful feature you can configure is the debugging mode. By default, it's turned off. But if you want to display all messages exchanged with the LiveChat API, you can turn it on by setting debug: true. It may come in handy for troubleshooting as it will also display errors.

DEBUGGING
Copied!
const chat = new ChatSDK({ debug: true });

Region

By default, you'll be connected to a data center in the United States. If you want to change the data center to Europe, specify region: europe in the configuration object.

REGION
Copied!
const chat = new ChatSDK({ region: "europe" });

API version

By default, you'll make request to the current stable API version (v3.4). To change it to different version, for example v3.5, set apiVersion: 3.5 in the configuration object.

API VERSION CHANGE
Copied!
const chat = new ChatSDK({ apiVersion: "3.5" });

Installing the SDK

To install LiveChat Node.js SDK, run the following command:

INSTALLING SDK
Copied!
npm i @livechat/chat-sdk

Data structures

The LiveChat system is based on four basic types of entities - users, chats, events, and threads.

Data structureDescriptionSample
ChatChats consist of threads.Chat
ThreadThreads are parts of a chat. They consist of events. They provide continuous chat experience.Thread
EventUsers can add events to chats (for example send a message), which are then added to threads automatically.Events
UserThere are two basic types of users: Agent and Customer. Users can participate in multiple concurrent chats.Agent Customer

All these concepts are thoroughly described in Messaging Overview.

Methods

init

It handles authorization, intializes the WebSocket connection, attaches event listeners, and then logs in the Agent.

INIT
Copied!
chatSDK.init({
  access_token: access_token
  // OR
  personal_access_token: personal_access_token
})
Parameters
ParameterRequiredData typeNotes
access_tokenYes/No1stringSee Authorization to learn how to get an access token. Optionally, you can acquire it directly from Accounts SDK and pass it in to the init() method. The Simple Agent app uses this mechanism.
personal_access_tokenYes/No1stringSee Authorization docs to learn how to get a Personal Access Token. Provided value should be encoded in base64.

1) The init function requires one of the parameters to be provided.

destroy

It clears any stored resources, removes all listeners, and disconnects from the network. After using this method you won't be able to use the destroyed SDK instance.

DESTROY
Copied!
chatSDK.destroy();

getAgentDetails

It allows you to get information about the currently logged in Agent.

GET AGENT DETAILS
Copied!
chatSDK
  .getAgentDetails()
  .then((agentData) => {
    // access to the agentData object
  })
  .catch((error) => {
    // catch an error object
  });

sendMessage

It sends a plain text message.

SEND MESSAGE
Copied!
const chatId = "PJ0MRSHTDG";
const message = "Hello world";

chatSDK
  .sendMessage(chatId, message)
  .then((event) => {
    // get event_id or handle a success scenario
  })
  .catch((error) => {
    // catch an error object
  });
Parameters
ParameterRequiredData typeNotes
chat_idYesstringId of chat that you want to send a message to
messageYesstringMessage content
recipientsNostringPossible values: all (default), agents
Returned value
ValueData type
event_idstring

Creating custom methods

This SDK supports the RTM transport. For that reason, make sure you use the Agent Chat API RTM reference. When creating your custom methods, base on the payloads from the Agent Chat RTM API methods. ​ In the example below, we're creating a custom method that returns a chat. As you can see in the documentation, only chat_id is required, but you can include other optional parameters in your custom method.

CUSTOM METHODS
Copied!
const getChat = (chat_id) =>
    ChatSDK.methodFactory({
        action: "get_chat",
        payload: { chat_id }
    });getChat("PJ0MRSHTDG")
    .then(data => {
        // get a chat details with the latest thread (if exists)
    })
    .catch(error => {
        // catch an error
    })

on

The on method subscribes to emitted events.

ON
Copied!
chatSDK.on("event_name", (data) => {
  console.log(data);
});

Here's what you can listen for:

Event nameAction
readyYou've been successfully logged in. You're now ready to use all API methods.
PushesRefer to documentation.

off

The off method unsubsribes from emitted events.

OFF
Copied!
chatSDK.off("event_name", (data) => {
  console.log(data);
});

once

The once method subscribes to emitted events and unsubscribes right after the callback function has been called.

ONCE
Copied!
chatSDK.once("event_name", (data) => {
  console.log(data);
});

Here's what you can listen for:

Event nameAction
readyYou've been successfully logged in. You're now ready to use all API methods.
PushesRefer to documentation.

Simple Agent

To show you LiveChat Node.js SDK in action, we've prepared a sample app, Simple Agent . Its primary function is to send text messages. Apart from that, it gives you access to previous conversations, as well as the info about the current Agent.

LiveChat Node.js SDK

To run the app, follow a few steps:

  1. Create an app in Developer Console.

  2. Add the Authorization building block. Configure it by entering http://localhost:3000/ in Redirect URI whitelist and by adding the following scopes:

    • chats--all:rw
    • chats--access:rw
    • agents--all:ro
    • agents-bot--all:ro
    • customers:ro
    • multicast:ro
  3. Go to the Private installation tab and install the app.

  4. Clone the LiveChat Node.js SDK repository from GitHub and go to the example folder.

  5. In Developer Console, go to the Authorization building block of your app.

  6. Copy Client Id and paste it into the .env file in the example folder.

  7. Run Simple Agent with the following commands (from the example folder perspective):

SIMPLE AGENT
Copied!
npm install // install dependencies
npm start //start the app

To start a chat, log in to you LiveChat account and choose the Preview live option available in the Settings tab. You'll now be able to receive messages and respond to them from within Simple Agent.

It's worth mentioning that all functions invoked before logging in are queued. Once you're logged in, they are executed in the same order as they were invoked.

Changelog

-- [v0.2.0] - 2022-01-19 --

  • Add support for PAT
  • Update Simple Agent example
  • Set v3.4 as default api version

-- [v0.1.0] - 2019-11-27 --

  • Initial alpha release.

Questions

If you found a bug or a typo, you can let us know directly on GitHub. In case of any questions or feedback, don't hesitate to contact us at developers@text.com. We'll be happy to help!

...

Join the community
Get in direct contact with us through Discord.
Follow us
Follow our insightful tweets and interact with our content.
Contribute
See something that's wrong or unclear? Submit a pull request.
Contact us
Want to share feedback? Reach us at: developers@text.com