[SalesForce] Retrieve UserId of @mention user from chatter post in Apex

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?

Best Answer

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.

Related Topic