JavaScript
Group Channel

Group Channel

A group channel is a chat that provides close interactions among limited number of users. It can be private or public. A private group channel can let a user join the chat through an invitation by another user who is already a member of the chatroom. For 1-on-1 messaging, you can create a private group channel with two members. A public group chat can let a user join the chat without invitation from others. A group channel can consist of one to one hundred members by default setting. This default number of members can increase per request.

A user can receive all messages from the group channels that they are a member of, and sends a message to those channels. They can also receive push notifications, typing indicators, unread counts and read receipts from the joined channels when they go offline. For more information, see the Push Notifications page which describes how to turn on and manage the push preference.


Choose a type of a channel

With our JavaScript SDK, you can use a variety of behaviour related properties when creating different types of group channels. You can create a group channel after configuring these properties.

Private vs. Public

A private group channel (default setting) can be accessed only by users that have accepted an invitation from an existing member of that group. On the other hand, a public group channel can be accessed by any user without an invitation, like an open channel.

Ephemeral vs. Persistent

Messages sent in an ephemeral group channel are not saved in the database of the SendBird system. Therefore, the old messages that scroll up beyond the user's display due to new messages can't be retrieved. On the other hand, messages sent in a persistent group channel (default setting) are stored permanently in the database.

1-on-1 vs. 1-on-N

A distinct group channel can be reused for the same users. If a user is invited as a new member, or if a member leaves the channel, then the distinct property is disabled automatically. For example, when attempting to create a new group channel with 3 users, A, B, and C, if a channel with same users already exists, a reference to the existing channel is just returned to who has attempted the new channel.

Consequently, we recommend that you turn on the distinct property in 1-on-1 messaging channels to reuse the existing channel when a user directly sends a message to another user. If the property is turned off, a new group channel is created with the same user even if there is a previous chat between them, and you can't see the old messages or data.


Create a channel

A user can create a group channel from inviting other users anytime in their client app. At the implemention level, you just need to write your code which passes the IDs of users to invite as a parameter to the creation method.

Before you write the code for creating a group channel for a typical 1-on-1 chat, you should make sure that you turn on the distinct property of the channel. Otherwise, if you turn off the distinct property, a new channel will be created with the same partner user even if there is already an existing channel between them. In this case, multiple 1-on-1 channels between the same two users can exist, each with its own chat history and data.

Note: If you want to retrieve a list of group channels, which also includes the current user's empty channels without any chat, you should set the includeEmpty option of MyGroupChannelListQuery instance for the retrieval.

Light Color Skin
Copy
var userIds = ['John', 'Harry'];
// When 'distinct' is false
sb.GroupChannel.createChannelWithUserIds(userIds, false, NAME, COVER_URL, DATA, function(groupChannel, error) {
    if (error) {
        return;
    }

    console.log(groupChannel);
});

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

Light Color Skin
Copy
var userIds = ['John', 'Harry'];

sb.GroupChannel.createChannelWithUserIds(userIds, DISTINCT, NAME, COVER_URL, DATA, CUSTOM_TYPE, function(groupChannel, error) {
    if (error) {
        return;
    }
    
    console.log(groupChannel);
});
  • NAME: the name of a channel, or the channel topic.
  • COVER_IMAGE_OR_URL: the file or URL of the cover image, which you can fetch to render into the UI.
  • DATA: the String field which can be a description of the channel or structured information such as a JSON string for other purposes.
  • CUSTOM_TYPE: the String field that allows you to subclassify your channel.

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

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

Otherwise, you can configure GroupChannelParams and create a new channel with that like below.

Light Color Skin
Copy
var params = new sb.GroupChannelParams();
params.isPublic = false;
params.isEphemeral = false;
params.isDistinct = false;
params.addUserIds(['John', 'Harry']);
params.operatorIds = ['Jay'];   // or .operators(Array<User>)
params.name = NAME;
params.channelUrl = UNIQUE_CHANNEL_URL; // In case of a group channel, you can create a new channel by specifying its unique channel URL in a 'GroupChannelParams' object. 
params.coverImage = FILE;       // or .coverUrl = COVER_URL;
params.data = DATA;
params.customType = CUSTOM_TYPE;

sb.GroupChannel.createChannel(params, function(groupChannel, error) {
    if (error) {
        return;
    }
    
    console.log(groupChannel);
});

Invite users as members

Only members of a group 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, go to the Settings > Application > Messages tab, and there is the Show channel history option. If the 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 have been invited.

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

Light Color Skin
Copy
var userIds = ['John', 'Harry'];

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

Accept or decline an invitation from other user

A user who is invited to a group channel can accept or decline the invitation. If a user accepts an invitation, they join the channel as a new member and can start chatting with other members. If a user declines an invitation, the invitation is cancelled.

Light Color Skin
Copy
// In case of accepting an invitation
groupChannel.acceptInvitation(function(response, error) {
    if (error) {
        return;
    }
});

// In case of declining an invitation
groupChannel.declineInvitation(function(response, error) {
    if (error) {
        return;
    }
});

By implementing the onUserReceivedInvitation() and onUserDelclinedInvitation() of a channel event handler, you can make the client apps of other members in the foreground to be notified of the results of two actions above. For more information, see the Event Handler page.

Note: Using the setChannelInvitationPreference(), you can determine for users within an application whether or not to automatically join a private group channel promptly from an invitation without having to accept it. By default, the value of channel invitation preference is true. If you want to give them the ability to decide whether to accept or decline an invitation, you should set the preference's value to false via the setChannelInvitationPreference() like the following sample code.

Light Color Skin
Copy
var autoAccept = false; // The value of `true` (default) means that a user will automatically join a group channel with no choice of accepting and declining an invitation.

sb.setChannelInvitationPreference(autoAccept, function(response, error) {
    if (error) {
        return;
    }
});

Join a channel as a member

This is only for public group channels. Any user can join a public group channel as a member without an invitation and chat with other members in the channel.

Light Color Skin
Copy
if (groupChannel.isPublic) {
    groupChannel.join(function(response, error) {
        if (error) {
            return;
        }
    });
}

Leave a channel

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

Light Color Skin
Copy
groupChannel.leave(function(response, error) {
    if (error) {
        return;
    }
});

Freeze and unfreeze a channel

You can temporarily disable various functions of a group channel to stop members from chatting in the channel, and enable the functions so that the members chat with each other. Note that in a frozen channel, normal members can't chat each other but the operators can send a message to the channel.

Light Color Skin
Copy
// In case of freezing a channel
groupChannel.freeze(function(response, error) {
    if (error) {
        return;
    }

    // Custom implementation for what should be done after freezing.
});

// In case of unfreezing a channel
groupChannel.unfreeze(function(response, error) {
    if (error) {
        return;
    }

    // Custom implementation for what should be done after unfreezing.
});

Retrieve a list of channels

After creating a query instance from the createMyGroupChannelListQuery() and using the instance's next() method which returns a list of group channel objects, you can get a list of the current user's joined channels.

Note: Using the includeEmpty option of a MyGroupChannelListQuery instance, you can determine whether or not to include empty channels in the result. The empty channels indicate group channels that have been created but currently contain no messages. By default, empty channels are not included (not displayed).

Light Color Skin
Copy
var channelListQuery = sb.GroupChannel.createMyGroupChannelListQuery();
channelListQuery.includeEmpty = true;
channelListQuery.limit = 20;    // The value of pagination limit could be set up to 100.

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

        console.log(channelList);
    });
}

Retrieve a channel by URL

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

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

    console.log(groupChannel);

    // Successfully fetched the channel.
    // Do something with groupChannel.
});

Note: We recommend that you store a user's channel URLs to handle the lifecycle or state changes of your app, or 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.


Hide or archive a channel from a list of channels

The following code will allow you to hide or archive a specific group channel from a list of the channels.

Light Color Skin
Copy
groupChannel.hide(IS_HIDE_PREVIOUS_MESSAGES, IS_ALLOW_AUTO_UNHIDE, function(response, error) {
    if (error) {
        return;
    }
});

groupChannel.unhide(function(response, error) {
    if (error) {
        return;
    }
});
  • IS_HIDE_PREVIOUS_MESSAGES: when the channel gets appeared back in the list, determines whether to conceal the messages sent and received before hiding or archiving the channel. If set to true, the previous messages aren't displayed in the channel. (Default: false)
  • IS_ALLOW_AUTO_UNHIDE: determines the state and operating behavior of the channel in the list. If set to true, the channel is hidden from the list, automatically gets unhidden when receiving a new message from other members of the channel, and appears back. If set to false, the channel is archived and disappeared from the list, and never appears back unless the unhide() is called for unarchiving.

Using the channel.hiddenState, you can check the channel state with regard to the list.

Light Color Skin
Copy
if (groupChannel.hiddenState === sb.GroupChannel.HiddenState.UNHIDDEN) {
        // The channel is displayed in the list.
} else if (groupChannel.hiddenState === sb.GroupChannel.HiddenState.HIDDEN_ALLOW_AUTO_UNHIDE) {
        // The channel is hidden from the list, and appears in the list on condition.
} else if (groupChannel.hiddenState === sb.GroupChannel.HiddenState.HIDDEN_PREVENT_AUTO_UNHIDE) {
        // The channel is archived, and appears only when the unhide() is called.
}

You can also filter channels by their state like the following:

Light Color Skin
Copy
var filteredQuery = sb.GroupChannel.createMyGroupChannelListQuery();
filteredQuery.includeEmpty = true;
filteredQuery.hiddenChannelFilter = sb.GroupChannel.HiddenChannelFilter.HIDDEN_PREVENT_AUTO_UNHIDE; 
// The filter options are limited to `UNHIDDEN`, `HIDDEN`, `HIDDEN_ALLOW_AUTO_UNHIDE`, or `HIDDEN_PREVENT_AUTO_UNHIDE`.
// If set to `HIDDEN`, hidden and archived channels are returned.
filteredQuery.next(function(grouChannels, error) {
    if (error) {
        return;
    }
    // Only archived group channels are returned.
});

Filter channels by user IDs

To filter group channels by user ID, use the userIdsExactFilter or userIdsIncludeFilter. Given an example where a user (with the ID 'Harry') is part of two group channels:

  • channelA: {'Harry', 'John', 'Jay'}
  • channelB: {'Harry', 'John', 'Jay', 'Jin'}

A userIdsExactFilter returns a list of the current user's group channels containing exactly the queried user IDs. In case you specify only one user ID in the filter, the filter returns a list of the current user's one (distinct) or more 1-on-1 group channels with the specified user.

Light Color Skin
Copy
var filteredQuery = sb.GroupChannel.createMyGroupChannelListQuery();
filteredQuery.userIdsExactFilter = ['John', 'Jay'];
filteredQuery.next(function(groupChannels, error) {
    ...
    // Only 'channelA' is returned.
});

A userIdsIncludeFilter returns a list of the current user's group channels including the queried user IDs partially and exactly. Two different results can be retruend based on the parameter queryType.

Light Color Skin
Copy
var filteredQuery = sb.GroupChannel.createMyGroupChannelListQuery();
filteredQuery.userIdsIncludeFilter = ['John', 'Jay', 'Jin'];
filteredQuery.next(function(groupChannels, error) {
    ...
    // Only 'channelB' that include the ids {'John', 'Jay', 'Jin'} as a subset is returned.
});

filteredQuery.queryType = sb.GroupChannelListQuery.QueryType.OR;
filteredQuery.next(function(groupChannels, err) {
    ...
    // 'channelA' and 'channelB' that include {'John'}, plus 'channelA' and 'channelB' that include {'Jay'}, plus 'channelB' that include {'Jin'}.
    // Actually 'channelA' and 'channelB' are returned.
});

Send a message

Upon joining a group 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 size, font type, or a custom JSON object.

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' 

groupChannel.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 on 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 (You can 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'

groupChannel.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 members 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.

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);

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

Light Color Skin
Copy
sb.removeChannelHandler(UNIQUE_HANDLER_ID);

Mention other members in a message

When a member wants to call the attention of other members of a group channel, they can mention those members 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 = 'Hi, guys!';
params.mentionedUserIds = ['John', 'Harry', 'Jay', 'Jin'];

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

Load previous messages

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

Note: You can determine whether a user can load previous messages sent before their joining the channel. In your dashboard, go to the Settings > Application > Messages tab, there is the Show channel history option. 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 have been invited.

Light Color Skin
Copy
var prevMessageListQuery = groupChannel.createPreviousMessageListQuery();
prevMessageListQuery.limit = 30;
prevMessageListQuery.reverse = true;

prevMessageListQuery.load(function(messages, error) {
    if (error) {
        return;
    }
    
    console.log(messages);
});

A limit parameter (30 in the above sample code) indicates how many messages should be included in a list. A query instance itself does pagination of a result set based on 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 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 invoking the load() method again, you must receive its callback first.


Load messages by timestamp or message ID

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

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

    // A list of messages sent before timestamp is successfully retrieved.
    console.log(messages);
});
  • TIMESTAMP (long): the timestamp to be the reference point of a retrieval, in Unix milliseconds.
  • IS_INCLUSIVE (boolean): whether or not to include messages sent exactly at TIMESTAMP.
  • PREV_RESULT_SIZE (int): the number of messages to load. 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): whether or not to reverse the results.
  • MESSAGE_TYPE (enum): the message filtering option for the BaseChannel.MessageTypeFilter. The possible values are limited to MessageTypeFilter.ALL, MessageTypeFilter.USER, MessageTypeFilter.FILE, or MessageTypeFilter.ADMIN.
  • CUSTOM_TYPE (**string): the custom message type to filter the messages with that custom type.

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 a group channel, using the getPreviousMessagesById() method.

Light Color Skin
Copy
groupChannel.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.
});
  • MESSAGE_ID (long): the unique ID of the message to be the reference point of a retrieval.
  • IS_INCLUSIVE (boolean): whether or not to include messages sent exactly at MESSAGE_ID.
  • PREV_RESULT_SIZE (int): the number of messages to load. 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): whether or not to reverse the results.
  • MESSAGE_TYPE (enum): the message filtering option for the BaseChannel.MessageTypeFilter. The possible values are limited to MessageTypeFilter.ALL, MessageTypeFilter.USER, MessageTypeFilter.FILE, or MessageTypeFilter.ADMIN.
  • CUSTOM_TYPE (string): the custom message type to filter the messages with that custom type.

Note: To retrieve messages sent after a specific message ID, use the getNextMessagesById() method in a similar way. 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
// In case of a user message
groupChannel.updateUserMessage(MESSAGE_ID, BODY, DATA, CUSTOM_TYPE, function(message, error) {
    if (error) {
        return;
    }
});

// In case of a file message
groupChannel.updateFileMessage(MESSAGE_ID, BODY, DATA, CUSTOM_TYPE, 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 members of the channel will be notified, including who has updated their own message.

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

handler.onMessageUpdated = function(channel, message) {
    ...
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, handler);
});

Delete a message

A user can delete their own messages. An error is returned if a user attempts to delete messages sent by others. Also operators of a channel can delete any messages in a channel.

Light Color Skin
Copy
groupChannel.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 members in the channel, including who has deleted their own message.

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

handler.onMessageDeleted = function(channel, messageId) {
        ...
};

sb.addChannelHandler(UNIQUE_HANDLER_ID, handler);

Clear the chat history

By using the resetMyHistory() method, you can help the current user clear the chat history in a group channel and start a fresh conversation with other members in the same channel. As the method's name implies, the chat history will be cleared only from the channel view of the current user, and will no longer be shown in that view. But the messages are not deleted from the database of the SendBird system, and other members can still see all the messages in their channel views.

This method simply clears the messages for the user by updating the lastMessage and readReceipt properties of a group channel object in addition to other internally managed data such as the number of the user’s unread message.

Note: This ability is effective only when the Show Channel History option is turned on in your dashboard: Settings > Messages > Show Channel History.

Light Color Skin
Copy
groupChannel.resetMyHistory(function(response, error) {
    if (error) {
        return;
    }
});

When a user is online, all data associated with the group channels they are a member of are automatically updated. However, when a user is disconnected from SendBird server and reconnects later, you should call the refresh() method to update the user's group channels with the latest information.

Light Color Skin
Copy
groupChannel.refresh(function(response, error) {
    if (error) {
        return;
    }
});

Note: If you want to make your users see the channels updated to the most recent when their client apps are in the foreground, we recommend you call the refresh() within the onReconnectSucceeded() method which receives a callback from SendBird server when successfully reconnected.


Retrieve a list of all members

You can retrieve a list of members in a group channel using members.

Light Color Skin
Copy
groupChannel.members;

Members of a channel are automatically updated when a user is online. But when a user is disconnected from SendBird server and then reconnected, you should call the refresh() method to update the user's group channels with the latest information. See the Refresh all data related to a group channel section for the sample code.


Retrieve the online status of members

To stay updated on each member's connection status in a group channel, call the refresh() method before calling the members to retrieve the members of the channel.

By calling user.connectionStatus at each User object in a list which the members returns, you can check user's current connection status. The connectionStatus has one of the following two values:

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

Retrieve a list of banned or muted users

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

Light Color Skin
Copy
// In case of retrieving banned users
var bannedUserListQuery = groupChannel.createBannedUserListQuery();
bannedUserListQuery.next(function(users, error) {
    if (error) {
        return;
    }
});

// In case of retrieving muted users
var memberUserListQuery = groupChannel.createMemberListQuery();
memberUserListQuery.mutedMemberFilter = 'muted';
memberUserListQuery.next(function(users, error) {
    if (error) {
        return;
    }
});

Ban and unban a user

Operators of a group 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 join the channel again after the time period set by the operators. The operators can ban and unban users in group channels using the following code.

Light Color Skin
Copy
sb.GroupChannel.getChannel(channelUrl, function(groupChannel, error) {
    if (error) {
        return;
    }

    // Ban and unban a user 
    if (groupChannel.myRole === sb.Member.Role.OPERATOR) {
        groupChannel.banUser(USER, SECONDS, DESCRIPTION, function(response, error) {
            if (error) {
                return;
            }

            // Custom implementation for what should be done after banning.

        });

        groupChannel.unbanUser(USER, function(response, error) {
            if (error) {
                return;
            }

            // Custom implementation for what should be done 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 a group 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. The operators can mute and unmute users in group channels using the following code:

Light Color Skin
Copy
sb.GroupChannel.getChannel(channelUrl, function(groupChannel, error) {
    if (error) {
        return;
    }

    // Mute and unmute a user 
    if (groupChannel.myRole === sb.Member.Role.OPERATOR) {
        groupChannel.muteUser(USER, function(response, error) {
            if (error) {
                return;
            }

            // Custom implementation for what should be done after muting.
        });

        groupChannel.unmuteUser(USER, function(response, error) {
            if (error) {
                return;
            }

            // Custom implementation for what should be done 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.