Mention users

The Mentions feature lets users tag specific individuals within a chat or conversation.

Kotlin Chat SDK lets one user tag another user by adding @ and typing at least three first letters of the username they want to mention. As a result, they get a list of suggested usernames when typing such a suggestion, like @Mar.

Generic referencing

Channel references, user mentions, and links are instances of MessageElement with different MentionTarget types.

The list of returned users depends on your app configuration - these can be either all members in the channel where you write a message or all users of your app (user data taken from the Admin Portal keyset for your app). The number of returned suggested users for the mention also depends on your app configuration and can show up to 100 suggestions. The names of the suggested users can consist of multiple words and contain up to 200 characters.

You can configure your app to let users mention up to 100 users in a single message (default value is 10).

You can implement mentions in your app in a similar way you would implement channel referencing and links.

Requires App Context

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

Add user mentions

You can let users mention other users in a draft message by adding @ and manually typing at least three first letters of the username they want to mention, like @Mar.

Whenever you mention a user, this user is added to the list of all mentioned users inside the MessageDraft object. This draft contains the text content and all mentioned users and their names from the selected user metadata source (all channel members or all users on the app's keyset). Once you send this message (send()), that information gets stored in the message metadata.

Method signature

You can add a user reference by calling the addMention() method with the target of MentionTarget.User.

Refer to the addMention() method for details.

Basic usage

Create the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention.

// create an empty message draft
val messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered = channel.type != ChannelType.PUBLIC)

// change the text
messageDraft.update(text = "Hello Alex! I have sent you this link on the #offtopic channel.")

// add a user mention to the string 'Alex'
messageDraft.addMention(offset = 6, length = 4, target = MentionTarget.User(userId = "alex_d"))

Remove user mentions

removeMention() lets you remove a previously added user mention from a draft message.

Method signature

You can remove user mentions from a draft message by calling the removeMention() method at the exact offset where the user mention starts.

Refer to the removeMention() method for details.

Offset value

If you don't provide the position of the first character of the message element to remove, it isn't removed.

Basic usage

Remove the user mention from the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention.

// assume the message reads
// Hello Alex! I have sent you this link on the #offtopic channel.`

// remove the channel reference
messageDraft.removeMention(offset = 6)

Get user suggestions

The message elements listener returns all users mentioned in the draft message that match the provided 3-letter string from a selected data source (channel members or global users on your app's keyset).

Single listener

The message elements listener returns suggested mentions for channel references, user mentions, and links.

For example, if you type Sam, you will get the list of users starting with Sam like Samantha or Samir. The default number of returned suggested usernames is 10 which is configurable to a maximum value of 100.

Method signature

You must add a message elements listener to receive user suggestions.

Refer to the addChangeListener() method for details.

Basic usage

// create a message draft
val messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered = channel.type != ChannelType.PUBLIC)

// add the listener
val listener = { elements: List<MessageElement>, suggestedMentions: PNFuture<List<SuggestedMention>> ->
updateUI(elements) // updateUI is your own function for updating UI
suggestedMentions.async { result ->
result.onSuccess { updateSuggestions(it) } // updateSuggestions is your own function for displaying suggestions
}
}
messageDraft.addChangeListener(listener)

Get mentioned users

To return all users mentioned in a message, use the getMessageElements() method.

Method signature

This method has the following signature:

message.getMessageElements(): List<MessageElement>

Input

This method doesn't take any parameters.

Output

TypeDescription
List<MessageElement>A list of message elements representing parsed components of the input text, including processed user mentions, links, and referenced channels based on the available data.
icon

MessageElement details

Basic usage

Check if the message with the 16200000000000000 timetoken contains any mentions.

chat.getChannel("incident-management").async { channelResult ->
channelResult.onSuccess { channel ->
// Successfully retrieved the channel
channel?.getMessage(16200000000000000L)?.async { messageResult ->
messageResult.onSuccess { message ->
// Handle success
val elements = message?.getMessageElements()

// Check if any elements represent user mentions
val hasMentions = elements?.any { element ->
// Assuming there's a specific type or condition for mentions
element is Link && element.target is User
} ?: false

if (hasMentions) {
show all 29 lines

The getCurrentUserMentions() method lets you collect in one place all instances when a specific user was mentioned by someone - either in channels or threads. You can use this info to create a channel with all user-related mentions.

Method signature

This method has the following signature:

chat.getCurrentUserMentions(
startTimetoken: Long?,
endTimetoken: Long?,
count: Int?
): PNFuture<GetCurrentUserMentionsResult>

Input

ParameterTypeRequiredDefaultDescription
startTimetokenLongNon/aTimetoken delimiting the start of a time slice (exclusive) to pull messages with mentions from. For details, refer to the Batch History section.
endTimetokenLongNon/aTimetoken delimiting the end of a time slice (inclusive) to pull messages with mentions from. For details, refer to the Batch History section.
countIntNo100Number of historical messages with mentions to return in a single call. Since each call returns all attached message reactions by default, the maximum number of returned messages is 100. For more details, refer to the description of the includeMessageActions parameter in the Kotlin SDK docs.

Output

ParameterTypeDescription
PNFuture<GetCurrentUserMentionsResult>objectReturned object containing two fields: enhancedMentionsData and isMore.
 → enhancedMentionsDataenhancedMentionsData (ChannelMentionData or ThreadMentionData)Array listing the requested number of historical mention events with a set of information that differ slightly depending on whether you were mentioned in the main (parent) channel or in a thread.

For mentions in the parent channel, the returned ChannelMentionData includes these fields: event (of type Event<EventContent.Mention>), channelId where you were mentioned, message that included the mention, userId that mentioned you.

For mentions in threads, the returned ThreadMentionData includes similar fields, the only difference is that you'll get parentChannelId and threadChannelId fields instead of just channelId to clearly differentiate the thread that included the mention from the parent channel in which this thread was created.
 → isMoreBooleanInfo whether there are more historical events to pull.

Basic usage

List the last ten mentions for the current chat user.

chat.getCurrentUserMentions(count = 10).async { mentionsResult ->
mentionsResult.onSuccess { mentions ->
// handle success
println("Last 10 mentions for the current user:")
mentions.data.forEach { mention ->
println("Message: ${mention.message.content}, Mentioned At: ${mention.message.timetoken}")
}
}.onFailure { exception ->
// handle failure
println("Error getting user mentions")
}
}

Show notifications for mentions

You can monitor all events emitted when you are mentioned in a parent or thread channel you are a member of using the listenForEvents() method. You can use this method to create pop-up notifications for the users.

Events documentation

To read more about the events of type mention, refer to the Chat events documentation.

Method signature

This method has the following parameters:

inline fun <reified T : EventContent> listenForEvents(
channel: String,
customMethod: EmitEventMethod?,
noinline callback: (event: Event<T>) -> Unit
): AutoCloseable {
return listenForEvents(T::class, channel, customMethod, callback)
}
Input
ParameterTypeRequiredDefaultDescription
Treified T : EventContentYesn/aReified type parameter bounded by the EventContent interface, allowing access to type information at runtime.
channelStringYesMentioned user IDChannel to listen for new mention events. By default, it's the current (mentioned) user's ID.
customMethodStringNon/aAn optional custom method for emitting events. If not provided, defaults to null.
callbacknoinline (event: Event<T>) -> UnitYesn/aA lambda function that is called with an Event<T> as its parameter. It defines the custom behavior to be executed whenever an mention event type is detected on the specified channel.
Output
TypeDescription
AutoCloseableInterface that lets you stop receiving moderation-related updates (moderation events) by invoking the close() method.

Basic usage

Print a notification for a mention of the current chat user on the support channel.

val user = chat.currentUser
chat.listenForEvents(user.id) { event: Event<EventContent.Mention> ->
if (event.payload.channel == "support") {
println("${user.id} has been mentioned on the support channel!")
}
}

Get mentioned users (deprecated)

You can access the mentionedUsers property of the Message object to return all users mentioned in a message.

Method signature

This is how you can access the property:

message.mentionedUsers

Basic usage

Check if the message with the 16200000000000000 timetoken contains any mentions.

channel.getMessage(16200000000000000).async { result ->
result.onSuccess { message: Message? ->
if (message != null) {
// Access the mentionedUsers property
val mentionedUsers = message.mentionedUsers

if (mentionedUsers.isNotEmpty()) {
println("The message contains the following mentioned users:")
mentionedUsers.forEach { user ->
println("User: ${user.name}")
}
} else {
println("The message does not contain any mentions.")
}
} else {
show all 21 lines
Last updated on