Moderate misbehaving users

Apart from moderation mechanisms designed for chat administrators, the Chat SDK provides moderation options for regular chat users. Users whose Chat SDK instances weren't initialized with the secretKey (as it's restricted to admins) can decide to hide messages from undesirable users.

The user IDs that a given chat user wants to hide messages from (mute them) are saved to a list. This mute list is soft-limited to 200 users and, by default, is only persisted for the duration of the user session.

You can decide to save and retrieve a local mute list during client initialization, effectively persisting the mute list beyond the scope of a single session, but then the hard 32KiB server data limit applies.

Mute list user limit

A persisted mute list can hold roughly up to 200 users (32KiB of data). If the size of the list exceeds that limit, the Chat SDK throws an HTTP 413 error and the list won't be persisted. The users will still be muted for the duration of the session.

All events and messages originating from a muted user are still received by the client, but are ignored. The mute list affects the following means of message delivery:

Requires App Context

To mute users, you must enable App Context for your app's keyset in the Admin Portal.

Mute users as a regular chat user

As a regular chat user, you can mute a specific user on all channels.

Method signature

Chat.MutedUsersManager.muteUser(userId: String): PNFuture<Unit>

Input

ParameterTypeRequiredDescription
userIdstringYesUser ID of the user you want to mute.

Output

This method returns a PNFuture<Unit> that succeeds when the data has been synced with the server. If syncMutedUsers is not enabled, the PNFuture<Unit> always succeeds.

Errors

If the size of the mute list exceeds 32KiB (roughly 200 users), you'll get the HTTP 413 (Request Entity Too Large) error.

Basic usage

import com.pubnub.chat.Chat
import com.pubnub.chat.config.ChatConfiguration

val chat = Chat.init(
ChatConfiguration(
publishKey = "demo",
subscribeKey = "demo",
userId = "myUniqueUserId"
)
)

val userToMute = "user_1905"

chat.mutedUsersManager.muteUser(userToMute).await()

Unmute users as a regular chat user

You can unmute a specific user on all channels. This removes the user from the mute list, allowing the client to see all messages and events originating from the user again.

Method signature

Chat.MutedUsersManager.unmuteUser(userId: String): PNFuture<Unit>

Input

ParameterTypeRequiredDescription
userIdstringYesUser ID of the user you want to unmute.

Output

This method returns a PNFuture<Unit> that succeeds when the data has been synced with the server. If syncMutedUsers is not enabled, the PNFuture<Unit> always succeeds.

Basic usage

import com.pubnub.chat.Chat
import com.pubnub.chat.config.ChatConfiguration

val chat = Chat.init(
ChatConfiguration(
publishKey = "demo",
subscribeKey = "demo",
userId = "myUniqueUserId"
)
)

val userToUnmute = "user_1905"

chat.mutedUsersManager.unmuteUser(userToUnmute).await()

Check muted users

You can check which users have been muted by inspecting the items in the mute list.

Method signature

Chat.MutedUsersManager.mutedUsers

Output

This property returns a Set<String> where each String is a user ID of a muted user.

Basic usage

import com.pubnub.chat.Chat
import com.pubnub.chat.config.ChatConfiguration

val chat = Chat.init(
ChatConfiguration(
publishKey = "demo",
subscribeKey = "demo",
userId = "myUniqueUserId"
)
)

val userToMute = "user_1905"

// Mute the user
chat.mutedUsersManager.muteUser(userToMute).await()
show all 20 lines

Persist the mute list

By default, the mute list is only persisted for the duration of the user session. You can save and retrieve the mute list during client initialization, effectively persisting the mute list by setting the syncMutedUsers parameter to true during client initialization.

Mute list and Access Manager

If you use Access Manager for user moderation within your chat app and syncMutedUsers is enabled, you must grant the Chat SDK user the following permissions:

  • read permission to the PN_PRV.$currentUserId.mute1 channel.
  • update, delete, and get permissions for the PN_PRV.$currentUserId.mute1 user.

Make sure to change $currentUserId to the user ID of the chat user that will use the mute list functionality.

Check restrictions

You can check if the chat administrator imposed any mute or ban restrictions for the following scenarios. Refer to the linked sections for more information.

Basic usage

Single user on a single channel
// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { userResult ->
userResult.onSuccess { user ->
if (user != null) {
// get the "support" channel
chat.getChannel("support").async { channelResult ->
channelResult.onSuccess { channel ->
if (channel != null) {
// get the channel restrictions for the user
user.getChannelRestrictions(channel).async { restrictionResult ->
restrictionResult.onSuccess { restriction ->
// handle the restriction object
}.onFailure {
// handle failure
}
show all 30 lines
All users on a single channel
// reference the "chat" object and invoke the "getChannel()" method
chat.getChannel("support").async { result ->
result.onSuccess { channel ->
if (channel != null) {
// fetch the user restrictions for the channel
channel.getUsersRestrictions().async { restrictionsResult ->
restrictionsResult.onSuccess { getRestrictionsResponse ->
// process the returned restrictions
for (restriction in getRestrictionsResponse.restrictions) {
if (restriction.mute || restriction.ban) {
// handle the restriction object (either muted or banned)
println("User ${restriction.userId} is restricted in channel ${channel.id}: mute=${restriction.mute}, ban=${restriction.ban}")
}
}
}.onFailure {
show all 27 lines
Single user on all channels
// reference the "chat" object and invoke the "getUser()" method
chat.getUser("support_agent_15").async { result ->
result.onSuccess { user ->
if (user != null) {
// fetch the channel restrictions for the user
user.getChannelsRestrictions().async { restrictionsResult ->
restrictionsResult.onSuccess { getRestrictionsResponse ->
// process the returned restrictions
for (restriction in getRestrictionsResponse.restrictions) {
if (restriction.mute || restriction.ban) {
// handle the restriction object (either muted or banned)
println("User is restricted on channel ${restriction.channelId}: mute=${restriction.mute}, ban=${restriction.ban}")
}
}
}.onFailure {
show all 27 lines

Secure moderation

Client-side restrictions can easily be bypassed if not secured with an additional server-side logic that uses Access Manager to allow or block user's access to PubNub resources (channels and users). This server-side can also be followed by additional client-side errors that inform app users about their restrictions up front.

Client-side restrictions

Once you enable and define server-side permissions with Access Manager, you can be sure that your muting and banning restrictions are always enforced.

Additionally, you can read moderation restrictions set with the Chat SDK methods also on your app's frontend to let a given user know upfront that they are muted on a channel or banned from accessing a channel using popup messages, iconography, etc. For example, before a user tries to write a message on a channel where they are muted and tries to search for the input field that is either greyed out or unavailable, you can display a popup message informing them about the restriction.

To let the client application react in real-time to changes in user permissions and present this information to the users effectively, the app needs to listen to and act on changes in moderation events:

  1. Listen for moderation events.

    Set up a listener to listen for the moderation event type ("banned," "muted," or "lifted") generated when UI restrictions are added or removed.

    val handleModerationEvent : (event: Event<EventContent.Moderation>) -> Unit
    // ...

    val unsubscribe = chat.listenForEvents(
    channelId = chat.currentUser.id,
    callback = handleModerationEvent
    )

    // ...
    // Remove the moderation event listener on cleanup
    unsubscribe.close()
  2. Act on moderation events.

    Update permissions in response to moderation events and generate new tokens if necessary.

    fun handleModerationEvent(event: Event<EventContent.Moderation>) {
    val restriction = event.payload.restriction
    val channelId = event.payload.channelId
    val reason = event.payload.reason

    // Handle different moderation events
    when (restriction) {
    RestrictionType.BAN -> {
    // Revoke specific permissions for banning
    println("User ${chat.currentUser.id} is banned on channel ${channelId}. Reason: ${reason ?: "N/A"}");

    // Revoke access rights specific to banning logic here
    // For example, you might remove write access

    }
    show all 33 lines
  3. Remove the event listener.

    // remember to call close when you're done 
    unsubscribe.close()
Last updated on