---
source_url: https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/users/mentions
title: Mention users
updated_at: 2026-06-15T12:11:36.323Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Mention users

Tag users in chat messages with `@` mentions. Type `@` followed by at least three letters to see username suggestions.

:::tip 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](https://www.pubnub.com/docs/sdks/kotlin/api-reference/objects#set-user-metadata)
* **Mentions per message**: up to 100 (default: 10)

Implementation follows similar patterns to [channel referencing](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/channels/references) and [links](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/links).

:::note Requires App Context
To mention users from a keyset, you must [enable App Context](https://youtu.be/9UEoSlngpYI) for your app's keyset in the [Admin Portal](https://admin.pubnub.com/).
:::

## Add user mentions

Add user mentions with `@` followed by at least three letters (e.g., `@Mar`).

Mentioned users are stored in the [MessageDraft object](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/learn/chat-entities/message-draft). 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()](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts#add-message-element) 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.

```kotlin
// 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()` removes a user mention from a [draft message](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts).

### 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()](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts#remove-message-element) method for details.

:::warning 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.

```kotlin
// 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

`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()](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts#add-message-draft-change-listener) method for details.

### Sample code

```kotlin
// 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:

```kotlin
message.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. |

##### MessageElement details

Each `MessageElement` on the returned list can be of one of these types:

* `data class PlainText(override val text: String) : MessageElement`
* `data class Link(override val text: String, val target: MentionTarget) : MessageElement`

If a `MessageElement` is of type `Link`, its `target` depends on the returned item:

```kotlin
// Mentioned user identified by [userId].
data class User(val userId: String) : MentionTarget

// Referenced channel identified by [channelId].
data class Channel(val channelId: String) : MentionTarget

// Link to [url].
data class Url(val url: String) : MentionTarget
```

### Sample code

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

```kotlin
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) {
                    println("The message contains mentions.")
                } else {
                    println("The message does not contain any mentions.")
                }
            }.onFailure { error ->
                // Handle failure
                println("Failed to retrieve the message: ${error.message}")
            }
        }
    }.onFailure { error ->
        // Failed to retrieve the channel
        println("Failed to retrieve the channel: ${error.message}")
    }
}
```

## Collect 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:

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

#### Input

| Parameter | Description |
| --- | --- |
| `startTimetoken`Type: `Long`Default: 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](https://www.pubnub.com/docs/sdks/kotlin/api-reference/storage-and-playback#batch-history). |
| `endTimetoken`Type: `Long`Default: 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](https://www.pubnub.com/docs/sdks/kotlin/api-reference/storage-and-playback#batch-history). |
| `count`Type: `Int`Default: `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](https://www.pubnub.com/docs/sdks/kotlin/api-reference/storage-and-playback#methods). The default value is `100`. |

#### Output

| Parameter | Description |
| --- | --- |
| `PNFuture<GetCurrentUserMentionsResult>`Type: `object` | Returned object containing two fields: `mentions` and `isMore`. |
| `> mentions`Type: `List<UserMention>` | List of mention events. Each `UserMention` contains: `message` (the `Message` object), `userId` (who triggered the mention), `channelId` (where the mention occurred), and `parentChannelId` (the parent channel if the mention is in a thread, otherwise `null`). |
| `> isMore`Type: `Boolean` | Info whether there are more historical events to pull. |

### Sample code

List the last ten mentions for the current chat user.

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

## Show notifications for mentions

`onMentioned()` monitors mention events on the `User` object. Use this to trigger pop-up notifications when the current user is mentioned in a channel or thread.

:::warning Deprecated method
`listenForEvents<EventContent.Mention>()` is deprecated. Use `user.onMentioned()` instead, which provides a typed `Mention` object.
:::

### Method signature

This method has the following parameters:

```kotlin
user.onMentioned(callback: (mention: Mention) -> Unit): AutoCloseable
```

#### Input

| Parameter | Description |
| --- | --- |
| `callback` *Type: `(mention: Mention) -> Unit`Default: n/a | Function invoked with a `Mention` event whenever the user is mentioned. |

The `Mention` object contains:

| Property | Description |
| --- | --- |
| `messageTimetoken`Type: `Long` | The timetoken of the message containing the mention. |
| `channelId`Type: `String` | The channel where the mention occurred. |
| `parentChannelId`Type: `String?` | The parent channel if the mention is in a thread, otherwise `null`. |
| `mentionedByUserId`Type: `String` | The user ID of the message author who created the mention. |

#### Output

| Type | Description |
| --- | --- |
| `AutoCloseable` | Interface that lets you stop receiving mention events by invoking the `close()` method. |

### Sample code

Print a notification when the current user is mentioned.

```kotlin
val user = chat.currentUser

val subscription = user.onMentioned { mention ->
    println("Mentioned in channel ${mention.channelId} at timetoken ${mention.messageTimetoken} by ${mention.mentionedByUserId}")
}

// stop listening:
// subscription.close()
```

## Get mentioned users (deprecated)

You can access the `mentionedUsers` property of the [Message object](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/learn/chat-entities/message) to return all users mentioned in a message.

### Method signature

This is how you can access the property:

```kotlin
message.mentionedUsers
```

### Sample code

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

```kotlin
channel.getMessage(16200000000000000).async { result ->
    result.onSuccess { message: Message? ->
        if (message != null) {
            // Access the mentionedUsers property
            val mentionedUsers = message.mentionedUsers
            
            if (mentionedUsers != null && mentionedUsers.isNotEmpty()) {
                println("The message contains the following mentioned users:")
                mentionedUsers?.forEach { (index, user) ->
                    println("User: ${user.name}")
                }
            } else {
                println("The message does not contain any mentions.")
            }
        } else {
            println("Message does not exist")
        }
    }.onFailure { exception: PubNubException ->
        println("Exception occurred: ${exception.message}")
    }
}
```