Facebook launched the Messenger Platform, giving developers the ability to create bots that could have a conversation with people on Messenger or from a Facebook Page. With bots, app owners can better engage with their users by providing personalized and interactive communication that can scale for the masses. Since the launch, businesses and app owners have shown great interest in the chat bots. Just three months after the announcement, there was an estimated 11,000 bots built on the platform.
The current interest in and appeal of chatbots is obvious and as the technology in artificial intelligence improves, the bots will get better at interacting with users.
In this article, we’ll look at how to create a Facebook chat bot that can interact with users via Messenger on behalf of a Facebook Page. We’ll build a bot that gives the user different details regarding a movie that they specified.
Do I Need to Know AI to Build a Bot?
Being skilled in AI will certainly help, especially in building sophisticated bots, but is not required. You can certainly build a bot without knowing machine learning.
There are two types of bots you can build. One is based on a set of rules and the other uses machine learning. The former is limited in the interactions it can offer. It can only respond to specific commands. This is the type of bot we’ll be building.
With bots that use machine learning, you get better interaction with the user. The user can interact with the bot in a more natural way as they would in a human to human interaction, as opposed to just using commands. The bot also gets smarter as it learns from the conversations it has with people. We’ll leave building this type of bot for a future article. Machine learning knowledge will not be necessary, though. Lucky for us, there are services such as wit.ai and Api.ai that enable developers to integrate machine learning (specifically Natural Language Processing – NLP) into their apps.
Getting Started
For your chat bot to communicate with Facebook users, we’ll need to set up a server that will receive, process and send back messages. The server will make use of the Facebook Graph API for this. The Graph API is the primary way to get data in and out of Facebook’s platform. The server must have an endpoint URL that is accessible from Facebook’s servers, therefore deploying the web application on your local machine won’t work, you have to put it online. Also, as of version 2.5 of the Graph API, new subscriptions to the service have to use a secure HTTPS callback URL.
Before configuring your Messenger app on Facebook Developer, let’s create a bare minimum webhook with Node.js to get started.
Setting Up a Temporary Webhook Endpoint with ngrok
I choose ngrok to serves a localhost to a public URL because it is simple and easy to use. This URL will be used as a Messenger webhook endpoint during the development, so you don’t need to deploy to a server until the app is completed.
Download ngrok, install it on your machine, and run with a port number, let’s use 5000:
$ ngrok http 5000
When you start ngrok, it will display a public URL of your tunnel in the terminal. We will need the URL later when setting up the Facebook app. (In the screenshot, the URL is https://47ba4dd4.ngrok.io)
Writing a Webhook with Express.js
Create your app directory and set up your Node.js app:
$ npm init
Once you configure your app, install Express and body-parser:
$ npm install express body-parser --save
Let’s create a webhook.js, and instantiate express and listen the server to port 5000, or whatever the port you have set with ngrok:
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const server = app.listen(process.env.PORT || 5000, () => { console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env); });
Now, create HTTP GET and POST route method to handle the command:
app.post('/webhook', (req, res) => { console.log(req.body); if (req.body.object === 'page') { req.body.entry.forEach((entry) => { entry.messaging.forEach((event) => { if (event.message && event.message.text) { sendMessage(event); } }); }); res.status(200).end(); } });
This is how you receive messages to your webhook via Facebook Messenger- All requests should come via post, while the GET route is only used at the time you configure your Facebook app.
Where you see the w3tweaks_live_chat, just use an arbitrary string. You will need later when setting up your Facebook app.Run the code, and go to the next step.
$ node webhooks.js
Setting Up a Facebook App
You need a Facebook Page to set up your chat bot. Create one from facebook.com/pages/create. Choose a category, and select a sub category from the dropdown and fill out the required filed. Then click Get Started.
Then create an app at developers.facebook.com/quickstarts.
Give it a name and click the button, then fill out the required info:
Once your app is created, follow the steps to configure or skip it to your Dashboard.
Click Add Product from the left menu, then choose Messenger. Click Get Started.
At the Token Generation,
- Choose the page you just created from the dropdown menu, and it will generate a token
- That you will need to include in your node code.
- Then, at the Webhooks, click the Setup Webhooks button:
In the dialog, fill out the
- Callback URL with your ngrok URL
- The random string for validation (the one you’ve specified in your ‘GET’ route in the webhook.js)
- Check messages
Click the Verify and Save. If you get a red icon with x at the Callback URL, it means the URL is not validated- either the URL is wrong or your node code is not properly running. Otherwise, you are ready to get back to code.
Writing a Super Simple Chat Bot
Install request to POST messages:
$ npm install request --save
Continue with your webhook.js, let’s implement sendMessage() that simply replies the sender an echo to just test your Messenger bot:
const request = require('request'); function sendMessage(event) { let sender = event.sender.id; let text = event.message.text; request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, message: {text: text} } }, function (error, response) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); }
Where you see the PAGE_ACCESS_TOKEN, use the generated token.
Try running the code. This acts as a very simple bot, which interact the Messenger platform to receive a message and echo the message as the reply- Go to [https://m.me/YOUR-PAGE] and start a conversation. If you’re the simple bot works correctly, it just replies the exactly what you send.
Your entry is simply echoed back. This is boring, so let’s use API.ai next to make this conversation more interesting.
Leave a Reply