Sunday, March 19, 2017

How to create facebook messenger bot part 2

Setup Welcome Screen For Greeting Text and Get Started Button 

This will be the welcome screen for the new conversation. It will appear only for the first time. This will be similar like this.


For this, we have to make the post request. I am using postman for the post request, you can simply add postman extension in your chrome.

Example
curl -X POST -H "Content-Type: application/json" -d '{
  "setting_type":"greeting",
  "greeting":{
    "text":"Welcome to shopping bot" //you can text whatever you want
  }
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"   // PAGE_ACCESS_TOKEN = previously generated page access token
  1. Select Post option from drop down of a postman. Enter request url = https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN
  2. In headers tab set key=Content-Type and value=application/json
  3. In body tab select raw radio button and enter 
{
  "setting_type":"greeting",
  "greeting":{
    "text":"Welcome to shopping bot" 
  }
}
After sending you can see output as
{
  "result": "Successfully updated greeting"
}
Similarly, you can set for get started button.

Example


curl -X POST -H "Content-Type: application/json" -d '{
  "setting_type":"call_to_actions",
  "thread_state":"new_thread",
  "call_to_actions":[
    {
      "payload":"InitialPayload"
    }
  ]
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"      
After setting you can see like

After click Get Started button you can see JSON format where we check for "IntialPayload" in order
"postback": {
                        "payload": "InitialPayload"
                    }
to replay some message for that user.

Now it's time to handle JSON format.
Here we are going to create Class for each object.



MessageRequest.java


public class MessageRequest {
    String object;
    List<entry> entry = new ArrayList<entry>();

    public String getObject() {
        return object;
    }

    public void setObject(String object) {
        this.object = object;
    }

    public List<entry> getEntry() {
        return entry;
    }

    public void setEntry(List<entry> entry) {
        this.entry = entry;
    }
}

Entry.java
public class Entry {
    String id;
    String time;
    List<messaging> messaging = new ArrayList<messaging>();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public List<messaging> getMessaging() {
        return messaging;
    }

    public void setMessaging(List<messaging> messaging) {
        this.messaging = messaging;
    }
}



Sender.java
public class Sender {
    String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
Recipient.java
public class Recipient {
    String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
Message.java
public class Message {
    String mid;
    String seq;
    String text;
    Long stickerId;
    List<attachment> attachments;
    Attachment attachment;
    QuickReplies quick_reply;
    List<quickreplies> quick_replies;
    public String getMid() {
        return mid;
    }

    public void setMid(String mid) {
        this.mid = mid;
    }

    public String getSeq() {
        return seq;
    }

    public void setSeq(String seq) {
        this.seq = seq;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Long getStickerId() {
        return stickerId;
    }

    public void setStickerId(Long stickerId) {
        this.stickerId = stickerId;
    }

    public List<attachment> getAttachments() {
        return attachments;
    }

    public void setAttachments(List<attachment> attachments) {
        this.attachments = attachments;
    }

    public Attachment getAttachment() {
        return attachment;
    }

    public void setAttachment(Attachment attachment) {
        this.attachment = attachment;
    }

    public QuickReplies getQuick_reply() {
        return quick_reply;
    }

    public void setQuick_reply(QuickReplies quick_reply) {
        this.quick_reply = quick_reply;
    }

    public List<quickreplies> getQuick_replies() {
        return quick_replies;
    }

    public void setQuick_replies(List<quickreplies> quick_replies) {
        this.quick_replies = quick_replies;
    }

    
}

Postback.java
public class Postback {
    String payload;
    Referral referral;
    public String getPayload() {
        return payload;
    }

    public void setPayload(String payload) {
        this.payload = payload;
    }

    public Referral getReferral() {
        return referral;
    }

    public void setReferral(Referral referral) {
        this.referral = referral;
    }

}

Referral.java
public class Referral {
    String ref;
    String source;
    String type;

    public String getRef() {
        return ref;
    }

    public void setRef(String ref) {
        this.ref = ref;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}


Attachment.java
public class Attachment {
    String type;
    Payload payload;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Payload getPayload() {
        return payload;
    }

    public void setPayload(Payload payload) {
        this.payload = payload;
    }
}
QuickReplies.java
public class QuickReplies {
    String content_type;
    String title;
    String payload;

    public String getContent_type() {
        return content_type;
    }

    public void setContent_type(String content_type) {
        this.content_type = content_type;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPayload() {
        return payload;
    }

    public void setPayload(String payload) {
        this.payload = payload;
    }
}
Messaging.java
public class Messaging {
    Sender sender;
    Recipient recipient;
    String timestamp;
    Message message;
    Postback postback;
    Referral referral;

    public Sender getSender() {
        return sender;
    }

    public void setSender(Sender sender) {
        this.sender = sender;
    }

    public Recipient getRecipient() {
        return recipient;
    }

    public void setRecipient(Recipient recipient) {
        this.recipient = recipient;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public Postback getPostback() {
        return postback;
    }

    public void setPostback(Postback postback) {
        this.postback = postback;
    }

    public Referral getReferral() {
        return referral;
    }

    public void setReferral(Referral referral) {
        this.referral = referral;
    }
}

Element.java

public class Element {
    String title;
    String subtitle;
    String image_url;
    List<Button> buttons;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public String getImage_url() {
        return image_url;
    }

    public void setImage_url(String image_url) {
        this.image_url = image_url;
    }

    public List<Button> getButtons() {
        return buttons;
    }

    public void setButtons(List<Button> buttons) {
        this.buttons = buttons;
    }
}
Button.java
public class Button {
    String type;
    String title;
    String payload;
    String url;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPayload() {
        return payload;
    }

