Mention users
Tag users in chat messages with @ mentions. Type @ followed by at least three letters to see username suggestions.
Generic referencing
Channel references, user mentions, and links are MessageElement instances with different MentionTarget values.
Configuration options:
- User source: channel members or all app users
- Suggestions: up to 100 usernames (default: 10)
- Username length: up to 200 characters
- Mentions per message: up to 100 (default: 10)
Implementation follows similar patterns to 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
Add user mentions with @ followed by at least three letters (e.g., @Mar).
Mentioned users are stored in the MessageDraft object. When sent with send(), mention data is saved to 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() removes a 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
Provide the exact offset position where the mention starts; otherwise, it won't be 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
getUserSuggestions() returns users matching a 3-letter string from channel members or global users.
Example: typing Sam returns Samantha, Samir, etc. Default limit: 10 users (max: 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) {
show all 29 linesCollect all user-related mentions
getCurrentUserMentions() retrieves all instances where the current user was mentioned in channels or threads. Use this to build a mentions feed.
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 the includeMessageActions parameter in the Kotlin SDK docs. |
Output
| Parameter | Description |
|---|---|
PNFuture<GetCurrentUserMentionsResult>Type: object | Returned object containing two fields: enhancedMentionsData and isMore. |
→ enhancedMentionsDataType: enhancedMentionsData (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. |
→ 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
listenForEvents() monitors mention events in channels and threads you're a member of. Use this to trigger pop-up notifications.
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 EventContent interface, allowing access to type information at runtime. |
channel *Type: StringDefault: Mentioned user ID | Channel to listen for new mention events. 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 an mention event type is detected on the specified channel. |
Output
| Type | Description |
|---|---|
AutoCloseable | Interface that lets you stop receiving moderation-related updates (moderation events) by invoking the close() 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 {
show all 21 lines