Skip to main content
Quick Reference for AI Agents & Developers
// Mention format: <@uid:USER_UID>
const messageText = "Hey <@uid:john123>, check this out!";

// Send message with mentions
const textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType);
await CometChat.sendMessage(textMessage);

// Get mentioned users from message
const mentionedUsers = message.getMentionedUsers();
mentionedUsers.forEach((user) => {
  console.log("Mentioned:", user.getName(), user.getUid());
});

// Fetch messages with mention info
const messagesRequest = new CometChat.MessagesRequestBuilder()
  .setGUID(guid)
  .mentionsWithTagInfo(true)
  .mentionsWithBlockedInfo(true)
  .build();

// Display: Replace <@uid:john123> with @John in UI
Mentions let users reference specific people in a conversation using the <@uid:UID> format. This is especially useful in group chats to direct messages to specific participants and trigger notifications.
Availability: SDK, API, UI KitsMentions work in text messages and media message captions.

Mention Format

To mention a user, include their UID in this format within your message text:
<@uid:USER_UID>
ExampleResult
<@uid:john123>Mentions user with UID “john123”
Hey <@uid:john123>, check this!Message mentioning John
<@uid:user1> and <@uid:user2>Multiple mentions

Send a Message with Mentions

const receiverID = "UID";
const messageText = "Hey <@uid:cometchat-uid-1>, check this out!";
const receiverType = CometChat.RECEIVER_TYPE.USER;

const textMessage = new CometChat.TextMessage(
  receiverID,
  messageText,
  receiverType
);

CometChat.sendMessage(textMessage).then(
  (message) => console.log("Message sent:", message),
  (error) => console.log("Failed to send:", error)
);

Get Mentioned Users

Retrieve the list of users mentioned in a message:
const mentionedUsers = message.getMentionedUsers();
// Returns array of User objects (or empty array)

mentionedUsers.forEach((user) => {
  console.log("Mentioned:", user.getName(), user.getUid());
});

Fetch Messages with Mention Info

When fetching messages, include additional information about mentioned users.

Builder Options

MethodDescription
mentionsWithTagInfo(true)Include tags of mentioned users
mentionsWithBlockedInfo(true)Include blocked relationship info

With Tag Information

const GUID = "GUID";
const limit = 30;

const messagesRequest = new CometChat.MessagesRequestBuilder()
  .setGUID(GUID)
  .setLimit(limit)
  .mentionsWithTagInfo(true)
  .build();

messagesRequest.fetchPrevious().then(
  (messages) => {
    messages.forEach((message) => {
      message.getMentionedUsers().forEach((user) => {
        console.log("User:", user.getName());
        console.log("Tags:", user.getTags());
      });
    });
  },
  (error) => console.log("Failed to fetch:", error)
);

With Blocked Relationship Info

const GUID = "GUID";
const limit = 30;

const messagesRequest = new CometChat.MessagesRequestBuilder()
  .setGUID(GUID)
  .setLimit(limit)
  .mentionsWithBlockedInfo(true)
  .build();

messagesRequest.fetchPrevious().then(
  (messages) => {
    messages.forEach((message) => {
      message.getMentionedUsers().forEach((user) => {
        console.log("User:", user.getName());
        console.log("Blocked by me:", user.getBlockedByMe());
        console.log("Has blocked me:", user.getHasBlockedMe());
      });
    });
  },
  (error) => console.log("Failed to fetch:", error)
);

Building a Mention Picker

Here’s a practical implementation for mention suggestions:
class MentionHelper {
  constructor(groupId) {
    this.groupId = groupId;
    this.members = [];
  }

  // Load group members for mention suggestions
  async loadMembers() {
    const request = new CometChat.GroupMembersRequestBuilder(this.groupId)
      .setLimit(100)
      .build();

    this.members = await request.fetchNext();
    return this.members;
  }

  // Filter members based on search query (when user types @...)
  searchMembers(query) {
    const lowerQuery = query.toLowerCase();
    return this.members.filter((member) =>
      member.getName().toLowerCase().includes(lowerQuery)
    );
  }

  // Convert user to mention format
  formatMention(user) {
    return `<@uid:${user.getUid()}>`;
  }

  // Build message text with mentions
  buildMessageWithMentions(text, selectedUsers) {
    let messageText = text;
    
    selectedUsers.forEach((user) => {
      const displayPattern = new RegExp(`@${user.getName()}`, "g");
      messageText = messageText.replace(displayPattern, this.formatMention(user));
    });
    
    return messageText;
  }
}

// Usage
const mentionHelper = new MentionHelper("group-123");
await mentionHelper.loadMembers();

// When user types "@jo"
const suggestions = mentionHelper.searchMembers("jo");

// When sending message
const messageText = mentionHelper.buildMessageWithMentions(
  "Hey @John, check this out!",
  [selectedUser]
);
// Result: "Hey <@uid:john123>, check this out!"

Display Mentions in UI

Convert mention format to readable display:
function renderMessageWithMentions(message) {
  let text = message.getText();
  const mentionedUsers = message.getMentionedUsers();
  
  mentionedUsers.forEach((user) => {
    const mentionPattern = `<@uid:${user.getUid()}>`;
    const mentionElement = `<span class="mention" data-uid="${user.getUid()}">@${user.getName()}</span>`;
    text = text.replace(mentionPattern, mentionElement);
  });
  
  return text;
}

// Input:  "Hey <@uid:john123>, check this!"
// Output: "Hey <span class="mention" data-uid="john123">@John</span>, check this!"
Styling Tip: Add CSS to highlight mentions:
.mention {
  color: #0066cc;
  background-color: #e6f2ff;
  padding: 2px 4px;
  border-radius: 4px;
  cursor: pointer;
}

Complete Implementation Example

class MentionManager {
  constructor(groupId) {
    this.groupId = groupId;
    this.members = [];
    this.showingSuggestions = false;
    this.searchQuery = "";
  }

  async initialize() {
    await this.loadMembers();
  }

  async loadMembers() {
    const request = new CometChat.GroupMembersRequestBuilder(this.groupId)
      .setLimit(100)
      .build();
    this.members = await request.fetchNext();
  }

  // Call this on every keystroke in the input
  handleInput(text, cursorPosition) {
    const beforeCursor = text.substring(0, cursorPosition);
    const mentionMatch = beforeCursor.match(/@(\w*)$/);

    if (mentionMatch) {
      this.showingSuggestions = true;
      this.searchQuery = mentionMatch[1];
      return this.getSuggestions();
    } else {
      this.showingSuggestions = false;
      return [];
    }
  }

  getSuggestions() {
    if (!this.searchQuery) return this.members.slice(0, 5);
    
    const query = this.searchQuery.toLowerCase();
    return this.members
      .filter((m) => m.getName().toLowerCase().includes(query))
      .slice(0, 5);
  }

  // Call when user selects a suggestion
  insertMention(text, cursorPosition, user) {
    const beforeCursor = text.substring(0, cursorPosition);
    const afterCursor = text.substring(cursorPosition);
    
    // Remove the @query part
    const newBefore = beforeCursor.replace(/@\w*$/, `@${user.getName()} `);
    
    this.showingSuggestions = false;
    return newBefore + afterCursor;
  }

  // Call before sending to convert display names to mention format
  prepareForSend(text) {
    let prepared = text;
    
    this.members.forEach((member) => {
      const displayPattern = new RegExp(`@${member.getName()}\\b`, "g");
      prepared = prepared.replace(displayPattern, `<@uid:${member.getUid()}>`);
    });
    
    return prepared;
  }

  // Call when displaying received messages
  formatForDisplay(message) {
    let text = message.getText();
    const mentionedUsers = message.getMentionedUsers();
    
    mentionedUsers.forEach((user) => {
      const pattern = `<@uid:${user.getUid()}>`;
      const display = `<span class="mention">@${user.getName()}</span>`;
      text = text.replaceAll(pattern, display);
    });
    
    return text;
  }
}

Next Steps