Apex · Integration · REST · Salesforce Einstein · Trigger

Einstein Intent and Einstein Sentiment Analysis on Facebook Posts

Einstein Language 

Einstein Language Is used to build natural language processing into your apps and unlock insights within text. Einstein Language contains two NLP services:

Einstein Intent—Categorize unstructured text into user-defined labels to better understand what users are trying to accomplish. Leverage the Einstein Intent API to analyze text from emails, chats, or web forms to

  • Determine which products prospects are interested in, and send customer inquiries to the appropriate sales person.
  • Route service cases to the correct agents or departments, or provide self-service options.
  • Understand customer posts to provide personalized self-service in your communities.

Einstein Sentiment—Classify the sentiment of text into positive, negative, and neutral classes to understand the feeling behind text. You can use the Einstein Sentiment API to analyze emails, social media, and text from chat to:

  • Identify the sentiment of a prospect’s emails to trend a lead or opportunity up or down.
  • Provide proactive service by helping dissatisfied customers first or extending promotional offers to satisfied customers.
  • Monitor the perception of your brand across social media channels, identify brand evangelists, and monitor customer satisfaction.


Lets suppose I have a Facebook Page for an E-Commerce site. If any user sharing their feedback through posts or comments on the page, We can retrieve the post and comments to Salesforce and find Intent of the post and the Sentiment of the comments.

This can be achieved by following these steps:

step 1. Create a Facebook page.

step 2. Create a Facebook app using Facebook Developers account.

To Connect with Facebook we Should use Graph API, To use Graph API we need to Create a Facebook Developers account using Facebook credentials,

To create a Facebook app

  • login to https://developers.facebook.com/
  • click on My Apps -> Add a New App.

Enter basic information and make the App Live, If the app is not Live we can’t use it for Communicating with Facebook.

Now click on Tools & Support and go to Graph API Explorer, here we can generate Access token and test the app.

Steps to create Access token:

  • select you app from Application drop down.
  • click on Get Token and select Get User Access Token.
  • select the permissions required and click Get Access Token.
  • To get Page Access token click on Get Token and select you Page from Page Access Tokens.
  • Now you can see your page name on the drop down list, click on that and select Request publish_pages.

This slideshow requires JavaScript.


step 3. Create an Object on Salesforce to save posts and their comments.

Create an object with fields to store posts, comments, Sentiment, Intent.

step 4. Create remote site setting on Salesforce.

Go to Remote Site Settings -> New Remote Site

enter site name, remote site URL as https://graph.facebook.com , check Active checkbox and Save.

step 5. Make a callout to Facebook to retrieve posts and comments.

In Einstein_Facebook class we are getting post and comments from Facebook, and extracting posts and comments from returned JSON and creating records.


public class Einstein_Facebook {

    public static void sendRequest(){

        //getting accesstoken from custom lable.
        String accessToken = Label.Facebook_Access_Token;
        HttpRequest request = new HttpRequest();
        request .setEndpoint('https://graph.facebook.com/v2.12/391648194596048?fields=posts{message,comments,type}&access_token='+accessToken);
        request .setMethod('GET');
        //Making request
        Http http = new Http();
        HTTPResponse response= http.send(request );
        //getting post and comments in response.
        String data=response.getBody();

        //getting post and comments from JSON rceived in response.
        List line=data.split(',');
        List posts=new List();
        List postAndComments=new List();
        for(String l:line){
            string substring=l.substringBetween('"message":"','"');
        //creating a Map of posts and comments.
        Map PostComments =new Map();
        for(String p:posts){
                List empty=new List();
        String key;
        Listcomments=new List();
        for(string messages : postAndComments){

            //checking if the message exists in posts and adding as key.
                    key = messages ;

                //else adding to comments to corresponding post.
                    PostComments.put(key, comments);

        //querying all the Posts and comments
        List existingPosts = [SELECT id,Comments__c,Posts__c FROM Einstein_Facebook__c];
        List listDelete = new List();
        for(Einstein_Facebook__c Post:existingPosts){

            //checking if post already exists and adding to a list.

        //deleting the list.
        delete listDelete;

        List  PostCommentList=new List();
        //Iterating through Map to create records.
        for(string post : PostComments.keySet()){
            for(string comments : PostComments.get(post)){
                Einstein_Facebook__c Facebookcomment=new Einstein_Facebook__c();
                Facebookcomment.Comments__c=comments ;

        //Inserting List of  posts and comments.
        insert PostCommentList;



step 6. Write a trigger to get Intent and sentiment of post and comments.

Trigger to fire after insert on Facebook posts and comments:

trigger EinsteinFB_Trigger on Einstein_Facebook__c (after insert) {    For(Einstein_Facebook__c post : Trigger.New) 


      String  postId = post.Id; 




Handler for the trigger:

Here we are using EinsteinVision_Admin EinsteinVision_Sentiment classes to get Intent and Sentiment of posts and comments which we explained in detail in our previous blog on Einstein Intent and Einstein Sentiment.

global class Einstein_Handler{

    Public static void getProbabilityforFB(String body){
        Einstein_Facebook__c fd=[select Posts__c, Comments__c from Einstein_Facebook__c where id=:body]; 

        String intentLabel = EinsteinVision_Admin.getPrediction(fd.Posts__c);
        String sentimentLabel = EinsteinVision_Sentiment.findSentiment(fd.Comments__c);

        update fd;


This is a report to show analysis of Facebook post and comments.

facebook report

4 thoughts on “Einstein Intent and Einstein Sentiment Analysis on Facebook Posts

  1. Hi, I am stuck at the Publish the Page, where it is expecting me to register and validate the app and is expecting me to be a valid business unit. I am doing this for a demo as an individual. Is there an alternative way out to get this working? Any help is much appreciated.


  2. Hi, many information are missing to replicate. Can you add what you stored in custom label?
    Even apex class returns many errors and cannot be saved.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s