7

Is there a way to retrieve the user id of @mention user from chatter post in Apex? We can write a before insert trigger on feeditem, but when we display the body (which has @mention user) it simply displays as text. Is there any workaround for this?

2 Answers 2

11

You can use the new Chatter API in Apex to do this. It's in developer preview currently and is on by default in all Developer Edition orgs. (Note: It went GA in Summer '13.)

Here's an example of how to use it:

String communityId = null;
String feedItemId = 'YOUR_FEEDITEM_ID';

ConnectApi.FeedItem feedItem = ConnectApi.ChatterFeeds.getFeedItem(communityId, feedItemId);
List<ConnectApi.MessageSegment> messageSegments = feedItem.body.messageSegments;
for (ConnectApi.MessageSegment messageSegment : messageSegments) {
    if (messageSegment instanceof ConnectApi.MentionSegment) {
        ConnectApi.MentionSegment mentionSegment = (ConnectApi.MentionSegment) messageSegment;
        System.debug('Mentioned user name: ' + mentionSegment.name);
        System.debug('Mentioned user id: ' + mentionSegment.user.id);
    }
}

Link: API documentation for the ConnectApi.ChatterFeeds class.

1
  • now to access user record related information such as user id, use mentionSegment.record.id instead of mentionSegment.user.id
    – Navii
    Commented Jul 30, 2020 at 8:01
2

Here is the update of the code for 2023, getFeedItem is no longer support in latest API version.

String communityId = null;
String feedItemId = 'YOUR_FEEDITEM_ID';

ConnectApi.FeedElement feedItem = ConnectApi.ChatterFeeds.getFeedElement(communityId, feedItemId);
List<ConnectApi.MessageSegment> messageSegments = feedItem.body.messageSegments;
for (ConnectApi.MessageSegment messageSegment : messageSegments) {
    if (messageSegment instanceof ConnectApi.MentionSegment) {
        ConnectApi.MentionSegment mentionSegment = (ConnectApi.MentionSegment) messageSegment;
        System.debug('Mentioned user name: ' + mentionSegment.name);
        System.debug('Mentioned user id: ' + mentionSegment.record.id);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .