Quick Start

SendBird helps you to add real-time chat to any app with speed and efficiency. The JavaScript SDK specifically provides you with methods to initialize and configure chat from the client side - no backend required. This quick start section presents a succinct overview of the SDK’s functionalities and logic, then guide you through the preliminary steps of setting up SendBird in your own app.


Create a new SendBird application in the Dashboard

The first thing to do is to sign in to the SendBird Dashboard and create a SendBird application. If you do not have an account yet you can sign uupp with Google, GitHub, or create a new account.

You can create one application per service, regardless of the platform. For example, an app released in both Android and iOS requires only one application to be created in the Dashboard.

All users within the same SendBird application can communicate with each other, across all platforms. This means users using iOS, Android, web clients, etc. can all chat with one another. However, users in different SendBird applications cannot talk to each other.

XSS (Cross Site Scripting) Prevention

Cross-site scripting (XSS) is a type of computer security vulnerability. XSS helps attackers inject client-side scripts into web pages viewed by other users.

Users can send any type of string data without restriction through SendBird. Please keep in mind to check safety of received data from other users before rendering it into your DOM.

Note: For more about the XSS prevention, visit the OWASP's XSS Prevention Cheat Sheet page.


Run the sample

Download the latest SendBird JavaScript sample.

Or download/clone the sample by using git.

Git clone
$ git clone https://github.com/smilefam/SendBird-JavaScript

Run sample project

You need a local server to run the sample project. In this example, we'll be using Python to run our local server.

  1. Download and install Python if you do not have it installed in your system.
  2. Open a terminal and run a Python HTTP Server in your project path.
    $ cd web-sample
    # If you use Python 2
    $ python -m SimpleHTTPServer 8000
    # or Python 3
    $ python -m http.server 8000
  3. Try connecting to http://localhost:8000 from a web browser to view the sample project.

Integrating SendBird with an existing app

Download the latest SendBird JavaScript SDK

$ bower install sendbird
$ npm install sendbird

Add the SDK file to your project

Download the SendBird JavaScript SDK file and add it to your Project classpath (generally the libs/ directory). Then include the JavaScript file on your page.

<script src="lib/SendBird.min.js"></script>

Supported Browsers

Brower Supported versions
Internet Explorer 10 or later
Edge 13 or later
Chrome 16 or later
Firefox 11 or later
Safari 7 or later
Opera 12.1 or later
iOS Safari 7 or later
Android Browser 4.4 (Kitkat) or later

Running the 3.0 sample in React Native

  1. Download and install node and npm.
  2. Clone the sample project from GitHub.
    $ git clone https://github.com/smilefam/SendBird-JavaScript
  3. Open a terminal and run the following commands in your project path.
    $ cd react-native-sample/SendBirdReactNativeSample
    $ npm install
    $ npm install -g react-native-cli
  4. Run the sample app in an iOS simulator.
    $ react-native run-ios
  5. Run the sample app in an Android simulator. Before running this command, you must run the simulator from Android Studio.
    $ react-native run-android

Parameter ordering in callbacks

In a callback, the error parameter is passed last in order by default. For example, connect() below returns parameters in (user, error) order.

sb.connect(userId, function(user, error) {});

It is possible to configure SendBird to change this order by calling sb.setErrorFirstCallback(true). Once true is set, all callbacks pass the error as the first parameter.

sb.setErrorFirstCallback(true);
sb.connect(userId, function(error, user) {});

sb.setErrorFirstCallback(false) returns callbacks to their original parameter ordering, with errors last.


Using functions of SendBird object with Immutable-js

If you're using Immutable-js in your products, instead of Immutable.Map(), use Immutable.fromJS() which converts deeply nested objects to an Immutable Map.
You can call functions in the SendBird object, Because fromJS() returns internal objects. But if you use Map function, you can't call SendBird function.

var userIds = ['unique_user_id1', 'unique_user_id2']; 
sb.GroupChannel.createChannelWithUserIds(userIds, false, name, coverUrl, data, function(createdChannel, error) {
    if (error) {
        console.error(error);
        return;
    }
    var immutableObject = Immutable.fromJS(createdChannel);
    console.log(immutableObject);
});

Authentication

To use SendBird's features, first do the following authentication tasks.


Initializing with APP_ID

To use the chat features, you must initialize SendBird using the APP_ID assigned to your SendBird application. Typically, initialization is implemented in the user login view.

var sb = new SendBird({
    appId: APP_ID;
});

Connecting with UserID

By default, SendBird requires only a UserID to join a channel. Upon requesting connection, SendBird queries its user database for a matching UserID. If it finds that the UserID has not been registered yet, SendBird creates a new user account. The UserID can be any unique string id, such as an email address or a UID from your database.

This simple authentication procedure is useful when you are in development or if your service does not require additional security.

Note: Explanation on SendBird's usage of Handlers and callbacks can be found under the Event Handler section.

sb.connect(userId, function(user, error) {});

Note: You must connect to SendBird before calling any methods through the SDK (apart from initializing SendBird). If you attempt to call a method without connecting, you may receive an API-TOKEN is missing error.


Connecting with UserID and Access Token

With the SendBird Platform API, you can create a user with an access token, or you can issue an access token for an existing user. Once an access token is issued, you are required to provide the user's token in the login method.

  1. Create a SendBird user account via the Platform API when your user signs up on your service.
  2. Save the access token to your secured persistent store.
  3. Load the access token in your client and pass it to the SendBird login method.
  4. For security reasons, we recommend that you periodically update your access token by issuing a new token to replace the previous one.

Note: You can set restrictions for users without access tokens in your Dashboard settings. These settings can be found under Security - Access Token Policy.

sb.connect(userId, accessToken, function(user, error) {});

Disconnecting

You must disconnect from SendBird when your user no longer needs to receive messages from an online state. But users receive Group Channel messages through Push Notificions in React Native.

Disconnecting removes all registered handlers and callbacks. That is, it removes all Event Handlers added through sb.addChannelHandler() or sb.addConnectionHandler(). It also flushes all internally cached data, such as the channels that are cached when sb.OpenChannel.getChannel() or sb.GroupChannel.getChannel() is called.

sb.disconnect(function(){
    // You are disconnected from SendBird.
});

Updating a user profile and profile image

You can update user's nickname and profile image. Call updateCurrentUserInfo(nickname, profileUrl, callbackFunction) to update the nickname, as well as the profile picture with a URL.

sb.updateCurrentUserInfo(nickname, profileUrl, function(response, error) {
  console.log(response, error);
});

Or, you can upload an image directly using updateCurrentUserInfoWithProfileImage(nickname, profileFile, callbackFunction).

sb.updateCurrentUserInfoWithProfileImage(nickname, profileFile, function(response, error) {
  console.log(response, error);
});

Push notification message templates

Message templates define how a message is displayed when a push notification arrives to a user's device. You can choose between the default template and the alternative template, both of which are customizable.

Message templates

Text message File message
Default template {sender_name}: {message} (for example, John: Hello!) {filename} (for example, squirrel.jpg)
Alternative template New message arrived New file arrived

{sender_name}, {message}, and {filename} represent the corresponding string values. Use these fields to customize message templates from your Dashboard Settings. The option is under Notifications > Push Notification Message Templates.

To choose whether a user receives messages in the form of the default template or the alternative template, call sb.setPushTemplate(templateName, handler). templateName can be one of two values: sb.PUSH_TEMPLATE_DEFAULT, or sb.PUSH_TEMPLATE_ALTERNATIVE.

sb.setPushTemplate(sb.PUSH_TEMPLATE_ALTERNATIVE, function (response, error) {
  // do something...
  console.log(response, error);
});

Note: The default configuration is sb.PUSH_TEMPLATE_DEFAULT.

You can check your current setting with sb.getPushTemplate().

sb.getPushTemplate(function (response, error) {
  // do something...
  console.log(response, error);
});

Channel Types

We recommend you to understand the following terminology before proceeding with the rest of this guide.


Open Channel

Open Channel is a public chat. In this channel type, anyone can enter and participate in the chat without permission. A single channel can handle thousands of simultaneous users like Twitch-style public chat.


Group Channel

Group Channel is a private chat. A user may join the chat only through an invitation by another user who is already a member of the chatroom.

  • Distinct property : A channel with the Distinct property turned on is always reused for the same members. If a new member is invited, or if a member leaves the channel, then the Distinct property is disabled automatically.

  • 1-on-1 messaging : 1-on-1 messaging is a private channel between two users. You can turn on the Distinct property for the channel to reuse a channel for the same members like Twitter Direct Messages-style 1-on-1 chatting.

  • Group messaging : Group messaging is a private channel among multiple users. You can invite up to hundreds of members into a group channel like WhatsApp-style closed group chat.


Open Channel vs. Group Channel

Type Open Channel Group Channel
Access control Public Invitation required
Class name OpenChannel GroupChannel
Number of members Over a few thousand Less than a few hundred
How to create SendBird Dashboard / Platform API / Client SDK Client SDK / Platform API
Operators Supported N/A
User ban Supported N/A
User mute Supported N/A
Freeze channel Supported N/A
Push notifications N/A Supported
Unread counts N/A Supported
Read receipts N/A Supported
Typing indicators N/A Supported

Open Channel

Open Channel is a public chat. In this channel type, anyone can enter and participate in the chat without permission. A single channel can handle thousands of simultaneous users like Twitch-style public chat.


Creating an open channel

Open Channel is ideal for use cases that require a small and static number of channel. To create an open channel from the SendBird Dashboard, do the following:

In the dashboard, click OPEN CHANNELS, then click CREATE at the top-left corner. In the dialog box that appears, specify the name, url, cover image, and custom type of a channel. The channel url is a unique identifier.

You can also create a channel on demand or dynamically via the SDK or the SendBird Platform API.

sb.OpenChannel.createChannel(name, coverUrl, data, function(createdChannel, error) {
    if (error) {
        console.error(error);
        return;
    }

    // onCreated
    console.log(createdChannel);
});

Getting a list of open channels

You can obtain a list of all open channels by creating a OpenChannelListQuery. The next() method returns a list of OpenChannel objects.

var openChannelListQuery = sb.OpenChannel.createOpenChannelListQuery();

openChannelListQuery.next(function (channels, error) {
    if (error) {
        console.log(error);
        return;
    }

    console.log(channels);
});

Getting an open channel instance with a URL

Since a channel URL is a unique identifier of an open channel, you can use a URL to retrieve a channel instance. It is important to remember that a user must enter the channel to send or receive messages within it.

Store channel URLs to handle lifecycle or state changes in your app. For example, if a user disconnects from SendBird by temporarily switching to another app, you can provide a smooth restoration of the user's state using a stored URL to fetch the appropriate channel instance, then re-entering the user into the channel.

sb.OpenChannel.getChannel(channelUrl, function(channel, error) {
    if(error) {
        console.error(error);
        return;
    }

    // Successfully fetched the channel.
    console.log(channel);
});

Entering an open channel

A user must enter an open channel to receive messages. You may enter up to 10 open channels at once.

Entered open channels are valid only within the current connection. If you disconnect or reconnect to SendBird, you must re-enter channels to continue receiving messages.

sb.OpenChannel.getChannel(channelUrl, function (channel, error) {
    if (error) {
        console.error(error);
        return;
    }

    channel.enter(function(response, error){
        if (error) {
            console.error(error);
            return;
        }
    });
});

Exiting the open channel

To stop receiving messages from the open channel, you must exit the channel.

sb.OpenChannel.getChannel(channelUrl, function (channel, error) {
    if (error) {
        console.error(error);
        return;
    }

    channel.exit(function(response, error){
        if (error) {
            console.error(error);
            return;
        }
    });
});

Sending messages

In an entered channel, a user can send messages of the following types:

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.

You can additionally specify a customType to further subclassify a message. When you send a text message, you can additionally attach arbitrary strings via a data field. You can utilize this field to send structured data such as font sizes, font types, or custom JSON objects.

Delivery failures due to the network issues returns an exception. By implementing the callback below, it is possible to display only the messages that are successfully sent.

channel.sendUserMessage(message, data, customType, function(message, error){
    if (error) {
        console.error(error);
        return;
    }

    // onSent
    console.log(message);
});

A user can also send any binary file through SendBird. There are two ways in which you can send a binary file: by sending the file itself, or by sending a URL.

By sending a raw file, you are uploading it to the SendBird servers. Alternatively, you can choose to send a file hosted in your own servers by passing in a URL that points to the file. In this case, your file isn't hosted in the SendBird servers, and downloaded through your own servers instead.

Note: If you upload your file directly, a size limit is imposed per file. This limit depends on your plan, and can be viewed from your Dashboard. No file size limit is imposed if you send a file message via a URL. Then the file isn't uploaded to the SendBird servers.

// Sending file message with raw file
channel.sendFileMessage(file, data, customType, function(fileMessage, error){
    if (error) {
        console.error(error);
        return;
    }

    // onSent
    console.log(fileMessage);
});

// Sending file message with file URL
channel.sendFileMessage(fileUrl, name, type, size, data, customType, function(fileMessage, error){
    if (error) {
        console.error(error);
        return;
    }

    // onSent
    console.log(fileMessage);
});

Note: To send metadata along with a file, you can populate the data field.


Receiving messages

Messages can be received by adding a ChannelHandler. A received BaseMessage object is one of the following three message types.

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.
  • AdminMessage: message sent by an admin through the Platform API.

UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageReceived = function(channel, message){
    console.log(channel, message);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

Loading previous messages

You can load previous messages by creating a query using createPreviousMessageListQuery() and calling load(). You can display the past messages in your UI once they have loaded.

var messageListQuery = channel.createPreviousMessageListQuery();

messageListQuery.load(30, true, function(messageList, error){
    if (error) {
        console.error(error);
        return;
    }
    console.log(messageList);
});

Past messages are queried in fixed numbers (30 in the above code). A new PreviousMessageListQuery instance loads the most recent n messages. load() on the same query instance returns n messages before that. So if you store your query instance as a member variable, you can traverse through your entire message history.

Note: You must ensure that you have received a callback before calling load() again.


Loading messages by timestamp

You can query a set number of previous messages starting from the timestamp of the earliest message.

Note: The number of results may be larger than the set limit when there are multiple messages with the same timestamp as the earliest message.

var messageListQuery = channel.createMessageListQuery();

messageListQuery.prev(earliestMessageTimestamp, limit, reverseOrder, function(messageList, error){
    if (error) {
        console.error(error);
        return;
    }
    console.log(messageList);
});

Getting a list of participants in a channel

Participants are online users who are currently receiving all messages from the open channel.

var participantListQuery = channel.createParticipantListQuery();

participantListQuery.next(function (participantList, error) {
    if (error) {
        console.error(error);
        return;
    }
    console.log(participantList);
});

Getting participants' online statuses

To stay updated on each participant's connection status, you must obtain a new UserListQuery, which contains the lastest information on each user. To get a UserListQuery for a specific channel, call channel.createParticipantListQuery(). If you want to get the list of all users of your app, call sb.createUserListQuery().

You can then check each of the users' connection statuses by making calls to user.connectionStatus.

Note: If your app needs to keep track of users' connection statuses in real time, we recommend you to receive a new UserListQuery periodically, perhaps in intervals of one minute or more.

connectionStatus can return one of three values:

  • nonavailable: user's status information cannot be reached.
  • offline: user is disconnected from SendBird.
  • online: user is connected to SendBird.
var participantListQuery = openChannel.createParticipantListQuery();

participantListQuery.next(function (participantList, error) {
    if (error) {
        console.error(error);
        return;
    }
    console.log(participantList);
});

Getting a list of banned or muted users in a channel

You can also create a query to get a list of muted or banned users in an open channel. This query is only available for users who are registered as operators of the open channel.

var UserListQuery = openChannel.createBannedUserListQuery();  //or createMutedUserListQuery()

UserListQuery.next(function (userList, error) {
    if (error) {
        console.error(error);
        return;
    }

    console.log(userList);
});

Deleting messages

Users can delete messages. An error is returned if a user tries to delete messages sent by someone else. Also channel operators can delete any message in the channel, including those by other users.

Deleting a message fires a onMessageDeleted event to all other users in the channel.

channel.deleteMessage(message, function(response, error){
    if (error) {
        console.error(error);
        return;
    }
});

You can receive a onMessageDeleted event in the channel handler.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageDeleted = function (channel, messageId) {
    console.log('ChannelHandler.onMessageDeleted: ', channel, messageId);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

Open Channel: Advanced

This section explains the premium features of Open Channel. Some are available only to a paying user.


Admin messages

You can send an admin message to users in a channel using the SendBird Dashboard or the Platform API. To send the admin message via the Dashboard, in the Open Channels panel, select an open channel, find a message box below, click the Admin Message tab, and write a message in the box. The admin message is limited to 1000 characters.

If you are currently developing under the Free Plan and therefore cannot use the Moderation Tools from the Dashboard, you must send the admin messages through the Platform API.


Channel cover images

When creating a channel, you can add a cover image by specifying an image URL or file.

sb.OpenChannel.createChannel(name, coverUrl, data, function(createdChannel, error){
    if (error) {
        console.error(error);
        return;
    }
    // onCreated
});

You can retrieve the cover image URL with channel.coverUrl, and update the channel's cover image by calling update().


Custom channel types

When creating a channel, you can additionally specify a custom type to further subclassify your channels. This custom type takes on the form of a String, and can be handy in searching or filtering channels.

Note: data and customType are both String fields that allow you to append information to your channels. The intended use case is for customType to contain information that can subclassify the channel (for example, distinguishing "School" and "Work" channels). However, both these fields can be flexibly utilized.

sb.OpenChannel.createChannel(name, coverUrl, data, operatorUserIds, customType, function(createdChannel, error){
    if (error) {
        console.error(error);
        return;
    }

    // onCreated
});

To get a channel's custom type, call channel.customType


Custom message types

Likewise, you can specify a custom type for messages to categorize them into more specific groups. This custom type takes on the form of a String, and can be useful in searching or filtering messages.

Note: data and customType are both String fields that allow you to append information to your messages. The intended use case is for customType to contain information that can subclassify the message (for example, distinguishing "FILE_IMAGE" and "FILE_AUDIO" type messages). However, both these fields can be flexibly utilized.

To embed a custom type into a message, pass a String parameter to channel.sendUserMessage() or channel.sendFileMessage().

channel.sendUserMessage(message, data, customType, function(message, error){
    if (error) {
        console.error(error);
        return;
    }

    // onSent
});

To get a message's custom type, call message.customType.


Message auto-translation

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

SendBird makes it possible for messages to be sent in different languages through its auto-translation feature. Pass in a List of language codes to sendUserMessage() to request translated messages in the corresponding languages.

var targetLangList = ["es", "ko"];

channel.sendUserMessage(message, data, customType, targetLangList, function(message, error){
    if (error) {
        console.error(error);
        return;
    }

    // onSent
});

You can obtain translations of a message with userMessage.translations. This returns an Object containing the language codes and translations.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageReceived = function (channel, message) {
    var esTranslation = message.translations["es"];

    // Display translation in UI.
};

sb.addChannelHandler(UNIQUE_CHANNEL_ID, ChannelHandler);

Note: The message auto-translation supports 53 languages. For the language code table, see the Miscellaneous > Supported Languages.


You can search for specific channels by adding a keyword to your OpenChannelListQuery. There are two types of keywords: a Name Keyword and a URL Keyword.

Adding a Name Keyword to a query returns the list of open channels that have the keyword included in their names.

var openChannelListQuery = sb.OpenChannel.createOpenChannelListQuery();
openChannelListQuery.nameKeyword = "NameKeyword";

openChannelListQuery.next(function (channels, error) {
    if (error) {
        console.log(error);
        return;
    }

    // Returns a Array of channels that have "NameKeyword" in their names.
    console.log(channels);
});

Adding a URL Keyword to a query returns the open channel whose URL exactly matches the given keyword.

var openChannelListQuery = sb.OpenChannel.createOpenChannelListQuery();
openChannelListQuery.urlKeyword = "UrlKeyword";

openChannelListQuery.next(function (channels, error) {
    if (error) {
        console.log(error);
        return;
    }

    // Returns a List containing a single channel with the URL that matches the URL Keyword.
    console.log(channels);
});

File message thumbnails

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

When sending an image file, you can choose to create thumbnails of the image, which you can fetch and render into your UI. You can specify up to 3 different dimensions to generate thumbnail images in, which can be convenient for supporting various display densities.

Note: Supported file types are files whose media type is image/* or video/*. The SDK does not support creating thumbnails when sending a file message via a file URL.

Create a List of FileMessage.ThumbnailSize objects to pass to channel.sendFileMessage(). A ThumbnailSize can be created with the constructor ThumbnailSize(int maxWidth, int maxHeight), where the values specify pixels. The onSent() callback subsequently returns a List of Thumbnail objects that each contain the URL of the generated thumbnail image file.

var thumbnailSizes = [];
// Create and add ThumbnailSizes (Max: 3 ThumbnailSizes).
thumbnailSizes.push({'maxWidth': 100,'maxHeight': 100});
thumbnailSizes.push({'maxWidth': 200,'maxHeight': 200});

channel.sendFileMessage(file, data, customType, thumbnailSizes, function(fileMessage, error){
    if (error) {
        console.error(error);
        return;
    }

    var thumbnailFirst = fileMessage.thumbnails[0];
    var thumbnailSecond = fileMessage.thumbnails[1];

    var maxHeightFirst = thumbnailFirst.maxHeight; // 100
    var maxHeightSecond = thumbnailSecond.maxHeight; // 200

    var urlFirst = thumbnailFirst.url; // URL of first thumbnail file.
    var urlSecond = thumbnailSecond.url; // URL of second thumbnail file.
});

maxWidth and maxHeight specify the maximum dimensions of the thumbnail. Your image is resized evenly to fit within the bounds of (maxWidth, maxHeight). Note that if the original image is smaller than the specified dimensions, the thumbnail isn't resized. url returns the location of the generated thumbnail file within the SendBird servers.


Updating a user message

It is possible to modify a user message that has already been sent. To do so, you must know the messageId, which is a unique ID assigned to all messages within a channel.

channel.updateUserMessage(messageId, message, data, customType, function(userMessage, error) {
  if (error) {
    console.error(error);
    return;
  }

  // do something...
  console.log(userMessage);
});
Name Type Description
messageId number The unique ID of message.
message (optional) string The new message body.
data (optional) string The new data component.
customType (optional) string The new custom type.
callback Function A callback function that is executed when the update is complete.

Updating a file message

It is possible to modify a FileMessage that has already been sent. To do so, you must know the messageId, which is a unique ID assigned to all messages within a channel.

channel.updateFileMessage(messageId, data, customType, function(fileMessage, error) {
  if (error) {
    console.error(error);
    return;
  }

  // do something...
  console.log(fileMessage);
});
Name Type Description
messageId number The unique ID of message.
data (optional) string The new data component.
customType (optional) string The new custom type.
callback Function A callback function that is executed when the update is complete.

Receiving updated messages

You can receive an updated message through a ChannelHandler. UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageUpdated = function(channel, message){
  // do something...
  console.log(channel, message);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

When the UI isn't valid anymore, remove the channel handler.

sb.removeChannelHandler(UNIQUE_HANDLER_ID);

Checking file upload progress

You can check the progress of a file upload by passing a progressHandler as a parameter when calling sendFileMessage().

var sentFileMessage = channel.sendFileMessage(file, '', '', 
  function(event) { // check progress of upload request
    // do something...
    console.log(parseInt(Math.floor(e.loaded/e.total * 100)) + '%');
  },
  function(fileMessage, error) { // callback
    // do something...
    console.log(fileMessage, error);
  }
);

Canceling a FileMessage upload

You can cancel a file upload while it is not yet completed. If this function runs successfully, it returns true.

Note: If you attempt to cancel the uploading after it is already completed, or cancelled, or returned an error, the function returns false.

var sentFileMessage = channel.sendFileMessage(file, '', '', function(fileMessage, error) {
  // do something...
  console.log(fileMessage, error);
});

var cancelResult = channel.cancelUploadingFileMessage(sentFileMessage.reqId);
console.log(cancelResult);

Group Channel

Group Channel is a private chat. A user may join the chat only through an invitation by another user who is already a member of the chatroom. A group channel can consist of one to hundreds of members. Creating a channel with two members allows 1-to-1 messaging.

A user automatically receives all messages from the group channels that they are a member of.


Creating a group channel

A group channel can be created on demand by a user through the SendBird SDK.

Distinct property : A channel with the Distinct property turned on is always reused for the same members. If a new member is invited, or if a member leaves the channel, then the distinct property is disabled automatically. For example, in the case that a group channel with 3 members, A, B, and C, already exists, attempting to create a new channel with the same members just returns a reference to the existing channel.

Consequently, we recommend that you turn on the Distinct property in 1-to-1 messaging channels to reuse the same channel when a user chooses to directly message a friend. If the property is turned off, a new channel is created with the same friend even if there is a previous conversation between them, and you can't see previously sent messages or data.

var userIds = ['unique_user_id1', 'unique_user_id2'];
// distinct is false 
sb.GroupChannel.createChannelWithUserIds(userIds, false, name, cover_url, data, function(createdChannel, error) {
    if (error) {
        console.error(error);
        return;
    }

    console.log(createdChannel);
});

You can also append information by passing additional arguments.

var userIds = ['unique_user_id1', 'unique_user_id2'];

sb.GroupChannel.createChannelWithUserIds(userIds, distinct, name, coverUrl, data, customType, function(createdChannel, error) {
    if (error) {
        console.error(error);
        return;
    }

    console.log(createdChannel);
});
  • name: the name of a channel, or the channel topic.
  • distinct: whether the channel is Distinct.
  • coverUrl: the file or URL of the cover image, which you can fetch to render into the UI.
  • data: the String field to store structured information, such as a JSON String.
  • customType: the String field that allows you to subclassify your channel.

Note: See the Advanced section for more information on cover images and custom types.

You can also create channels via the SendBird Platform API. If you want to control channel creations and member invitations on the server-side, use the Platform API.


Getting a group channel instance with a URL

Since a channel URL is a unique identifier of a group channel, you can use a URL to retrieve a channel instance.

Store channel URLs to handle lifecycle or state changes in your app. For example, if a user disconnects from SendBird by temporarily switching to another app, you can provide a smooth restoration of the user's state using a stored URL to fetch the appropriate channel instance, then re-entering the user into the channel.

sb.GroupChannel.getChannel(channelUrl, function(channel, error) {
    if (error) {
        console.error(error);
        return;
    }

    // Successfully fetched the channel.
    console.log(channel);
});

Inviting users to an existing channel

Only members of the channel can invite new users into the channel.

You can determine whether the newly invited user sees the past messages in the channel or not. In your Dashboard Settings - Messages section, there is an option to show channel history. If this option is turned off, new users can view all messages sent before they have joined the channel. If not, new users can see only messages sent after they had been invited.

Note: By default, Show channel history is turned on.

groupChannel.inviteWithUserIds(userIds, function(response, error) {
    if (error) {
        console.error(error);
        return;
    }
});

Leaving the group channel

If a user leaves the group channel, the user can't receive messages from the channel anymore.

groupChannel.leave(function(response, error) {
    if (error) {
        console.error(error);
        return;
    }
});

Getting a list of my group channels

You can obtain a list of all group channels by creating a createMyGroupChannelListQuery(). The next() method returns a list of GroupChannel objects. You can also set an option to include empty channels.

Note: You can also set an option to include empty channels by setting includeEmpty = true. Empty channels are channels that have been created but contain no sent messages. By default, empty channels are not shown.

var channelListQuery = sb.GroupChannel.createMyGroupChannelListQuery();
channelListQuery.includeEmpty = true;
channelListQuery.limit = 20; // pagination limit could be set up to 100

if (channelListQuery.hasNext) {
    channelListQuery.next(function(channelList, error){
        if (error) {
            console.error(error);
            return;
        }

        console.log(channelList);
    });
}

Querying group channels by User IDs

It is possible to filter a channel search by user IDs. This can be done by creating a userIdsFilter.

Given an example where a user (with the ID "User") is part of two group channels:

  • channelA: [ "User", "John", "Jay" ]
  • channelB: [ "User", "John", "Jay", "Jin" ]

An ExactFilter returns the list of channels containing exactly the queried userIDs.

var channelListQuery = sb.GroupChannel.createMyGroupChannelListQuery();
var userIds = [];
userIds.push("John");
userIds.push("Jay");

channelListQuery.userIdsFilter = userIds;

if (channelListQuery.hasNext) {
    channelListQuery.next(function(channelList, error){
        if (error) {
            console.error(error);
            return;
        }

        // returns channelA only.
        console.log(channelList);
    });
}

An IncludeFilter returns channels where the userIDs are included. This method can return one of two different results, based on the paramater queryType.

var channelListQuery = sb.GroupChannel.createMyGroupChannelListQuery();
var userIds = [];
userIds.push("John");
userIds.push("Jay");
userIds.push("Jin");

channelListQuery.userIdsFilter = userIds;
channelListQuery.queryType = "AND";

if (channelListQuery.hasNext) {
    channelListQuery.next(function(channelList, error){
        if (error) {
            console.error(error);
            return;
        }

        // Returns only channelB that include the ids { John, Jay, Jin } as a subset.

    console.log(channelList);
    });
}

channelListQuery.queryType = "OR";

if (channelListQuery.hasNext) {
    channelListQuery.next(function(channelList, error){
        if (error) {
            console.error(error);
            return;
        }

        // Returns channelA and channelB that include { John }, plus channelA and channelB that include { Jay }, plus channelB that include { Jin }.
        // Actually channelA and channelB are returned.

        console.log(channelList);
    });
}

Querying group channels by name

It is possible to filter a channel search by channel name. This can be done by creating a channelNameContainsFilter.

Given an example where a channel’s name is ‘John Channel’. This filter returns the list of channels containing the queried channel name.

var channelListQuery = sb.GroupChannel.createMyGroupChannelListQuery();
channelListQuery.channelNameContainsFilter = 'John Channel';

if (channelListQuery.hasNext) {
    channelListQuery.next(function(channelList, error){
        if (error) {
            console.error(error);
            return;
        }

        console.log(channelList);
    });
}

Sending messages

In an entered channel, a user can send messages of the following types:

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.

You can additionally specify a customType to further subclassify a message. When you send a text message, you can additionally attach arbitrary strings via a data field. You can utilize this field to send structured data such as font size, font type, or a custom JSON object.

Delivery failures due to the network issues returns an exception. By receiving a callback within an implementation of sendUserMessage(), it is possible to display only the messages that are successfully sent.

channel.sendUserMessage(message, data, customType, function(message, error){
    if (error) {
        console.error(error);
        return;
    }

    console.log(message);
});

A user can also send any binary file through SendBird. There are two ways in which you can send a binary file: by sending the file itself, or by sending a URL.

By sending a raw file, you are uploading it to the SendBird servers. Alternatively, you can choose to send a file hosted in your own servers by passing in a URL that points to the file. In this case, your file is hosted in the SendBird servers, and downloaded through your own servers instead.

Note: If you upload your file directly, a size limit is imposed per file. This limit depends on your plan, and can be viewed from your Dashboard. No file size limit is imposed if you send a file message via a URL. Then the file isn't uploaded to the SendBird servers.

// Sending file message with raw file
channel.sendFileMessage(file, name, type, size, data, customType, function(fileMessage, error){
    if (error) {
        console.error(error);
        return;
    }
    console.log(fileMessage);
});

// Sending file message with file URL
channel.sendFileMessage(fileUrl, data, customType, function(fileMessage, error){
    if (error) {
        console.error(error);
        return;
    }
    console.log(fileMessage);
});

channel.sendFileMessage(fileUrl, name, type, size, data, customType, function(fileMessage, error){
    if (error) {
        console.error(error);
        return;
    }
    console.log(fileMessage);
});

Note: To send metadata along with a file, you can populate the data field.


Receiving messages

Messages can be received by adding a ChannelHandler. A received BaseMessage object is one of the following three message types.

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.
  • AdminMessage: message sent by an admin through the Platform API.

UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageReceived = function(channel, message){
    console.log(channel, message);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

When the UI isn't valid anymore, remove the channel handler.

sb.removeChannelHandler(UNIQUE_HANDLER_ID);

Loading previous messages

You can load previous messages by creating a query using createPreviousMessageListQuery() calling load(). You can display these messages in your UI once they have loaded.

Note: Whether a user can load messages prior to joining the channel depends on your settings. In your Dashboard Settings - Messages section, there is an option to show channel history. If this option is turned on, new users can view all messages sent before they have joined the channel. If not, new users can see only messages sent after they had been invited.

var messageListQuery = channel.createPreviousMessageListQuery();

messageListQuery.load(30, true, function(messageList, error){
    if (error) {
        console.error(error);
        return;
    }
    console.log(messageList);
});

Past messages are queried in fixed numbers (30 in the above code). A new PreviousMessageListQuery instance loads the most recent n messages. load() on the same query instance returns n messages before that. So if you store your query instance as a member variable, you can traverse through your entire message history.

Note: You must ensure that you have received a callback before calling load() again.


Deleting messages

Users can delete messages. An error is returned if a user tries to delete messages sent by someone else. Also channel operators can delete any message in the channel, including those by other users.

Deleting a message fires a onMessageDeleted event to all other users in the channel.

channel.deleteMessage(message, function(response, error){
    if (error) {
        console.error(error);
        return;
    }

});

You can receive a onMessageDeleted event using a ChannelHandler.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageDeleted = function (channel, messageId) {
    console.log('ChannelHandler.onMessageDeleted: ', channel, messageId);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

Group Channel: 1-to-1 Chat

A 1-to-1 chat is just a group channel with two members.


Creating a 1-to-1 chat

A group channel can be created on demand by a user through the client SDK. Pass in two user IDs to create a 1-to-1 chat between two users.

You typically want a 1-to-1 chat to be Distinct. If the Distinct property is turned off, the user can create a new channel with the same opponent, even if they have had previous conversations. In this case, multiple 1-to-1 chats between the same two users can exist, each with its own chat history and data.

// For typical 1-to-1 chat which is unique between two users
sb.GroupChannel.createChannelWithUserIds(['another_user_id'], true, name, coverFile, data, customType, function(createdChannel, error){
    if (error) {
        console.error(error);
        return;
    }

});
  • name: the name of a channel, or the channel topic.
  • distinct: whether the channel is Distinct. This must be true for 1-to-1 chats.
  • coverFile: the file or URL of the cover image, which you can fetch to render into the UI.
  • data: the String field to store structured information, such as a JSON String.
  • customType: the String field that allows you to subclassify your channel.

Note: See the Advanced section for more information on cover images and custom types.

You can also create channels via the SendBird Platform API. If you want to control channel creations and member invitations on the server-side, use the Platform API.

Group Channel: Advanced

This section explains the premium features of Group Channel. Some are available only to a paying user.


Getting a list of all channel members

You can obtain a list of members in a group channel by referencing members.

var members = groupChannel.members;

Members are automatically updated when you are online. If you disconnect from SendBird and reconnect, refresh() the channel to be updated with the latest information.

groupChannel.refresh(function(response, error){
    if (error) {
        console.error(error);
        return;
    }

    // onRefresh
});

Getting members' online statuses

To stay updated on each member's connection status, call channel.refresh() before accessing channel.members. You can then check each of the users' connection statuses by getting user.connectionStatus.

Note: If your app needs to keep track of users' connection statuses in real time, we recommend you to refresh() your channel instance periodically, perhaps in intervals of one minute or more.

connectionStatus can return one of three values:

  • nonavailable: user's status information cannot be reached.
  • offline: user is disconnected from SendBird.
  • online: user is connected to SendBird.

Typing indicators

You can send typing events by invoking startTyping and endTyping.

groupChannel.startTyping();
groupChannel.endTyping();

You can receive a onTypingStatusUpdated event in the channel handler.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onTypingStatusUpdated = function(channel){
    console.log(channel);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

Read receipts

A user can indicate that they have read a message by calling markAsRead().

groupChannel.markAsRead();

This broadcasts a onReadReceiptUpdated event, which can be handled with a ChannelHandler.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onReadReceiptUpdated = function(channel){
    console.log(channel);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

getReadReceipt(BaseMessage) returns the number of members in the channel who have not read the message.

var unreadCount = channel.getReadReceipt(message);

Admin messages

You can send an admin message to users in a channel using the SendBird Dashboard or the Platform API. To send the admin message via the Dashboard, in the Group Channels panel, select a group channel, find a message box below, click the Admin Message tab, and write a message in the box. The admin message is limited to 1000 characters.

If you are currently developing under the Free Plan and therefore cannot use the Moderation Tools from the Dashboard, you must send the admin messages through the Platform API.


Channel cover images

When creating a channel, you can add a cover image by specifying an image URL or file.

sb.GroupChannel.createChannel(name, coverUrl, data, function(channel, error){
    if (error) {
        console.error(error);
        return;
    }
});

You can retrieve the cover image URL with channel.coverUrl. You can also update a channel's cover image by calling update().


Custom channel types

When creating a channel, you can additionally specify a custom type to further subclassify your channels. This custom type takes on the form of a String, and can be handy in searching or filtering channels.

Note: data and customType are both String fields that allow you to append information to your channels. The intended use case is for customType to contain information that can subclassify the channel (for example, distinguishing "School" and "Work" channels). However, both these fields can be flexibly utilized.

// distinct is false
sb.GroupChannel.createChannel(users, false, name, coverUrl, data, customType, function(channel, error){
    if (error) {
        console.error(error);
        return;
    }

    console.log(channel);
});

To get a channel's custom type, call channel.customType.


Custom message types

Likewise, you can specify a custom type for messages to categorize them into more specific groups. This custom type takes on the form of a String, and can be useful in searching or filtering messages.

Note: DATA and CUSTOM_TYPE are both String fields that allow you to append information to your messages. The intended use case is for CUSTOM_TYPE to contain information that can subclassify the message (for example, distinguishing "FILE_IMAGE" and "FILE_AUDIO" type messages). However, both these fields can be flexibly utilized.

To embed a custom type into a message, pass a String parameter to channel.sendUserMessage() or channel.sendFileMessage().

channel.sendUserMessage(message, data, customType, function(response, error){
    if (error) {
        console.error(error);
        return;
    }
});

To get a message's custom type, call message.customType.


Message auto-translation

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

SendBird makes it possible for messages to be sent in different languages through its auto-translation feature. Pass in a List of language codes to sendUserMessage() to request translated messages in the corresponding languages.

var targetLanguages = ["es", "ko"];

channel.sendUserMessage(message, data, customType, targetLanguages, function(response, error){
    if (error) {
        console.error(error);
        return;
    }

    // onSent
});

You can obtain translations of a message using userMessage.translations. This method returns a Object containing the language codes and translations.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageReceived = function (channel, message) {
    var esTranslation = message.translations["es"];

    // Display translation in UI.
};

sb.addChannelHandler(UNIQUE_CHANNEL_ID, ChannelHandler);

Note: The message auto-translation supports 53 languages. For the language code table, see the Miscellaneous > Supported Languages.


File message thumbnails

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

When sending an image file, you can choose to create thumbnails of the image, which you can fetch and render into your UI. You can specify up to 3 different dimensions to generate thumbnail images in, which can be convenient for supporting various display densities.

Note: Supported file types are files whose media type is image/* or video/*. The SDK does not support creating thumbnails when sending a file message via a file URL.

Create ThumbnailSize object to pass to channel.sendFileMessage(). A ThumbnailSize can be created with object {'maxWidth', 'maxHeight'}, where the values specify pixels. The callback subsequently returns a Array of Thumbnail objects that each contain the URL of the generated thumbnail image file.

var thumbnailSizes = [];
// Create and add ThumbnailSizes (Max: 3 ThumbnailSizes).
thumbnailSizes.push({'maxWidth': 100,'maxHeight': 100});
thumbnailSizes.push({'maxWidth': 200,'maxHeight': 200});

channel.sendFileMessage(file, data, customType, thumbnailSizes, function(message, error){
    if (error) {
        console.error(error);
        return;
    }

    var thumbnailFirst = message.thumbnails[0];
    var thumbnailSecond = message.thumbnails[1];

    var maxHeightFirst = thumbnailFirst.maxHeight; // 100
    var maxHeightSecond = thumbnailSecond.maxHeight; // 200

    var urlFirst = thumbnailFirst.url; // URL of first thumbnail file.
    var urlSecond = thumbnailSecond.url; // URL of second thumbnail file.
});

maxWidth and maxHeight specify the maximum dimensions of the thumbnail. Your image is resized evenly to fit within the bounds of (maxWidth, maxHeight). Note that if the original image is smaller than the specified dimensions, the thumbnail isn't resized. url stores the location of the generated thumbnail file within the SendBird servers.


Updating a user message

It is possible to modify a user message that has already been sent. To do so, you must know the messageId, which is a unique ID assigned to all messages within a channel.

channel.updateUserMessage(messageId, message, data, customType, function(userMessage, error) {
  if (error) {
    console.error(error);
    return;
  }

  // do something...
  console.log(userMessage);
});
Name Type Description
messageId number The unique ID of message.
message (optional) string The new message body.
data (optional) string The new data component.
customType (optional) string The new custom type.
callback Function A callback function that is executed when the update is complete.

Updating a file message

It is possible to modify a file message that has already been sent. To do so, you must know the messageId, which is a unique ID assigned to all messages within a channel.

channel.updateFileMessage(messageId, data, customType, function(fileMessage, error) {
  if (error) {
    console.error(error);
    return;
  }

  // do something...
  console.log(fileMessage);
});
Name Type Description
messageId number The unique ID of message.
data (optional) string The new data component.
customType (optional) string The new custom type.
callback Function A callback function that is executed when the update is complete.

Receiving updated messages

You can receive an updated message through a ChannelHandler. UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageUpdated = function(channel, message){
  // do something...
  console.log(channel, message);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

When the UI isn't valid anymore, remove the channel handler.

sb.removeChannelHandler(UNIQUE_HANDLER_ID);

Checking file upload progress

You can check the progress of a file upload by passing a progressHandler as a parameter when calling sendFileMessage().

var sentFileMessage = channel.sendFileMessage(file, '', '', 
  function(event) { // check progress of upload request
    // do something...
    console.log(parseInt(Math.floor(e.loaded/e.total * 100)) + '%');
  },
  function(fileMessage, error) { // callback
    // do something...
    console.log(fileMessage, error);
  }
);

Canceling a file message upload

You can cancel a file upload while it is not yet complete. If this function runs successfully, it returns true.

Note: If you attempt to cancel the uploading after it is already completed, or cancelled, or returned an error, the function returns false.

var sentFileMessage = channel.sendFileMessage(file, '', '', function(fileMessage, error) {
  // do something...
  console.log(fileMessage, error);
});

var cancelResult = channel.cancelUploadingFileMessage(sentFileMessage.reqId);
console.log(cancelResult);

Channel Metadata

With metadata and metacounter, you can store additional information within a channel. The metadata allows you to store a Dictionary of String key-value pairs in a channel instance. If you want to store an integer with atomic increasing and decreasing operations, use the metacounter instead.

Use cases for metadata/metacounters could include tracking the number of likes, the background color, or a long description of the channel, which can each be fetched and rendered into the UI.


Metadata

Metadata is a Dictionary that is stored within a channel. Its uses are very flexible, allowing you to customize a channel to fit you and your users' needs.

Create

To store metadata into a channel, create a Dictionary, and then pass it as an argument when calling createMetaData(). You can store multiple key-value pairs in the map.

channel.createMetaData({ testData1: 'StringA', testData2: 'StringB' }, function(response, error){
    if (error) {
        console.log(error);
        return;
    }
});

Update

The process for updating metadata is identical to creation. Values are updated for existing keys, while new key-value pairs added.

channel.updateMetaData({ testData1: 'String1', testData2: 'String2', testData3: 'String3' }, function(response, error){
    if (error) {
        console.log(error);
        return;
    }
});

Get

To get stored metadata, create a Collection of keys, and then pass it as an argument to getMetaData(). The callback returns a Dictionary containing the corresponding key-value pairs.

channel.getMetaData(['testData1', 'testData2'], function(response, error){
        if (error) {
            console.log(error);
            return;
        }
});

Metacounter

A metacounter is a Map that is stored within a channel instance. Its primary uses are to track and update discrete indicators within a channel.

Create

To store a metacounter into a channel, create a Map, and then pass it as an argument when calling createMetaCounter(). You can store multiple key-value pairs in the map.

channel.createMetaCounters({ testData1: 1, testData2: 2 }, function(response, error){
    if (error) {
        console.log(error);
        return;
    }
});

Get

To get stored metacounters, create a Collection of keys and pass it as an argument to getMetaCounters(). The callback returns a Dictionary containing the corresponding key-value pairs.

channel.getMetaCounters(['testData1', 'testData2'], function(response, error){
    if (error) {
        console.log(error);
        return;
    }
});

Increase

The increase and decrease operations work similarly to getting metacounters, as described above. Create a Dictionary of keys to pass to increaseMetaCounters(), which increments the corresponding metacounters by 1.

var counters = {};
counters["key1"] = 2 ; // Increases by 2.
counters["key2"] = 3 ;  // Increases by 3.
channel.increaseMetaCounters(counters, function(response, error){
    if (error) {
        console.log(error);
        return;
    }
});

Decrease

Likewise, pass a Dictionary of keys to decreaseMetaCounters(), which decrements the metacounters by 1.

`javascript var counters = {}; counters["key1"] = 3 ; // Decreases by 2. counters["key2"] = 4 ; // Decreases by 3. channel.decreaseMetaCounters(counters, function(response, error){ if (error) { console.log(error); return; } });

Event Handler

Event Handlers are crucial components of the SendBird SDK that allow a client to react to server-side events. These handlers contain callback methods that can be overridden to respond to specific chat-related events passed from the server. For example, ChannelHandler.onMessageReceived(BaseChannel, BaseMessage) is triggered whenever a message is received. The specifics of each received message is contained within the BaseChannel and BaseMessage arguments passed in the triggering callback.

By providing its own Event Handlers, the SendBird SDK allows a client to respond to asynchronous events without worrying about the plethora of issues surrounding client-server communication and multithreading. A chat application especially involves rapid exchanges of data that must take place in near real-time across potentially thousands of users. Therefore, the SDK optimizes communication and threading to ensure data integrity between users and servers. Add Event Handlers and implement the necessary callback methods to track events occuring within channels or a user's own device.


Channel Handler

Register a ChannelHandler to receive information whenever events occur within a channel.

You can register multiple channel handlers. Each handler must have its unique identifier UNIQUE_HANDLER_ID. Typically, Event handlers are registered in each activity to stay up to date with changes in the channel, as well as notify the channel of the user's own activity.

var sb = new SendBird({ appId: appId });
var ChannelHandler = new sb.ChannelHandler();

ChannelHandler.onMessageReceived = function (channel, message) { }; // Received a chat message.
ChannelHandler.onMessageUpdated = function (channel, message) { }; // Received an updated chat message.
ChannelHandler.onMessageDeleted = function (channel, msgId) { };  // When a message has been deleted.
ChannelHandler.onChannelChanged = function (channel) { }; // When a channel property has been changed. More information on the properties can be found below.
ChannelHandler.onChannelDeleted = function (channelUrl, channelType) { };  // When a channel has been deleted.
ChannelHandler.onReadReceiptUpdated = function (groupChannel) { }; // When read receipt has been updated.
ChannelHandler.onTypingStatusUpdated = function (groupChannel) { }; // When typing status has been updated.
ChannelHandler.onUserJoined = function (groupChannel, user) { }; // When a new member joined the group channel.
ChannelHandler.onUserLeft = function (groupChannel, user) { }; // When a member left the group channel.
ChannelHandler.onUserEntered = function (openChannel, user) { }; // When a new user entered the open channel.
ChannelHandler.onUserExited = function (openChannel, user) { }; // When a new user left the open channel.
ChannelHandler.onUserMuted = function (openChannel, user) { }; // When a user is muted on the open channel.
ChannelHandler.onUserUnmuted = function (openChannel, user) { }; // When a user is unmuted on the open channel.
ChannelHandler.onUserBanned = function (openChannel, user) { }; // When a user is banned on the open channel.
ChannelHandler.onUserUnbanned = function (openChannel, user) { };  // When a user is unbanned on the open channel.
ChannelHandler.onChannelFrozen = function (openChannel) { }; // When the open channel is frozen.
ChannelHandler.onChannelUnfrozen = function (openChannel) { }; // When the open channel is unfrozen.
ChannelHandler.onChannelHidden = function (groupChannel) { }; // When the group channel is hidden.

ChannelHandler.onMetaDataCreated = function (channel, metaData) { }; // When metaData is created. 
ChannelHandler.onMetaDataUpdated = function (channel, metaData) { }; // When metaData is updated. 
ChannelHandler.onMetaDataDeleted = function (channel, metaDataKeys) { }; // When metaData is deleted.
ChannelHandler.onMetaCountersCreated = function (channel, metaCounter) { }; // When metaCounter is created. 
ChannelHandler.onMetaCountersUpdated = function (channel, metaCounter) { }; // When metaCounter is updated. 
ChannelHandler.onMetaCountersDeleted = function (channel, metaCounterKeys) { }; // When metaCounter is deleted. 

// Add this channel handler to SendBird object.
sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

onChannelChanged() is called whenever a one of the following channel properties have been changed:

  • Push preference
  • Last message (except in cases where the message is a silent Admin message)
  • Unread message count
  • Name, cover image, data, custom type
  • Operators (only applicable to open channels)
  • Distinct property (only applicable to group channels)

Where the activity isn't valid anymore, remove the channel handler.

sb.removeChannelHandler(UNIQUE_HANDLER_ID);

Connection Handler

Register a ConnectionHandler to detect changes in the user's own connection status.

You can register multiple Connection Handlers. Each handler must have its unique identifier UNIQUE_HANDLER_ID. Typically, connection handlers are registered in each activity to monitor the state of the user's connection with the SendBird servers.

var sb = new SendBird({ appId: appId })
var ConnectionHandler = new sb.ConnectionHandler();

ConnectionHandler.onReconnectStarted = function(){}; // Network has been disconnected. Auto reconnecting starts.
ConnectionHandler.onReconnectSucceeded = function(){}; // Auto reconnecting succeeded.
ConnectionHandler.onReconnectFailed = function(){}; // Auto reconnecting failed. You can call `reconnect()` to reset timer and restart reconnection to SendBird.

sb.addConnectionHandler(UNIQUE_HANDLER_ID, ConnectionHandler);

When the activity isn't valid anymore, remove the connection handler.

sb.removeConnectionHandler(UNIQUE_HANDLER_ID);

Miscellaneous

This section contains information for the following:

  • Client error codes
  • Server error codes
  • Supported languages

Client error codes

The following errors are six-digit integers beginning with 800.

Error Code Description
INVALID_INITIALIZATION 800100 Initialization failed
CONNECTION_REQUIRED 800101 Connection required
INVALID_PARAMETER 800110 Invalid parameters
NETWORK_ERROR 800120 Network error
NETWORK_ROUTING_ERROR 800121 Routing error
MALFORMED_DATA 800130 Malformed data
MALFORMED_ERROR_DATA 800140 Malformed error data
WRONG_CHANNEL_TYPE 800150 Wrong channel type
MARK_AS_READ_RATE_LIMIT_EXCEEDED 800160 Mark as read rate limit exceeded
QUERY_IN_PROGRESS 800170 Query is in progress
ACK_TIMEOUT 800180 Command ack timed out
LOGIN_TIMEOUT 800190 Login timed out
WEBSOCKET_CONNECTION_CLOSED 800200 Connection closed
WEBSOCKET_CONNECTION_FAILED 800210 Connection failed
REQUEST_FAILED 800220 Request failed
REQUEST_CANCELLED 800240 Request cancelled

Server error codes

The following errors are six-digit integers beginning with 400, 500, and 900.

Code Description
400100 Parameter Error - String value is required
400101 Parameter Error - Number value is required
400102 Parameter Error - List value is required
400103 Parameter Error - Json value is required
400104 Parameter Error - Boolean value is required
400105 Parameter Error - Not all the required fields are arrived
400106 Parameter Error - Value must be a positive number
400107 Parameter Error - Value must be a negative number
400108 User doesn't have an access to channels or messages
400110 Parameter Error - Length of value is not valid
400111 Parameter Error - Unknown
400112 Parameter Error - Should provide two different values
400151 Parameter Error - Not allowed characters
400201 Object(Channel/User/Message) not found
400202 Unique constraint violation
400300 User Authentication Error - Deactivated user
400301 User Authentication Error - Deleted user or user not found
400302 User Authentication Error - Invalid access token
400303 User Authentication Error - Unexpected error
400304 User Authentication Error - Application not found
400305 User Authentication Error - User id is too long
400306 User Authentication Error - Plan quota exceeded
400307 User Authentication Error - Requests from authorized domain
400601 The push token registration failure
400602 The push token removal failure
400910 Requests are rate-limited
400920 Tried to access non-allowed features under your plan
500901 Unexpected errors
900010 Try to send messages without login
900020 Try to send messages to group channels not belong to the user
900021 Try to send messages after getting deactivated
900030 Try to send messages to the channels when the guest policy is read-only on dashboard
900041 The user is muted on this channel
900050 User cannot send messages to frozen channels
900060 Message is blocked by profanity filter
900070 Try to send messages to deleted channels
900080 You cannot send messages on 1-on-1 group channel when receiver is blocked
900081 You cannot send messages on 1-on-1 group channel when receiver is deactivated
900100 Try to enter the banned channel
900200 You are blocked because you sent too many messages in short period

Supported Languages

SendBird provides message auto-translations for the languages listed in the following table.

Language Code Language Code
Afrikaans af Klingon (pIqaD) tlh-Qaak
Arabic ar Korean ko
Bosnian (Latin) bs-Latn Latvian lv
Bulgarian bg Lithuanian lt
Catalan ca Malay ms
Chinese Simplified zh-CHS Maltese mt
Chinese Traditional zh-CHT Norwegian no
Croatian hr Persian fa
Czech cs Polish pl
Danish da Portuguese pt
Dutch nl Querétaro Otomi otq
English en Romanian ro
Estonian et Russian ru
Finnish fi Serbian (Cyrillic) sr-Cyrl
French fr Serbian (Latin) sr-Latn
German de Slovak sk
Greek el Slovenian sl
Haitian Creole ht Spanish es
Hebrew he Swedish sv
Hindi hi Thai th
Hmong Daw mww Turkish tr
Hungarian hu Ukrainian uk
Indonesian id Urdu ur
Italian it Vietnamese vi
Japanese ja Welsh cy
Kiswahili sw Yucatec Maya yua
Klingon tlh - -

Change Log

If you click the link below, you can see a list of significant features and fixes added with each release of SendBird JavaScript SDK.

View the change log history