How to create your first Facebook Messenger Bot. 🤖 💪

A simple tutorial to create a Chatbot using Ruby on Rails and Facebook Messenger, step by step.

Facebook now allows bots to talk to users. You can book a flight, read some news, buy your next shoes or play with some game.

Facebook and the rest of the tech world are convinced that conversation is the future of business.

Chatbots use a process called deep learning, a type of machine learning in which a neural network can recognise speech, data, and specific patterns and transmit that data through the layers of the network.
This will be possible due to machine learning. In the near future, all of our devices will have similar abilities and will be able to take actions on our behalf.

1. Design the Experience

“You should message a business just the way you would message a friend,” declared Mark Zuckerberg when he launched the Facebook Messenger Platform for bots.

A great starting point could be the Principles of bot design:

  • Don’t pretend to be a human
  • Keep it incredibly simple
  • Respect the chat medium
  • Optimise for the end user
  • Provide an escape hatch

In my case, a booking chat service, I have chosen a close domain of interaction and possibilities, in just 5 steps:

1.1 Welcome Message

Hi there, let’s get started!
You’re now talking to the super cool Wine Tasting bot. 🤖🍷😀

A very informal message with only two possibilities:

  • Book a Wine Tasting.
  • Leave the bot chat and talk with a human.

1.2 Select a Wine Region

To facilitate the interaction and improve the conversions, the bot suggests the most popular area without asking anythings.

1.3 Chose a Wine Tasting

This one is probably the most important step. Throughout a great selection of results, some impressive photos and again, a simple interaction, you could transform users in conversions. 🤑🤑🤑

1.4 Login and Pay Button

To manage the user login and registration you can use Account Linking and a simple web-page.

Unfortunately, at this moment, Facebook Pay is still in Beta, so you could Request access to the beta program or manage payments throughout you site.

1.5 Get the Ticket and Receipt

One of most valuable benefit because every one should use a bot is have everything in the same place. Facebook messenger makes it possible to manage tickets and receipt easily.

2. Setup your Facebook Page

Now we need to create a Facebook Page and get the Page Access Token.

Create Facebook page (skip if you want to use existing page)

Open Facebook for Developers and get Page Access Token (step 3. Get Page Access Token from this tutorial).

3. Configure Rails

There are many Ruby library available that you could use to develop your first Facebook Messenger Bot, I chosen Messenger-Ruby:

“A simple library for supporting implementation of Facebook Messenger Bot in Ruby on Rails.”

3.1 Gemfile

Add this line on you Gemfile

YOUR_APP/Gemfile
gem 'messenger-ruby'

And then execute:

$ bundle install

3.2 Initializer

Create messenger.rb initializer in you app directory and paste Page Access Token:

Open messeger settings:

And then on right get the Page Access Token

YOUR_APP/config/initializers/messenger.rb
Messenger.configure do |config|
config.verify_token = '<VERIFY_TOKEN>' #will be used in webhook verifiction
config.page_access_token = '<PAGE_ACCESS_TOKEN>'
end

3.3 Routes

Add to your routes.rb:

YOUR_APP/config/routes.rb
mount Messenger::Engine, at: "/messenger"

3.4 Messenger Controller

Create messenger_controller.rb in your controllers directory — controller has to inherit from Messenger::MessengerController:

YOUR_APP/app/controllers/messenger_controller.rb
class MessengerController < Messenger::MessengerController
def webhook
#logic here
render nothing: true, status: 200
end
end

4 Initialize your Bot

4.1 Bot subscription

