Originally published at
Moishe Beshkin. You can comment here or
there.
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:
@Path("/messenger")
@RequestScoped
public class MessengerController {
@GET
@Path("/webhook")
@Produces("text/plain")
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;
}
@POST
@Path("/webhook")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
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 = "
https://graph.facebook.com/v2.6/me/messages?access_token=";
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.setRequestMethod("POST");
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
con.setDoOutput(true);
OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
w.write(rawData);
w.close();
int responseCode = con.getResponseCode();
LOGGER.info("responseCode: "+responseCode);
LOGGER.info("responseMessage: "+con.getResponseMessage());
is = con.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
As a result user will be able to communicate with our kosher bot.
Click to view
Click to view