Last Updated On:

It’s been over three years since Facebook announced the launch of Facebook Messenger chatbots. Since then, loads of brands have created their own chatbots and added them to Facebook Messenger in a bid to improve their customer service.

By 2018, there were more than 300,000 chatbots on Facebook Messenger. This marked an increase of 100,000 chatbots in just one year.

From these numbers, it’s evident that Facebook Messenger chatbots are beneficial for brands. They help improve the quality of customer service by solving the customer’s queries within minutes.

A Facebook Messenger chatbot can instantly reply to any message, thus removing the waiting time for customers. Additionally, it’s available 24×7, unlike human customer support, which may not be present round-the-clock.

It can also help brands save on recurring expenses such as the salaries of their staff. You can even use one to market new products and simplify the purchasing process.

With the advent of AI-powered chatbots, you can expect your customer experience to skyrocket on implementing them.

While it may seem difficult to develop your own Facebook Messenger chatbot, it’s not as hard as you may think. There are thousands of platforms out there that can help you build a Facebook Messenger chatbot.

You can even find many online chatbots that you can directly integrate into Facebook Messenger.

Now, let’s take a look at how to develop a Facebook Messenger chatbot from scratch. Here’s how you can do it.

1. Choose Your Platform for Facebook Messenger Chatbot

The two major platforms that you can use to build your Facebook Messenger chatbot are Dialogflow and Wit.ai. Dialogflow is a service by Google while Facebook owns Wit.ai. Let’s take a look at them:website traffic ebook

a. Dialogflow

This platform allows you to natural language processing, speech to text, and artificially intelligent systems. You can train them by creating your customized functionality.

Through machine learning, this tool can understand what users are talking about. The best parts about this platform are that it can recognize over 15 languages, is free, and makes it easy to create a chatbot.

However, it’s not very customizable, and you may find it challenging to do platform implementations.

Dialogflow Facebook Messenger Chatbot

Image via Ignite Visibility

b. Wit.ai

Wit.ai is also similar to Dialogflow and helps you process natural language. In addition, it can filter out useful data such as context and intent.

The user-friendly UI makes it easy to develop your first Facebook Messenger chatbot. Just like Dialogflow, it’s free, adaptable, and integrates NLP. However, it may take you some time to learn how to implement it and isn’t very visual as well.

While Wit.ai is a great platform, Dialogflow is better for beginners and has extensive documentation to guide you through as well.

Hence, we’ll take a look at how you can develop your Facebook Messenger chatbot using it.

wit.ai Facebook Messenger Chatbot

Image via Gupshup.io

2. Set up the Development Environment

You need to start by creating a webhook that provides other apps with real-time data. Unlike other APIs, it continuously keeps sending data to other applications. To create this webhook, you can use Express.js.

Start by creating a directory called “Facebook Messenger chatbot.” On creating this, you can go to the terminal and initialize Node.js. Once you’ve done this, you can install Express.js to create a server. You’ll also create a middleware called body-parser for parsing new incoming requests.

For this, you need to type the following in the terminal:

npm install express body-parser –save

Post the installation, go to the directory and make a file called index.js. After that, start the Express server and set the listening to port 3000. Save it.

To check if it’s working, you can run the following in the terminal.

node index.js

If it’s working, you should get a message that says, “Webhook server is listening, port 3000.”

Now, you need to create two endpoints. The first is for the initial verification of Facebook. You’ll need to get a token as you’re connecting a Facebook page with the webhook server.

This token shall be matched with the webhook server’s response to ensure it’s the same server. The second endpoint is for all the other messages that you receive from Facebook Messenger.

To simplify things, separate your code in two folders. You can name them controllers and helpers. The first endpoint should be created in controllers and be named verification.js. The code for it is:

module.exports = (req, res) => {

const hubChallenge = req.query[‘hub.challenge’];

const hubMode = req.query[‘hub.mode’];

const verifyTokenMatches = (req.query[‘hub.verify_token’] === ‘mynewbot’);

if (hubMode && verifyTokenMatches) {

res.status(200).send(hubChallenge);

} else {

res.status(403).end();

}

};

You can change the string called “mynewbot” to anything you wish. Do keep it in mind as you will need it later while setting up the Facebook app.

The second endpoint too goes in the controller folder and is called messageWebhook.js. The code for it is as below:

const processMessage = require(‘../helpers/processMessage’);

module.exports = (req, res) => {

if (req.body.object === ‘page’) {

req.body.entry.forEach(entry => {

entry.messaging.forEach(event => {

if (event.message && event.message.text) {

processMessage(event);

}

});

});

res.status(200).end();

}

};

Once you’ve done this, stop the console by typing:

node index.js

3. Setup Proxy Server

It is necessary to setup a proxy server because our local Express server isn’t available for everyone on the internet. Additionally, the server doesn’t support HTTPS, however, you need it as it’s a necessity for Facebook Messenger. For this, you can set up a grok server.

To set up a grok server, you can use ngrok. It helps in setting up secure tunnels from public endpoints to your local network. After installing ngrok, you need to open the terminal and then type the following

ngrok http 3000

You’ll get a new screen that shows you multiple URLs. The URL that you need is the last one on the list.

Setup server proxy Facebook Messenger Chatbot

Image via Docksal Documentation

4. Setup Facebook App

