JavaScript
Open Channel

Open Channel

An open channel is basically a public chat and it can handle a large number of participants online. In this channel type, anyone can enter and participate in the chat without permission. A single open channel can accomodate up to 1,000, simultaneous users like Twitch-style public chat. This maximum number of an open channel's participants can increase per request.


Create a channel

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

  1. In your dashboard, go to the Application > Open channels panel, and then click Create channel at the top-right corner.
  2. 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 of a channel.)

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

Light Color Skin
Copy
OpenChannel.createChannel(NAME, COVER_IMAGE_OR_URL, DATA, OPERATOR_IDS, CUSTOM_TYPE, function(openChannel, error) {
    if (error) {
        return;
    }

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

When creating a channel, you can also append additional information like cover image and description by specifying several parameters.

ParameterTypeDescription

NAME

string

Specifies the channel topic, or the name of the channel.

COVER_IMAGE_OR_URL

string or File

Specifies the cover image URL of the channel, or uploads a file for the cover image.

DATA

string

Specifies additional data that you can store for the channel.

OPERATOR_IDS

string[]

Specifies an array of one or more IDs of the users to register as operators to the channel. Operators can delete any messages, and also view all messages in the channel without any filtering or throttling.

CUSTOM_TYPE

string

Specifies the custom channel type which is used for channel grouping.

function()

callback

Specifies the callback function which receives the response from SendBird server for a channel creation request.

Using the getCoverUrl() and updateChannel() methods, you can get and update the cover image URL of a channel.


Enter a channel

A user must enter an open channel to receive messages. The user can enter up to 10 open channels at once, which are valid only within a current connection. So when a user is disconnected from SendBird server with the disconnect() and reconnected to the server with the connect(), you should make sure the user re-enters the open channels for them to continue receiving messages.

Note: When a user is reconnected by attempts of the SendBird instance from a temporary unstable connection, the user is automatically re-entered into the participating channels.

Light Color Skin
Copy
sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) {
    if (error) {
        return;
    }

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

Exit a channel

If a user exits an open channel, the user can't receive any messages from that channel.

Light Color Skin
Copy
sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) {
    if (error) {
        return;
    }

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

Delete a channel

Only the operators of an open channel can delete the channel (the following code works properly in the operators' client apps only). Otherwise, an error is returned to a callback function.

Light Color Skin
Copy
sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) {
    if (error) {
        return;
    }
    
    openChannel.delete(function(response, error) {
        if (error) {
            return;
        }
    }
});

Freeze and unfreeze a channel

An open channel can be freezed only with the SendBird Dashboard or Platform API as opposed to a group channel which operators of the channel can do that via the SDKs.

To freeze, go to your dashboard and do the following: on the Application > Open channels panel, select an open channel to freeze, and click the Freeze icon at the upper right corner. To unfreeze, click the icon again with the frozen channel selected.

  • In a frozen channel, participants can't chat one another but the operators can send a message to the channel.

Retrieve a list of channels

You can retrive a list of OpenChannel objects using the next() method of an OpenChannelListQuery instance like the following.

Light Color Skin
Copy
var openChannelListQuery = sb.OpenChannel.createOpenChannelListQuery();

openChannelListQuery.next(function(openChannels, error) {
    if (error) {
        return;
    }

    console.log(openChannels);
});

Retrieve a channel by URL

Since a channel URL is a unique identifier of an open channel, you can use a URL when retrieving a channel object.

Light Color Skin
Copy
sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) {
    if (error) {
        return;
    }

    // TODO: Implement what is needed with the contents of the channel object.
    console.log(openChannel);
});

Note: We recommend that you store a user's channel URLs to handle the lifecycle or state changes of your app, or any other unexpected situations. For example, when a user is disconnected from SendBird server due to switching to another app temporarily, you can provide a smooth restoration of the user's state using a stored URL to fetch the appropriate channel instance.


Send a message

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

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

You can additionally specify a CUSTOM_TYPE 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.

