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:

9 comments:

  1. Great post. Please keep posting on bots.

    ReplyDelete
    Replies
    1. Thank you, and please visit with my updated posts.

      Delete
  2. Please post some more. Your video is the one who i can understand the most

    ReplyDelete
    Replies
    1. Sure, I will post soon to complete it. please subscribe my youtube channel and blog. Thanks.

      Delete
    2. Hello Mr Kumar, i have some question to ask. Above codes are written in JAVA? means if i run this script it will appear the GetStarted button? how do i run the script in order to have buttons and all those. Please help

      Delete
    3. Yes, this is java code. Yes of course if you run those raw body content you can see get started button and welcome screen this is independent of programming languages although you can set from your programming also. For the request for the raw content you can simply use "curl" try it from terminal in linux or command prompt in window.
      https://developers.facebook.com/docs/messenger-platform/thread-settings/greeting-text.

      please visit this. And also you can simply use other extension like Postman as I suggested.

      Delete
  3. so all the above codes are supppose to JAVA ? im using netbeans to do JAVA.
    AND can u do the tutorial of quick replies and others button cause im stuck at there. i watch 1st video and it successfuly get the getStarted button. Now i need to do quick reply button, but i dont know how.

    ReplyDelete
    Replies
    1. Please visit documentation of facebook:https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies
      As I did with postback replies please try that one first and for quick replies
      if (event.postback != null){
      sendPostbackMessge(event);
      }else if(event?.message?.quick_reply){
      sendQuickReplies(event);
      }
      Please view the json in ngrok and try to implement for quick reply which is similar to sendPostbackMessge() method.

      Delete
    2. every single code you screenshot, is it all need to be in script? how do i know what sequence? do u have this JAVA file , can send? I still a bit dont understand

      Delete