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.
Sample code
Create the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention.
1// create an empty message draft
2val messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered = channel.type != ChannelType.PUBLIC)
3
4// change the text
5messageDraft.update(text = "Hello Alex! I have sent you this link on the #offtopic channel.")
6
7// add a user mention to the string 'Alex'
8messageDraft.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.
Sample code
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.
1// assume the message reads
2// Hello Alex! I have sent you this link on the #offtopic channel.`
3
4// remove the channel reference
5messageDraft.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.
Sample code
1// create a message draft
2val messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered = channel.type != ChannelType.PUBLIC)
3
4// add the listener
5val listener = { elements: List<MessageElement>, suggestedMentions: PNFuture<List<SuggestedMention>> ->
6        updateUI(elements) // updateUI is your own function for updating UI
7        suggestedMentions.async { result ->
8            result.onSuccess { updateSuggestions(it) } // updateSuggestions is your own function for displaying suggestions
9        }
10    }
11messageDraft.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:
1message.getMessageElements(): List<MessageElement>
Input
This method doesn't take any parameters.
Output
| Type | Description | 
|---|---|
| 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. | 
Sample code
Check if the message with the 16200000000000000 timetoken contains any mentions.
1chat.getChannel("incident-management").async { channelResult ->
2    channelResult.onSuccess { channel ->
3        // Successfully retrieved the channel
4        channel?.getMessage(16200000000000000L)?.async { messageResult ->
5            messageResult.onSuccess { message ->
6                // Handle success
7                val elements = message?.getMessageElements()
8
9                // Check if any elements represent user mentions
10                val hasMentions = elements?.any { element ->
11                    // Assuming there's a specific type or condition for mentions
12                    element is Link && element.target is User
13                } ?: false
14
15                if (hasMentions) {
Collect all user-related mentions
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:
1chat.getCurrentUserMentions(
2    startTimetoken: Long?,
3    endTimetoken: Long?,
4    count: Int?
5): PNFuture<GetCurrentUserMentionsResult>
Input
| Parameter | Description | 
|---|---|
| startTimetokenType:  LongDefault: n/a | Timetoken delimiting the start of a time slice (exclusive) to pull messages with mentions from. For details, refer to the Batch History section. | 
| endTimetokenType:  LongDefault: n/a | Timetoken delimiting the end of a time slice (inclusive) to pull messages with mentions from. For details, refer to the Batch History section. | 
| countType:  IntDefault: 100 | Number of historical messages with mentions to return in a single call. Since each call returns all attached message actions by default, the maximum number of returned messages is 100. For more details, refer to the description of theincludeMessageActionsparameter in the Kotlin SDK docs. | 
Output
| Parameter | Description | 
|---|---|
| PNFuture<GetCurrentUserMentionsResult>Type:  object | Returned object containing two fields: enhancedMentionsDataandisMore. | 
| → enhancedMentionsDataType:  enhancedMentionsData(ChannelMentionDataorThreadMentionData) | 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 ChannelMentionDataincludes these fields:event(of typeEvent<EventContent.Mention>),channelIdwhere you were mentioned,messagethat included the mention,userIdthat mentioned you.For mentions in threads, the returned ThreadMentionDataincludes similar fields, the only difference is that you'll getparentChannelIdandthreadChannelIdfields instead of justchannelIdto clearly differentiate the thread that included the mention from the parent channel in which this thread was created. | 
| → isMoreType:  Boolean | Info whether there are more historical events to pull. | 
Sample code
List the last ten mentions for the current chat user.
1chat.getCurrentUserMentions(count = 10).async { mentionsResult ->
2    mentionsResult.onSuccess { mentions ->
3        // handle success
4        println("Last 10 mentions for the current user:")
5        mentions.data.forEach { mention ->
6            println("Message: ${mention.message.content}, Mentioned At: ${mention.message.timetoken}")
7        }
8    }.onFailure { exception ->
9        // handle failure
10        println("Error getting user mentions")
11    }
12}
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:
1inline fun <reified T : EventContent> listenForEvents(
2    channel: String,
3    customMethod: EmitEventMethod?,
4    noinline callback: (event: Event<T>) -> Unit
5): AutoCloseable {
6    return listenForEvents(T::class, channel, customMethod, callback)
7}
Input
| Parameter | Description | 
|---|---|
| T*Type:  reified T : EventContentDefault: n/a | Reified type parameter bounded by the EventContentinterface, allowing access to type information at runtime. | 
| channel*Type:  StringDefault: Mentioned user ID | Channel to listen for new mentionevents. By default, it's the current (mentioned) user's ID. | 
| customMethodType:  StringDefault: n/a | An optional custom method for emitting events. If not provided, defaults to null. | 
| callback*Type:  noinline (event: Event<T>) -> UnitDefault: n/a | A lambda function that is called with an Event<T>as its parameter. It defines the custom behavior to be executed whenever anmentionevent type is detected on the specified channel. | 
Output
| Type | Description | 
|---|---|
| AutoCloseable | Interface that lets you stop receiving moderation-related updates ( moderationevents) by invoking theclose()method. | 
Sample code
Print a notification for a mention of the current chat user on the support channel.
1val user = chat.currentUser
2chat.listenForEvents(user.id) { event: Event<EventContent.Mention> ->
3    if (event.payload.channel == "support") {
4        println("${user.id} has been mentioned on the support channel!")
5    }
6}
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:
1message.mentionedUsers
Sample code
Check if the message with the 16200000000000000 timetoken contains any mentions.
1channel.getMessage(16200000000000000).async { result ->
2    result.onSuccess { message: Message? ->
3        if (message != null) {
4            // Access the mentionedUsers property
5            val mentionedUsers = message.mentionedUsers
6            
7            if (mentionedUsers.isNotEmpty()) {
8                println("The message contains the following mentioned users:")
9                mentionedUsers.forEach { user ->
10                    println("User: ${user.name}")
11                }
12            } else {
13                println("The message does not contain any mentions.")
14            }
15        } else {
