Question: How to insert FeedItem from Apex Email Service and set the network (aka community) that the Chatter post should belong in?
I know that in Apex there is the ConnectApi and it has various postFeedElement( communityId, ... ) methods. But my requirement is that I need to set the FeedItem.CreatedById to be someone other than the context user. To my knowledge, the ConnectApi does not let you specify the author it instead defaults to the context user. Hence why I'm trying to do this with FeedItem and DML directly.
This is related to my github project, Chatter Bot for Feeds, https://github.com/DouglasCAyers/salesforce-chatter-bot-feeds, which enables Process Builder and Flow to automate posting Chatter posts/comments authored by any user, support rich-text, and support @mentions.
This concept works great in the internal community, but failing when the apex code tries to insert FeedItem whose parent is a group that belongs to a external community.
Here's sample code that fails when run either in Apex Email Service or the Developer Console, assume this is executed by a System Administrator with permission to set audit fields:
FeedItem post = new FeedItem(
parentId = '<id to chatter group of an external community>',
createdById = '<id of user other than the current context user>',
body = 'Hello World',
isRichText = true
);
insert post;
The error I get is "System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []"
If I change the parentId to a chatter group of the internal community then this works fine. The system administrator that runs this code is a member of the community and is a member of the group that the post is trying to be made to. The only thing missing is telling Salesforce the community id / network id the post should belong to (but why isn't that just inferred by the FeedItem.ParentId??).
Thanks!
@Joe Morse yes, I was able to set the CreatedById and NetworkScope using FeedItem DML. I did have to enable the system permission "Insert System Field Values for Chatter Feeds" and "Create Audit Fields" for my context user.
FeedItem fi = new FeedItem(
parentId = '0F90a0000008U7R',
body = 'test',
createdById = '005j000000Bz31U', // not current user
networkScope = '0DB0a000000PBDHGA4'
);
insert fi;