Developing a Facebook Messenger Bot (Part 2)

Messenger Code of my first Facebook bot

At the end of part 1 of this series, I had to wait half-way through the tutorial due to a bug in Facebook’s interfaces. This glitch has been fixed now, and so I continued my adventurous journey towards the first reply of my first Facebook Messenger bot today!

Finish configuration

I could finally see the page behind the “Messenger” navigation entry. This page–in contrast to all others–looks exactly like the screenshot in Facebook’s tutorial. I went ahead and chose an existing Facebook page to connect the bot to. If you don’t want to annoy your coworkers or fellow admins of a page, choose a page that is not in productive use or simply create a new one for experimenting (sorry Jan Weinkauff for annoying you with endless “test” and “hello world” messages!).

When selecting the page in the drop down, I actually had to click through the typical Facebook permissions. After that was done, I had to select the page again in the dropdown to actually get a page access token. Once I had the token, I subscribed the app to updates from this page:

curl -ik -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=<token>"

That went smoothly. The next step was to implement the actual webhook that will receive messages from the page…

Receive messages

To receive messages, I needed to add another route to my routes.rb in Rails. This had to have the same URL as the webhook for validating your bot, but this time it should respond to the POST method. This is simple in Rails:

 get ‘bot/webhook’ => ‘bot#webhook’
post ‘bot/webhook’ => ‘bot#receive_message’

The first route is for validating and uses my webhook action, the second route hands control for POSTs to the receive_message action. For the first implementation of receive_message on the controller, I chose to simply log the incoming params, so that I could learn what I will get from Facebook.

After deploying this to heroku and tailing the logs (“heroku logs -t”), I went to my Facebook page and sent me a message. You send the message just like you would send it to the page itself. In the logs I could see the params coming in.

The next step was to create a test (a request spec in this case) to simulate someone messaging my bot. I could simply copy and paste the log output I got above to get a nice little test.

post ‘/bot/webhook’, {
“object”=>”page”,
“entry”=>[{
“id”=>131808576776958,
“time”=>1460744104655,
“messaging”=>[{
“sender” => {“id”=>864963853529223},
“recipient” => {“id”=>131808576776958},
“timestamp” => 1460724946483,
“message” => {
“mid” => “mid.1450724945949:950df03e205e47ab34”,
“seq” => 2,
“text”=> “test”
}
}]
}],
“bot”=>{
“object”=>”page”,
“entry”=>[{
“id”=>131808576776958,
“time”=>1460744104655,
“messaging”=>[{
“sender”=>{“id”=>864963853529223},
“recipient”=>{“id”=>131808576776958},
“timestamp”=>1460724946483,
“message”=>{
“mid”=>”mid.1450724945949:950df03e205e47ab34",
“seq”=>2,
“text”=>”test”
}
}]
}]
}
}
expect(response).to be_success

(The ids are scoped to the page as always)

This gave me something to play around with locally and see how I can digest what Facebook hands me. Although Facebook has only examples for Node.js in their tutorial, I could quickly see that I can handle this data in Rails (this is NOT good code, but it was merely to get to receiving the first message).

def receive_message
if params[:entry]
messaging_events = params[:entry][0][:messaging]
messaging_events.each do |event|
sender = event[:sender][:id]
if (text = event[:message] && event[:message][:text])
# send_text_message(sender, “Hi there! You said: #{text}. The Bots”)
end
end
end
 render nothing: true
end

So now I could receive messages. The final step would be to reply to them…

Send messages

Sending a message is as simple as POSTing a JSON object to Facebooks Graph API. However, I had to go through some trial and error to find out how to map Facebook’s Node.js code to a call from Rails.

First thing for this is to add the HTTParty gem to be able to make simple calls to an API. I implemented the send_text_message method (the one I commented out in the above receive_message code) with HTTParty and then uncommented the line in the receive_message method.

Now my little request spec was very helpful in trying to figure out how to call the messaging API correctly. Without the spec I would have to have deployed the whole thing to Heroku after every minor change, go to the Facebook page, send me a message and then look at the logs. With the spec I simply ran it locally and read the errors from the logs.

It turned out that I had to pass the access token as a regular parameter and the payload as JSON. At first I also forgot to set the ContentType in the header to JSON, too.

body = {
recipient: {
id: sender
},
message: {
text: text
}
}.to_json
response = HTTParty.post(
https://graph.facebook.com/v2.6/me/messages?access_token=#{page_access_token}",
body: body,
headers: { ‘Content-Type’ => ‘application/json’ }
)

After deploying this, I could celebrate! My bot was happily replying to all my messages :).

What’s next?

I found it pretty nice that you clearly see in your Facebook page admin interface, which messages were sent by a bot. Another nice surprise was to get a Messenger Code image, so people can get in contact with the bot without having to type the name (The Verge has an article about it). This seems to be a useful addition to make contacting companies and software systems even easier. Unfortunately as of today (Saturday after F8), my Messenger app on a German iPhone 6 does not yet support scanning of these codes — the price you pay for playing with cutting edge technology :P. But there is also another nice and simple way for people to contact a bot via Facebook’s m.me/ URL: to reach my test bot for example, simply go to http://m.me/thebotsbot.

My next steps will be to play a little with this and other Messenger bots, check out wit.ai to help me with language processing and then brainstorm with my team about possible business applications of this technology. Finding real problems of real people out there, for which a product around a Messenger bot could be a viable solution, is the most fun, but also the most challenging task. We do this at Dreimannzelt almost every day for our customers, but still identifying real problems and coming up with businesses to solve them remains challenging every single time. Do know any real-world problems to which a Messenger bot could be a great solution?

I would love to hear about your ideas in the comments. And if you liked these little articles, I would be very glad if you’d give them some ♥︎ below.