function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
EnryEnry 

@Mention with apex code

I've written a class to post a happy birthday message and picture on chatter.

Now i want mention a user in the post.

I have found:http://developer.force.com/cookbook/recipe/posting-a-chatter-mention-via-apex

My code create the post but it doesn't mention the user. 

i haven't experience with HttpRequest.

 

Please can you take a look to my code?

Thank you in advantage.

 

Global class HappyBirthdayRandom implements Schedulable{


//FOR TEST METHOD
   public static String CRON_EXP = '0 0 0 3 9 ? 2022';
   
   @future(callout=true)
            public static void mention(string uid,string RecordId){
                 //INVOKE CHATTER REST API FOR MENTION
                  String salesforceHost = System.Url.getSalesforceBaseURL().toExternalForm();
                  String url =  salesforceHost + '/services/data/v26.0/chatter/feeds/record/' + RecordId + '/feed-items';
                     HttpRequest req = new HttpRequest();
                      req.setMethod('POST');
                      req.setEndpoint(url);
                      string ChatterPostText='Happy Birthday';
                        req.setHeader('Content-type', 'application/json');
                         req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
                          req.setBody('{ "body" : { "messageSegments" : [ { "type": "mention", "id" : "' + uid + '" }, { "type": "text",  "text" : "' + ' ' + ChatterPostText +  '" } ] } }');
                           Http http = new Http();
                            HTTPResponse res = http.send(req);           
                    } 
   
   
   

  Global void execute(SchedulableContext sc) 
    {

            
           // SEARCH BY STATIC RESOURCE NAME
           List<StaticResource> Pictures=[Select Name, ContentType, Body From StaticResource where Name like 'PicturehappyBirthday%'];
           List<FeedItem> posts = new List<FeedItem>();
           // IS THE USER BIRTHDAY?              
           List<user> lstu=[SELECT id,name,date_of_birth__c FROM user WHERE  CALENDAR_MONTH(date_of_birth__c)=:date.today().month() AND  DAY_IN_MONTH(date_of_birth__c)=:date.today().day()];
           CollaborationGroup fgroup=[Select id,name from CollaborationGroup where Name like 'Name%' limit 1];
       
              for(User u:lstu)
              {
                    //GENERATE A RANDOM NUMBER [0-5] TO SELECT THE PICTURE
                   Integer choice=math.mod(Integer.valueof(Math.random()*100),6);
                   Blob Decodedbody=Pictures[choice].body;
                   // CREATE POST
                   FeedItem post = new FeedItem();


                   
                   // CREATE BY
                   post.CreatedById=u.id;
                   // CREATE ON
                   post.ParentId =fgroup.id;
                   post.Type = 'ContentPost';
                   mention(u.id,post.id); 
                   post.Body = 'Happy birthday to '+u.name+' !';
                   post.ContentData = Decodedbody;
                   post.ContentFileName = 'Wishes!.jpg';
                   posts.add(post);
              }
                 insert posts;
 
        }
    }

 

 

 

RoyGiladRoyGilad

Hi Erny

Cool idea!!!

just love it.

The problem is that you call the "memtion" method before you have an ID for the post, it should be done after the insert.

Note that this will change your code , you can't more than 10 future call.

 

Also, I think you worote it very nicely, the only thing that I would change is the random function you use, you wrote all of your code in a way it can be extended with lots of images (which is great) except for the random lime:

Integer choice=math.mod(Integer.valueof(Math.random()*100),6);

I think if you can change it to the below you could forever add new photos without changing your code:

Integer choice=math.mod(Integer.valueof(Math.random()*100),Pictures.size());
EnryEnry

Hi Roy,Thanks for your reply.

i think that you are right about the post id.

But with my code i'm going to end up creating two posts, one via your insert and one via the REST API .

Many persons have advise against to use call out.

Just try to use Connect in Apex rather than this Chatter REST API Callout.

http://blogs.developerforce.com/developer-relations/2013/02/getting-started-with-connect-in-apex.html

 

 

What do you think about?

 

Thanks again,you are very kind.

RoyGiladRoyGilad

Hi Erny
I think the same, I checked it out and to access Chatter API, use the classes in the ConnectApi namespace.
For information about working with the ConnectApi classes, see Working with Chatter in Apex:

http://www.salesforce.com/us/developer/docs/apexcode/Content/connectAPI_overview.htm

 

Here is how you use the mention via ConnectAPI:

 

// Post a feed item that has an @-mention.

String communityId = null;
ConnectApi.FeedType feedType = ConnectApi.FeedType.UserProfile;
String userToMention = '005xx000001TDn3'
String subjectId = '005xx000001TDn3';

ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
textSegment.text = 'Hey there ';
messageInput.messageSegments.add(textSegment);

ConnectApi.MentionSegmentInput mentionSegment = new ConnectApi.MentionSegmentInput();
mentionSegment.id = userToMention;
messageInput.messageSegments.add(mentionSegment);

textSegment = new ConnectApi.TextSegmentInput();
textSegment.text = '. How are you?';
messageInput.messageSegments.add(textSegment);

ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
input.body = messageInput;

ConnectApi.FeedItem feedItemRep = ConnectApi.ChatterFeeds.postFeedItem(communityId, feedType, subjectId, input, null);