Message delivery failures due to the network issues returns an exception. By implementing the callback function of the sendUserMessage() method, you can display messages that are successfully sent to a channel.

Light Color Skin
Copy
const params = new sb.UserMessageParams();

params.message = TEXT_MESSAGE;
params.customType = CUSTOM_TYPE;
params.data = DATA;
params.mentionType = 'users';                       // Either 'users' or 'channel'
params.mentionedUserIds = ['Jeff', 'Julia'];        // Or mentionedUsers = Array<User>;    
params.metaArrayKeys = ['linkTo', 'itemType'];
params.translationTargetLanguages = ['fe', 'de'];   // French and German
params.pushNotificationDeliveryOption = 'default';  // Either 'default' or 'suppress'

openChannel.sendUserMessage(params, function(message, error) {
    if (error) {
        return;
    }

    console.log(message);
});

A user can also send any binary file through the SDK. The two ways to send a binary file are provided: by sending the file itself, or by sending a URL.

Sending a raw file indicates that you upload it to SendBird server and it can be downloaded from the server when needed in client apps. As another option, you can choose to send a file hosted in your server by passing a URL that represents the location of the file as a parameter. In this case, your file isn't hosted on SendBird server, and can be downloaded only from your own server instead.

Note: If you upload a file directly, a size limit is imposed per file depending on your plan. You can see your limit in the dashboard and adjust the limit via our sales team. No file size limit is imposed if you send a file message with its URL since the file isn't uploaded to SendBird server.

Light Color Skin
Copy
// Sending a file message with a raw file
const params = new sb.FileMessageParams();

params.file = FILE;             // Or .fileUrl = FILE_URL (You can also send a file message with a file URL.)
params.fileName = FILE_NAME;
params.fileSize = FILE_SIZE;
params.thumbnailSizes = [{maxWidth: 100, maxHeight: 100}, {maxWidth: 200, maxHeight: 200}]; // Add the maximum sizes of thumbnail images (allowed number of thumbnail images: 3).
params.mimeType = MIME_TYPE;
params.customType = CUSTOM_TYPE;
params.data = DATA;
params.mentionType = 'users';                       // Either 'users' or 'channel'
params.mentionedUserIds = ['Jeff', 'Julia'];        // Or mentionedUsers = Array<User>;
params.metaArrayKeys = ['linkTo', 'itemType'];
params.translationTargetLanguages = ['fe', 'de'];   // French and German
params.pushNotificationDeliveryOption = 'default';  // Either 'default' or 'suppress'

openChannel.sendFileMessage(params, function(fileMessage, error) {
    if (error) {
        return;
    }

    console.log(fileMessage);
});

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


Receive messages through a channel event handler

Messages sent from other participants can be received through the onMessageReceived() method of a channel event handler. A BaseMessage object for each received message is one of the following three message types.

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

The UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

Light Color Skin
Copy
var ChannelHandler = new sb.ChannelHandler();

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

sb.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler);

Mention other participants in a message

When a participant wants to call the attention of other participants in an open channel where push notifications are not allowed by default, they can mention those participants in a message. To do so, you should:

  1. Specify a list of the user IDs to mention.
  2. Add the list to either UserMessageParams or FileMessageParams which may contain options for further action.
  3. Pass the params to either sendUserMessage() or sendFileMessage().
  4. Then only up to 10 participants mentioned in the message will be notified.
Light Color Skin
Copy
var params = new sb.UserMessageParams();
params.message = MESSAGE;
params.mentionedUserIds = ['Harry', 'Jay', 'Jin'];

openChannel.sendUserMessage(params, function(message, error) {
    if (error) {
        return;
    }
});

Load previous messages

After creating a query instance using the createPreviousMessageListQuery() method and using the load() method which returns a list of message objects, you can retrieve a set number of previous messages in an open channel. With a returned list, you can display the past messages in your UI once they have loaded.

Light Color Skin
Copy
// There should only be one single instance per channel view.
var messageListQuery = openChannel.createPreviousMessageListQuery();
messageListQuery.limit = LIMIT;
messageListQuery.reverse = REVERSE;