    public void setPayload(String payload) {
        this.payload = payload;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

Payload.java

public class Payload {
        String template_type;
        String text;
        List<element> elements;
    List<button> buttons;
    
    public String getTemplate_type() {
    return template_type;
    }
    
    public void setTemplate_type(String template_type) {
    this.template_type = template_type;
    }
    
    public String getText() {
    return text;
    }
    
    public void setText(String text) {
    this.text = text;
    }
    
    public List<element> getElements() {
    return elements;
    }
    
    public void setElements(List<element> elements) {
    this.elements = elements;
    }
    
    public List<button> getButtons() {
    return buttons;
    }
    
    public void setButtons(List<button> buttons) {
    this.buttons = buttons;
    }
    }

Now its time to reply some text when user click Get Started button. All the callback messages should be listen in POST request. Lets make one helper class for making format of message to send. Here I am going to make FacebookHelper.java.
def private processMessages(){
        //make post request as readable
        String payload = FacebookHelper.readRequest(request);
        //convert json format to java readable format
        MessageRequest messageRequest = new Gson().fromJson(payload,MessageRequest.class)
        List<messaging> messagings = messageRequest.entry.get(0).messaging;
        for (Messaging event:messagings){
            try {
                if (event.postback != null){
                    sendPostbackMessge(event);
                }
            }catch (Exception e){
                e.printStackTrace();
                response.status = 200;
                render(true);
                return ;
            }

        }
        response.status = 200;
        render(true);
    }



Here line 3 will convert the JSON post request format to readable form which we will create in FacebookHelper.java.
public class FacebookHelper {

public static String readRequest(HttpServletRequest request){
        String line = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            BufferedReader bufferedReader = request.getReader();
            while ((line = bufferedReader.readLine())!=null){
                stringBuffer.append(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }
}
Line 9 check wheather the callback message is postback or not. If it is postback message then it will call sendPostbackMessge() method for checking and reply message.


private static sendPostbackMessge(Messaging event){
        List<string> postbackReplies =  testAndGetPostBackReplies(event)
        if (postbackReplies.size()>0){
            for (String postrep:postbackReplies){
                FacebookHelper.sendPostRequest(postrep);
            }
        }
    }

private static testAndGetPostBackReplies(Messaging event){
        List<string> postback = new ArrayList();
        String payload = event.postback.payload
        switch (payload){
            case "InitialPayload":
               postback = FacebookHelper.getInitialPostbackTemplate(event)
                break;
        }
        return postback
    }


public class FacebookHelper {
public static List<string> getInitialPostbackTemplate(Messaging event){
        List<string> replies = new ArrayList<string>();
        Message message = getMessage("Hello how can i help you?");
        String jsonReply = getJsonReply(event.getSender().getId(),message);
        replies.add(jsonReply);
        return replies;
    }
}


private static Message getMessage(String messg){
        Message message = new Message();
        message.setText(messg);
        return message;
    }



private static String getJsonReply(String senderId, Message message){
        Recipient recipient = new Recipient();
        recipient.setId(senderId);
        Messaging reply = new Messaging();
        reply.setRecipient(recipient);
        reply.setMessage(message);
        String replyJson = new Gson().toJson(reply);
        System.out.println("reply json------------------"+replyJson);
        return replyJson;
    }




getJsonReply method simply convert reply message in Json Format to post to client. In order to send message you have to call sendPostRequest() method.

public static String sendPostRequest(String payload){
        StringBuffer jsonString;
        try {
            URL url = new URL("https://graph.facebook.com/v2.6/me/messages?access_token=YOUR-PAGE-ACCESS-TOKEN");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            writer.write(payload);
            writer.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            jsonString = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            connection.disconnect();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return jsonString.toString();

    }


Now you can see the output when Get Started button is clicked for the first time.


In the next tutorial we will create a final shopping bot, which have image attachment, buttons, quick replies button, option menu and payment system.

Share:

Monday, March 6, 2017

How to create facebook messenger bot part 1

Facebook gives the large platform for the messenger. In this tutorial series, we are going to create our own facebook messenger bot.  Please refer facebook developer messenger platform here for the documentation. We are going to create simple messenger bot for shopping.



Step 1: The first thing is to create a facebook app and page if you don't have. so let's create facebook app and page.


Click to create the app and fill the pop up modal and create app id. This will create the page with app id number. Here click +add product to add messenger.


Now create facebook page of your own which is the identity of your bot so, include the appropriate name and image for the page. 

Step 2: Setup Webhook

In order to get the update or handle and process the messages of conversation between bot and the client, we required to setup callback Url to process messages. With the live server its fine but we have to develop on the local server, as our local server is not a live one so we have to tunnel our local server to live one. For this, we are using ngrok. Please refer my youtube video to set up ngrok.


Create bot application in your editor, run the application and tunnel it using ngrok. The tunneled url will be similar like this http://849ac456.ngrok.io/. 



1.Generate a page access token: Use the page created to generate page access token.


2.Setup Webhook(Callback URL):


Here callback ULR is where we process post and get request. we need to verify this token later. Subscription field messages is subscribed to get the update when the message has been sent to your page and messaging_postback is for postback replies. In order to verify we need to write verify code in the get request of callback URL.

class MessengerController {

   def verifyAndProcess(){
        if (request.getMethod() == 'GET'){
            if (request.getParameter('hub.mode') == 'subscribe' &&
                    request.getParameter('hub.verify_token') == "bot") {
                log.info("Validating webhook");
                response.setStatus(200)
                 render(request.getParameter('hub.challenge'))
            } else {
                log.error("Failed validation. Make sure the validation tokens match.")
                response.setStatus(403)
                render(false)
            }
        }else {
            processMessages() //for processing messages
        }

    }
}
Finally, click verify and save. Here I am using grails application if you are using servlet then you have to verify it in doGet method and process post request message in doPost method.

Now you have to subscribe your page.


Step 3: Create link to messenger
In order to chat with a bot, we have to simply provide the link to the messenger for this use following view.
<div class="jumbotron">
<div class="container">
<div class="page-header">
<h1>
Messenger Chat bot</h1>
</div>
<div class="fb-messengermessageus" color="blue" messenger_app_id="your app-id" page_id="your PAGE_ID" size="standard">
</div>
</div>
</div>
<script>

    window.fbAsyncInit = function() {
        FB.init({
            appId: "1201209609977381", //your app-id
            xfbml: true,
            version: "v2.6"
        });

    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

</script>





If you type some text in messenger after clicking message us button you  can see post response in ngrok history console as bellow.





In the next tutorial, we are going to learn how to handle this JSON format and make a bot to reply.


Share: