Codementor Events

A Facebook Messenger BOT

Published Aug 06, 2018Last updated Aug 07, 2018
A Facebook Messenger BOT

Well this time I want to share with you the way to make a functional Facebook Bot, in this case I'm goin to use the java as backend languaje.
So first of all we need the next items to start:

  • A facebook Page
  • Facebook application
  • Java Project
    Well I think I don't need tell you how to create a Facebook page, so let's create a facebook application and configurate.
    Go to the page: Facebook developers and add a new application, my applications is: > tk-bot
    Now we have to create a token for our backend application, for this we have to add the messenger application and access to the settings tab, select the page and generate a new token, the token looks like this:
    DeepinScreenshot_select-area_20180806164154.png
    Copy this access token to a file, now access to start.spring.io and configure an application with the next dependencies: Web, Lombok and download it.
    Code time....
    Now we have almost all for our chatbot, lets add a new controller in our java project the code is:
@RestController()
@RequestMapping("webhook")
public class WebHook {

    private final String PAGE_TOKEN ="THIS_IS_THE_TOKEN_YOU_COPIED_BEFORE";
    private final String VERIFY_TOKEN="A_SECRET_VERIFY_TOKEN";
    //this is for reply messages
    private final String FB_MSG_URL="https://graph.facebook.com/v2.6/me/messages?access_token="
            + PAGE_TOKEN;

  //logger to watch whats happening in our bot
    private final Logger logger = LoggerFactory.getLogger(WebHook.class);
    private final RestTemplate template = new RestTemplate();


  //This is necessary for register a webhook in facebook 
    @GetMapping()
    @ResponseStatus(HttpStatus.OK)
    public String get(@RequestParam(name = "hub.verify_token")String token,
                    @RequestParam(name = "hub.challenge")String challenge){
        if(token!=null && !token.isEmpty() && token.equals(VERIFY_TOKEN)){
            return challenge;
        }else{
            return "Wrong Token";
        }
    }

  //This method  reply all messages with: 'This is a test message'
    @PostMapping
    @ResponseStatus(HttpStatus.OK)
    public void post(@RequestBody FacebookHookRequest request){
        logger.info("Message from chat: {}",request);
        request.getEntry().forEach(e->{
            e.getMessaging().forEach(m->{
                String id = m.getSender().get("id");
                sendReply(id,"This is a test message");
            });
        });
    }

    private void sendReply(String id,String text){
        FacebookMessageResponse response = new FacebookMessageResponse();
        response.setMessage_type("text");
        response.getRecipient().put("id",id);
        response.getMessage().put("text",text);
        HttpEntity<FacebookMessageResponse> entity = new HttpEntity<>(response);
        String result = template.postForEntity(FB_MSG_URL,entity,String.class).getBody();
        logger.info("Message result: {}",result);

    }
}

You also need to add the next classes: FacebookEntry.java,FacebookHookRequest.java,FacebookMessage.java,FacebookMessageResponse.java,FacebookMessaging.java this are for made an receive request from Facebook 😄:

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class FacebookEntry implements Serializable {
    private String id;
    private Long time;
    private List<FacebookMessaging> messaging = new ArrayList<>();

}

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class FacebookHookRequest implements Serializable {
    private String object;
    private List<FacebookEntry> entry = new ArrayList<>();
}


@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class FacebookMessage implements Serializable {
    private String mid;
    private Long seq;
    private String text;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class FacebookMessageResponse implements Serializable {
    private String message_type;
    private Map<String,String> recipient = new HashMap<>();
    private Map<String,String> message = new HashMap<>();
}


@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class FacebookMessaging implements Serializable {
    private Map<String,String> sender;
    private Map<String,String> recipient;
    private Long timestamp;
    private FacebookMessage message;
}

Now you have all the backend for reply dummies messages, deploy this using Heroku
the commands for do this are:

$ heroku create
$ git init
$ git add .
$ git commit -m 'Hook for facebook'
$ git push heroku master

And when the application is running open the Application configuration in facebook, and configure a web hook putting the url of your heroku instance and the path: /webhook
DeepinScreenshot_select-area_20180806165823.png
Also you have to select the options:
DeepinScreenshot_select-area_20180806165955.png
And click in save.
So with this configurations you have all necessary to test your bot like this:
DeepinScreenshot_select-area_20180806170152.png
And if you go to the heroku logs you will se the next log:
DeepinScreenshot_select-area_20180806170346.png

Now you cand add a NLP like wit.ai to catch user intents and add rules using DROOLS for context conversations

Discover and read more posts from Victor de la Cruz
get started
post comments1Reply
nabilChemkhi
3 years ago

Hi Victor, thanks, you are awesome.
I did the same as you.
everything is working like a charm
but when I send a message
I receive an infinity loop of respons