For setting up a Facebook Messenger chatbot, you need to first set up a Facebook app. For this, you need to have a public page and a Facebook Developer application. The latter will be connected with your public page and webhook server and will serve as a middleware.

Once you’ve created a Facebook page, you should head to Facebook for Developers to create your app. Give it a name, fill in your email ID and click on “Create App ID.” Post that, you need to select a product. For this, click on “Messenger” and then tap “Set Up.”

Once the page opens, find the “Token Generation” section, and then select the page that you’ve created. This will give you a Page Access Token. Save it.

Below this section, you’ll find the Webhooks section. You need to click on “Setup Webhooks” and fill out Callback URL, Verify Token, and Subscription Fields. Once you’ve done this, you need to integrate Dialogflow into the application.

5. Integrate Dialogflow

To integrate Dialogflow, head to their website and then sign up on it. Now, you can start preparing your virtual assistant and teach it specific skills that you need it to have. Begin by clicking on “Create Agent” and fill in the details of your agent. This includes its name, description, language, and time zone.

Now, head to the section named “Small Talk” and click on “Enable.” Once you’ve done that, you can try your Facebook Messenger chatbot on the right side by asking it simple questions.

You need to them embed the conversation that you have with the Facebook Messenger chatbot in your codebase. However, to do that, you need to first install two packages in your terminal. The first is a request node page that can be used to send requests to Facebook.

This can be done by:

npm install — save request

The second one is the Dialogflow node.js package, for this you need to type the following in the console:

npm install — save apiai

You need to now implement the processMessage function by creating a file in the helpers directory and naming it processMessage.js.

Now, initialize your apiaiClient using the API key (Client Access Token). It should be entered in the const API_AI_TOKEN. On the other hand, the Facebook Page Access Token should be added to the const FACEBOOK_ACCESS_TOKEN. You can use the following code for doing so:

const API_AI_TOKEN = ‘your Dialogflow Client Access Token’;

const apiAiClient = require(‘apiai’)(API_AI_TOKEN);

const FACEBOOK_ACCESS_TOKEN = ‘your Facebook Page Access Token’;

const request = require(‘request’);

const sendTextMessage = (senderId, text) => {

request({

url: ‘https://graph.facebook.com/v2.6/me/messages’,

qs: { access_token: FACEBOOK_ACCESS_TOKEN },

method: ‘POST’,

json: {

recipient: { id: senderId },

message: { text },

}

});

};

module.exports = (event) => {

const senderId = event.sender.id;

const message = event.message.text;

const apiaiSession = apiAiClient.textRequest(message, {sessionId: ‘crowdbotics_bot’});

apiaiSession.on(‘response’, (response) => {

const result = response.result.fulfillment.speech;

sendTextMessage(senderId, result);

});

apiaiSession.on(‘error’, error => console.log(error));

apiaiSession.end();

};

Also add the following to index.js.

const verificationController = require(‘./controllers/verification’);

const messageWebhookController = require(‘./controllers/messageWebhook’);

app.get(‘/’, verificationController);

app.post(‘/’, messageWebhookController);

This code shows that your webhook server received information from a user on Facebook Messenger. This text was then passed to Dialogflow. Once the response came from there, a response event got triggered, and that got sent back to Facebook Messenger.

You need to then test your Facebook Messenger chatbot to perfect it. For this, you should add testers for it. To do so, you can open the Facebook App and head to “Roles. ” In this, select “Testers” and click on “Add Testers” to add people.

Now, you need to begin testing your Facebook Messenger chatbot. You need to assess the replies that your bot is giving for simple questions such as “How are you?”

Once the chatbot passes this test, you need to increase its intents. These are essentially mechanisms that help the chatbot understand what the user is asking and help it respond according to it.

6. Create Intents for Your Facebook Messenger Chatbot

For this, you need to first login to the agent to which you want to add the new functionality. Post that, go to Dialogflow and click on the “+” in the intents section. First, you need to name the intent, let’s say, “shane-barker-info”.

In the box that says “User says”, enter all the possible questions that the user can ask related to that topic. To improve the accuracy of your Facebook Messenger chatbot, you should add as many questions as possible.

Once you’ve listed down the questions, you need to tell your Facebook Messenger chatbot to take an action based on them. For this, go to “Action” and type an action in lowercase. You must also add responses to the questions.

To add them, go to “Responses” and add multiple responses. You can then save the intent.

After saving the intent, you should test the same by asking test questions in the console on the right. It’s not necessary to ask the same questions as you’ve entered; they can be similar to them.

Check if the answers that you get are the same as the responses you’ve entered. Through machine learning, Facebook Messenger chatbot understands your question and gives the right answers.

Lastly, head to Facebook Messenger and check if your chatbot is working well.

Final Thoughts

Creating a Facebook Messenger chatbot may seem like a daunting task at first, but with the right tools, you can create it easily. Using Node.js, Express.js, ngrok, and Dialogflow, you can design your very own chatbot.

While you may need some level of coding knowledge, it is also possible to get it done with just the codes I’ve mentioned in this post. Alternatively, you can use one of the readily available AI-chatbots and integrate them into Facebook Messenger.

Add various intents to it to help it answer more questions from your customers. Consider adding as many possible questions to improve its accuracy. This way, by making a chatbot, you’ll be able to improve your customer service.

Need help designing your Facebook Messenger chatbot? Get in touch with me for further details.conversion consultant