Developing bots for Facebook Messenger Platform with Glasfish server

There is so much informational noise about new Facebook feature – Messenger Platform, that I could not resist to try it out for our project “Is it kosher?“.

Here are some general steps for make your own bot on a simple REST server like Glassfish.
1. register your webhooks.
I think this was one of the most complicated parts, because Facebook documentation is not quite clear.
So, I created a Constroller:

public class MessengerController {
    public String webhookGet(@QueryParam("hub.verify_token") String verifyToken, @QueryParam("hub.challenge") String challenge ){
        if (!verifyToken.equals("my_voice_is_my_password_verify_me"))
            return "wrong token: "+verifyToken;
        return challenge;

    public JsonObject webhook(MessengerHook messengerHook) {
       // some stuff with data obtained from Messenger API.

After the server is up and running, you will be able to register it for messenger API. Checkout Quick Start documentation for more details.

2. sending messages to users
After you got request from Messenger, then you can parse the message and respond properly.
To send a response, I am using the following function:

    public void sendMessage(final JsonObject jsonObject){
        final String url = "";
        getIs(url, jsonObject);

    private InputStream getIs(String urlString, JsonObject obj){
        InputStream is = null;
        // Making HTTP request
        try {
            String rawData = obj.toString();

            URL url = new URL(urlString);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            //add reuqest header
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            con.setRequestProperty("Accept-Language", "en-US,es;q=0.8");
            con.setRequestProperty("Connection", "keep-alive");
            con.setRequestProperty("X-Requested-With", "XMLHttpRequest");

            // Send post request

            OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");


            int responseCode = con.getResponseCode();
  "responseCode: "+responseCode);
  "responseMessage: "+con.getResponseMessage());

            is = con.getInputStream();

        } catch (IOException e) {
        return is;

As a result user will be able to communicate with our kosher bot.

Leave a Reply

%d bloggers like this: