Writing Messenger bot in Java with Spring Framework
Previously I wrote about setting Messenger bot environment on own VPS. Today I’m writing about setting basic bot with Java and Spring Framework. To do so I’m needed:
After setting up basic Facebook page and creation of Facebook app, I had to select Messenger product, which will be used with my application. After that there is no much to do. Wee need to get:
Page access token, which is needed to send message
Set webhook for Messenger to receive messages
Set submissions for: messaging and messaging subscriptions
First submission is neeed to reply on messages, which is possible only up to 24h after receiving one. Second submission is needed to reply after 24h and reply periodically. But let’s do some coding first.
Well, that escalated quickly. Let me explain code above. Facebook sends POST request to mine webhook endpoint, which is deserialized as an Event class object, which JSON representation looks like that
I needed to create POJO classes to handle all parts of message. Here what’s interesting for us, is sender->id and message->text. Rest can be easily ignored. Here I used messengerController bean to handle reply containing reversed message (test on ASCII chars only plx or it fails :<). There is also a contract with Facebook, that after properly receiving message, application should return HTTP status 200. To send message back to Facebook I used retrofit2 library again. Simple message must only contain recipient and text components.
And that’s it. You can test your bot, by writing private message to facebook page connected with bot application as long as you are page / app admin. After that, when everything works properly, you apply for review and describe your bot commands. Later on one of Facebook non technical (!!!) employees will send described commands and some random ones, and if everything will work properly, your bot will be accepted and available for public.