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
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.
-
now to access user record related information such as user id, use
mentionSegment.record.id
instead ofmentionSegment.user.id
– NaviiCommented Jul 30, 2020 at 8:01
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);
}
}