Assaf Elovic

@assafelovic

How to better build your first chatbot in under 12 minutes

Building a chatbot is actually building a conversation between two or more people

To skip the tutorial, feel free to download the source code from my Github repo here.

There are quite a few great tutorials out there for beginners about how to build a basic chatbot. However, most of these tutorials describe an implementation for stateless chatbots.

What that means is, that there’s no information saved regarding a user’s state in an ongoing conversation. For example, if the bot asks “What’s your location?” and the user replies “San Fransisco”, there’s no way for the bot to connect between the question and the user’s reply.

Since you’re building a chatbot, what you’re actually building is a conversation between two or more people. One of them happens to be your bot. Like in any conversation, your bot should know to reply to messages and understand when someone replies to his. In order to do that, you must save the history of past messages and defined conversation user states.

In my opinion, saving a user’s state within a conversation, is crucial and fundamental to any basic chatbot. It allows the chatbot to communicate with users in a natural flow and obtain necessary information for basic to advanced functionality, that otherwise would not be possible.

That’s why I’ve decided to write this tutorial, which explains how to build a basic stateful Facebook Messenger bot, which requires no prior chatbot development experience.

Getting started

For starters, you’ll need a Facebook developers account which can be found here.

Secondly, follow the beginning of the process for creating a Facebook page and set up a ‘Webhook’ (up until step 5) by clicking here. Note: You should write down the verification code which you’ve provided to the web hook in the tutorial. Lastly, once you’ve got a Facebook page up and running, look up the page token, and send a POST request with the following:

https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=<TOKEN_GOES_HERE>

You should get a response ‘true’ which means you’ve synced your Facebook page with the provided API.

Finally, please get familiar with the basics of Node.js and MongoDB. In addition, you should understand the basics of writing in ES6.

Now let’s create you very first Facebook messenger chat bot!

Facebook API Structured messages

First things first. Understand and learn the basic concepts of the Facebook API — click here. Let’s look at an example:

welcome_message: {
attachment: {
type: "template",
payload: {
template_type: "button",
text: "Hello and welcome to your first bot. Would you like to get see our products?",
buttons: [
{
type: "postback",
title: "Yes",
payload: "get_options"
},
{
type: "postback",
title: "No",
payload: "no_options"
}
]
}
}
}

In the example above, you can see that for every message sent to Facebook, we need to declare the type of message, which is in this case, is a template (for basic text, text is enough). In addition, we declare the template’s type which is buttons in this case, and the buttons themselves. For every button, we need to declare the button title, type and payload. The button type is so we’ll know how to handle the button click, and the payload is so we can identify which button the user clicked (a further example is described in the source code).

Server side

The basic and required implementation for the server side, is to set up a GET and POST handler for the Messenger webhook. The GET handler is for Facebook verification when applying your url webhook, and should be as follows:

function facebookVerification(req, res) {
res.send(req.query['hub.challenge']);
}

Note: the WEBHOOK_TOKEN above is to be set as you’ve declared when initializing the webhook. Facebook shows an example with ‘my_voice_is_my_password_verify_me’. You can leave it as is and update the source code.

The second and most important method is the POST. Facebook Messenger sends every ICM (Incoming message) sent to your bot page, via POST to the url you’ve declared in the developers portal. The method should handle all ICMs either those which arrived by user clicks, or by free text. Please note, that there’s many more templates you can add. I’ll describe three methods which are used in this case:

// 0
app.post('/webhook/', messengerListener);
// 1
function messengerListener(req, res) {
let messaging_events = req.body.entry[0].messaging;
for (let messagingItem of messaging_events) {
let user_id = messagingItem.sender.id;
getUser(user_id, messagingItem, parseICM);
}
res.sendStatus(200);
}
// 2
function
getUser(user_id, incoming_message, callback) {
User.findById(user_id, function (err, user_object) {
callback(user_id, incoming_message, user_object);
});
}
// 3
function parseICM(user_id, message_item, user_object) {
var current_state = "welcome_message";
if (message_item.message && message_item.message.text) {
fb_api.sendFacebookGenericMsg(user_id, message_templates.templates[current_state]);
}
user_models.set(user_id, {current_state: ""});
}

The first step (commented) is for listening to POST requests and forwarding them on to a method called messengerListener (method 1). This method then extracts from the POST body the relevant info such as the message item (consists of user unique id, message text, etc) and forwards the content to a method called getUser (method 2).

The method getUser (method 2), tries to retrieve a user with the given unique id from the DB. If the user is not found, a null is returned. Finally, the user query result is passed to a callback function which is in our case, parseICM (method 3).

The parseICM method, is in charge of sending an OGM (Outgoing message) based on the user’s ICM (Incoming Message) and current state. In the case above, the default state is “welcome_message”. The method first classifies the ICM type, which could either be a text message, or a clicked message (when user clicks on buttons the bot provided). Based on the ICM and user’s state, a relevant response message is sent back. There are additional methods declared in the code above, which I will not explain, since they are pretty much self explanatory and can be found in full in the source code provided at the top of this post (or at the end). Feel free to ask me any questions regarding any of the methods and general flow of the server side.

Finally, in order to send back a response to the end user, you’ll need to send a POST request with the message template as described above and with the following structure:

function sendFacebookGenericMsg(user_id, message_template) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: FB_TOKEN},
method: 'POST',
json: {
recipient: { id: user_id },
message: message_template
}
}, facebookCallbackResponse);
}

The FB_TOKEN shown above, is the page token you’ve received via the Facebook developers portal page.

Congratulations! You’ve completed your very first Facebook Messenger bot. The source code is built in such a way, that it’ll be very easy for you to scale it up to a fully functional chatbot.

From here, I highly recommend moving on to an article I’ve wrote, on how to improve your chatbot in 3 simple steps. The article includes simple ways on how to implement natural language understanding and conversation flow architecture design.

To view the full project source code, click here! Feel free to ask any questions, and I’ll answer you ASAP.

More by Assaf Elovic

Topics of interest

More Related Stories