Run your application and:

  • Complete step 2. Setup Webhook from this tutorial if you mounted Messenger::Engine at /messenger and your application can be found at https://example.com, your Callback URL will be https://example.com/messenger/webhook
  • Select message_deliveries, messages, messaging_optins and messaging_postbacks under Subscription Fields.
  • Visit /messenger/subscribe in your app (it's replacement for 4. Subscribe the App to the Page step) - call subscribe action anytime you want to refresh subscription of your app.

4.2 Thread Setup

Configure the Thread Settings on Messenger to improve the user-experience of your integration. These settings apply to each page individually.

Get more info

4.2.1 Greeting Text

You can set a greeting for new conversations. This can be used to communicate your bot’s functionality. If the greeting text is not set, the page description will be shown in the welcome screen. You can personalize the text with the person’s name.

Greeting Text can be used as introductory text to help explain what your bot does. If you set the Greeting Text, it will be used instead of the page description.

Than open your terminal and setup the Greeting Text:

curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"greeting",
"greeting":{
"text":"Timeless apparel for the masses."
}
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"

4.2.2 Get Started Button

The Welcome Screen can display a Get Started button. When this button is tapped, we will trigger the postback received callback and deliver the person’s page-scoped ID (PSID). You can then present a personalized message to greet the user or present buttons to prompt him or her to take an action.

Than open your terminal and setup the Started Button:

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

5 Show the first message

5.1 Get a Postback

In the webhook action inside our MessengerController we need to get the postbaks form the client.

YOUR_APP/app/controllers/messenger_controller.rb
class MessengerController < Messenger::MessengerController
def webhook
     #Postback
if fb_params.first_entry.callback.postback?
        value = params["entry"].first["messaging"].first["postback"]["payload"]
        puts case tag
when "start"
#start message here
when "case-b"
#logic here
else
#logic here
end
     end
   end
end

5.2 Simple message with two buttons

Add the start message:

buttons = Messenger::Templates::Buttons.new(
text: 'Hi there, let’s get started! You\'re now talking to the super cool Wine Tasting bot. 🤖🍷😀',
buttons: [
Messenger::Elements::Button.new(
type: 'postback',
title: 'Book a Wine Tasting',
value: 'book'
),
Messenger::Elements::Button.new(
type: 'postback',
title: 'Chat with an Agent',
value: 'agent'
)
]
)
Messenger::Client.send(
Messenger::Request.new(buttons,fb_params.first_entry.sender_id)
)

6 List results in a message

You cold need to list some results in a message, in my case a list of wine tastings:

tastings = #here the query
#check if there are some results
if tastings.length > 0

#first message
Messenger::Client.send(
Messenger::Request.new(
Messenger::Elements::Text.new(text: 'Great I found those wine tastings for you! 🍇🍷👫'), fb_params.first_entry.sender_id)
)
#create the Bubble elements array
elements = []
tastings.each do |tasting|
item = Messenger::Elements::Bubble.new(
title: title,
subtitle: subtitle,
image_url: image_url,
buttons: [
Messenger::Elements::Button.new(
type: 'postback',
title: 'More info',
value: value
),
Messenger::Elements::Button.new(
type: 'web_url',
title: 'Book now',
value: url
)
]
)
elements.push(item)
end #end each
  #setup the template
generic = Messenger::Templates::Generic.new(
elements: elements
)
  #send message
Messenger::Client.send(
Messenger::Request.new(generic,
fb_params.first_entry.sender_id)
)
end #end if

At this point you should able to create your first bot easily, for more info check the Facebook developers and the Library documentations.

7 Start a conversation

7.1 Messenger code

A way to start a conversation whit a Facebook is scan a Messenger code:

Note: This feature is only available on iOS and Android.
Messenger Codes make it easy to start conversations with people or businesses that aren’t in your Messenger contacts yet. Scanning a person’s or business’s code with your phone will open the option to send them a message.

How do you use a Messenger code to start a conversation?

  1. Open the messenger App in your phone
  2. Go to “Me Tap”
  3. Tap My Code to let someone scan your code, or tap Scan Code to scan someone else’s

How do you download your Page’s Messenger code?

Your Page’s Messenger code is a unique code you can download and share to help people easily message your Page. When people scan your Page’s code using the Messenger app, they’ll start a conversation with your Page.

To download your Page’s Messenger code:

  1. Click Messages at the top of your Page
  2. Click i button in the bottom left
  3. Click Download in the box that opens up and select an image resolution

7.2 Simple HTML link

You can create a simple web link to start conversation: https://m.me/winetasting

<a href="https://m.me/winetasting">
Message us on Facebook
</a>

Download source code

Check out the example source code on Github.


If you enjoyed this article please recommend and share.
This is the post you are looking for.
Like what you read? Give Enrico Piovesan a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.