A Facebook Messenger BOT With Java

574 views Asked by At

I try to create a facebook messenger bot I tried Victor de la Cruz method,the code is below , and here is the origin code: https://www.codementor.io/@vcg_cruz/a-facebook-messenger-bot-m2g6wgcxb#comments-m2g6wgcxb it works but when I send a message it generates an infinite loop of conversation this the result screen shot

    @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);

    }
}
/************************************/
@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;
}
1

There are 1 answers

1
MSWS On

You're responding to yourself I assume. Similar to how the Discord API works, your post method is being called when you receive your own message. You most likely want to check if the message author is from yourself.