...

// Retrieving previous messages.
messageListQuery.load(function(messageList, error) {
    if (error) {
        return;
    }

    console.log(messageList);
});
ParameterTypeDescription

LIMIT

int

Specifies the number of results to return per call. Acceptable values are 1 to 100, inclusive. The recommended value for this parameter is 30.

REVERSE

boolean

Determines whether to sort the retrieved messages in the reversed order. If true, returns a list of messages which the latest comes at first and the earlist at last. the results are sorted in the reversed order. If false, returns a list of messages which the earlist comes at first and the latest at last.

A LIMIT parameter indicates how many messages should be included in a returned list. A query instance itself does pagination of a result set according to the value of the LIMIT parameter, and internally manages a token to retrieve the next page in the result set.

Each time the load() method is called, the instance retrieves a set number of messages in the next page and then updates the value of the token to complete the current call and prepare a next call.

If you create a new query instance and call the load() method, a set number of the most recently sent messages are retrieved because its token has nothing to do with the previously created instance. So we recommend that you create a single query instance and store it as a member variable for traversing through the entire message history.

Note: Before calling the load() method again, you must receive a success callback from the server.


Load messages by timestamp or message ID

You can retrieve a set number of messages sent previously before a specific timestamp in an open channel, using the getPreviousMessagesByTimestamp() method.

Note: The number of results can be larger than the set limit if there are multiple messages created at the same timestamp as the earliest message.

Light Color Skin
Copy
openChannel.getPreviousMessagesByTimestamp(TIMESTAMP, IS_INCLUSIVE, PREV_RESULT_SIZE, REVERSE, MESSAGE_TYPE, CUSTOM_TYPE, function(messages, error) {
    if (error) {
        return;
    }

    // A list of messages sent before the specified timestamp is successfully retrieved.
});
ParameterTypeDescription

TIMESTAMP

number

Specifies the timestamp to be the reference point of a retrieval, in Unix milliseconds.

IS_INCLUSIVE

boolean

Determines whether to include the messages sent exactly on the TIMESTAMP.

PREV_RESULT_SIZE

number

Specifies the number of messages to retrieve. Note that the actual number of results may be larger than the set value when there are multiple messages with the same timestamp as the earliest message.

REVERSE

boolean

Determines whether to sort the retrieved messages in the reversed order.

MESSAGE_TYPE

string

Specifies the message type to filter the messages with the corresponding type. Acceptable values are MESG, FILE, ADMM, or leaving it empty. If left empty, all types of messages are returned.

CUSTOM_TYPE

string

Specifies the custom message type to filter the messages with the corresponding custom type.

function()

callback

Specifies the callback function which receives the response from SendBird server for a message retrieval request.

Note: To retrieve messages sent after a specified timestamp, use the getNextMessagesByTimestamp() method in a similar fashion. Using the getPreviousAndNextMessagesByTimestamp() method, you can retrieve previous and next messages on both sides of a specific timestamp. See our API reference on the both methods.

You can also retrieve a set number of messages sent previously before a specific message ID in an open channel, using the getPreviousMessagesById() method.

Light Color Skin
Copy
openChannel.getPreviousMessagesByID(MESSAGE_ID, IS_INCLUSIVE, PREV_RESULT_SIZE, REVERSE, MESSAGE_TYPE, CUSTOM_TYPE, function(messages, error) {
    if (error) {
        return;
    }

    // A list of messages, the IDs of which are ahead of the specified message ID, is successfully retrieved.
});
ParameterTypeDescription

MESSAGE_ID

long

Specifies the unique ID of the message to be the reference point of a retrieval.

IS_INCLUSIVE

boolean

Determines whether to include the messages sent exactly on the TIMESTAMP.

PREV_RESULT_SIZE

number

Specifies the number of messages to retrieve. Note that the actual number of results may be larger than the set value when there are multiple messages with the same timestamp as the earliest message.

REVERSE

boolean

Determines whether to sort the retrieved messages in the reversed order.

MESSAGE_TYPE

string

Specifies the message type to filter the messages with the corresponding type. Acceptable values are MESG, FILE, ADMM, or leaving it empty. If left empty, all types of messages are returned.

CUSTOM_TYPE

string

Specifies the custom message type to filter the messages with the corresponding custom type.

function()

callback

Specifies the callback function which receives the response from SendBird server for a message retrieval request.

Note: To retrieve messages sent after a specific message ID, use the getNextMessagesById() method in a similar fashion. By using the getPreviousAndNextMessagesById() method, you can also retrieve previous and next messages on both sides of a specific message ID. See our API reference on the both methods.


Update a message

A user can update any of their own text and file messages sent. An error is returned if a user attempts to update another user's messages. In addition, channel operators can update any messages sent in a channel.

Light Color Skin
Copy
// For a text message
const params = new sb.UserMessageParams();

params.message = NEW_TEXT_MESSAGE;
params.customType = NEW_CUSTOM_TYPE;
params.data = NEW_DATA;

// The MESSAGE_ID below indicates the unique message ID of a UserMessage object to update.
openChannel.updateUserMessage(MESSAGE_ID, params, function(message, error) {
    if (error) {
        return;
    }
});

...

// For a file message
const params = new sb.FileMessageParams();

params.fileUrl = NEW_FILE_URL;      // The file in a message can't be updated.
params.fileName = NEW_FILE_NAME;
params.fileSize = NEW_FILE_SIZE;
params.data = NEW_DATA;

// The MESSAGE_ID below indicates the unique message ID of a FileMessage object to update.
openChannel.updateFileMessage(MESSAGE_ID, params, function(message, error) {
    if (error) {
        return;
    }
});

The onMessageUpdated() method of a channel event handler will receive a callback from the server when a message is updated, and all participants of the channel will be notified, including who has updated their own message.

Light Color Skin
Copy
var channelHandler = new sb.ChannelHandler();

channelHandler.onMessageUpdated = function(channel, message) {
    console.log('channelHandler.onMessageUpdated: ', channel, message);
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, channelHandler);

Delete a message

A user can delete any messages which were sent by themselves. An error is returned if a user attempts to delete the messages of other participants. Also channel operators can delete any messages in a channel.

Light Color Skin
Copy
// The MESSAGE below indicates a UserMessage or FileMessage object to delete.
openChannel.deleteMessage(MESSAGE, function(response, error) {
    if (error) {
        return;
    }
});

The onMessageDeleted() method of a channel event handler will receive a callback from the server when a message is deleted, and the result also notified to all other participants in the channel, including who has deleted their own message.

Light Color Skin
Copy
var channelHandler = new sb.ChannelHandler();

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

sb.addChannelHandler(UNIQUE_HANDLER_ID, channelHandler);

Retrieve a list of participants

You can retrieve a list of participants who are currently online and receiving all messages from an open channel.

Light Color Skin
Copy
var participantListQuery = openChannel.createParticipantListQuery();

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

    console.log(participantList);
});

Retrieve the latest information on participants

To retrieve the latest and updated information on each online participant in an open channel, you need another ParticipantListQuery instance for the channel. Like the Retrieve a list of participants section above, create a new query instance by using the channel.createParticipantListQuery(), and then call its next() method consecutively to retrieve the latest.

You can also retrieve the latest and updated information on users at the application level. Like the Retrieve a list of users section, create a new query instance by using the sb.createApplicationUserListQuery(), and then call its next() method consecutively to retrieve the latest.

When retrieving the online (connection) status of a user, by checking the connectionStatus of each user object in a returned list, you can get the user's current connection status. The connectionStatus property has one of the following two values:

  • offline: the user is not connected to SendBird server.
  • online: the user is connected to SendBird server.

Note: If you need to keep track of the connection status of some users in real time, we recommend that you call periodically the next() method of a ApplicationUserListQuery instance after specifying its userIdsFilter filter, perhaps in intervals of one minute or more.


Retrieve a list of operators

You can follow the simple implementation below to retrieve a list of operators who monitor and control the activities in an open channel.

Light Color Skin
Copy
sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) {
    if (error) {
        return;
    }
   
    // Retrieving a list of operators. 
    for(var operator in openChannel.operators) {
        ...
    }
});

Retrieve a list of banned or muted users

You can 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.

Light Color Skin
Copy
var bannedUserListQuery = openChannel.createBannedUserListQuery();

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

    console.log(userList);
});

var mutedUserListQuery = openChannel.createMutedUserListQuery();

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

    console.log(userList);
});

Ban and unban a user

Operators of an open channel can remove any users that behave inappropriately in the channel by using our Ban feature. Banned users are immediately expelled from a channel and allowed to participate in the channel again after the time period set by the operators. Operators can ban and unban users in open channels using the following code.

Light Color Skin
Copy
sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) {
    if (error) {
        return;
    }

    // Banning and unbanning a user 
    if (openChannel.isOperator(sb.getCurrentUser())) {
        openChannel.banUser(USER, SECONDS, function(response, error) {
            if (error) { 
                return;
            }
            
            // TODO: Custom implementation for what to do after banning.
        });

        openChannel.unbanUser(USER, function(response, error) {
            if (error) { 
                return;
            }
            
            // TODO: Custom implementation for what to do after unbanning.
        });
    }
});

Note: You can also use the banUserWithUserId() and unbanUserWithUserId() methods, instead of the banUser() and unbanUser(), as they have the same abilities. You can find more information on the banUserWithUserId() and unbanUserWithUserID() in our API reference.


Mute and unmute a user

Operators of an open channel can prohibit the selected users from sending messages using our Mute feature. Muted users remain in the channel and are allowed to view the messages, but can't send any messages until the operators unmute them. Operators can mute and unmute users in open channels using the following code:

Light Color Skin
Copy
sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) {
    if (error) {
        return;
    }

    // Muting and unmuting a user 
    if (openChannel.isOperator(sb.getCurrentUser())) {
        openChannel.muteUser(USER, function(response, error) {
            if (error) {
                return;
            }
            
            // TODO: Custom implementation for what to do after muting.
        });

        openChannel.unmuteUser(USER, function(response, error) {
            if (error) {
                return;
            }
            
            // TODO: Custom implementation for what to do after unmuting.
        });
    }
});

Note: You can also use the muteUserWithUserId() and unmuteUserWithUserId(), instead of the muteUser() and unmuteUser(), as they have the same abilities. You can find more information on the muteUserWithUserId() and unmuteUserWithUserID() in our API reference.


Report a message, a user, or a channel

In an open channel, a user can report suspicious or harrassing messages as well as the other users who use abusive language. The user can also report channels if there are any inappropriate content or activity within the channel. Based on this feature and our report API, you can build your own in-app system for managing objectionable content and subject.

Light Color Skin
Copy
// Reporting a message
openChannel.reportMessage(MESSAGE_TO_REPORT, REPORT_CATEGORY, DESCRIPTION, function(error) {
    if (error) {
        return;
    }
});

// Reporting a user
openChannel.reportUser(OFFENDING_USER, REPORT_CATEGORY, DESCRIPTION, function(error) {
    if (error) {
        return;
    }
});

// Reporting a channel
openChannel.report(REPORT_CATEGORY, DESCRIPTION, function(erorr) {
    if (error) {
        return;
    }
});
ParameterTypeDescription

MESSAGE_TO_REPORT

object

Specifies the message to report for its suspicious, harassing, or inappropriate content.

OFFENDING_USER

object

Specifies the user who uses offensive or abusive language such as sending explicit messages or inappropriate comments.

REPORT_CATEGORY

enum

Specifies a report category which indicates the reason for reporting. Acceptable values are limited to suspicious, harassing, inappropriate, and spam.

DESCRIPTION

string

Specifies additional information to include in the report.