How to build a bot that automatically chat on Facebook Messenger

Recently, Facebook has opened the Messenger Platform platform to activate User Communication Bot via Facebook Apps and Facebook Pages application. In the following article, Network Administrator will guide you how to build a bot to automatically chat on Facebook Messenger.

Recently, Facebook has opened the Messenger Platform platform to activate User Communication Bot via Facebook Apps and Facebook Pages application.

In the following article, Network Administrator will guide you how to build a bot to automatically chat on Facebook Messenger.

How to build a bot that automatically chat on Facebook Messenger Picture 1How to build a bot that automatically chat on Facebook Messenger Picture 1

Here are the steps to create a chat bot on Facebook Messenger.

1. Set up

Messenger bot uses web server to handle messages that it receives or finds messages to send.

1.1. Build server

1. Download and install Heroku Toolbet here to start, stop and track incidents.

If you don't have an account, you can sign up for free at https://www.heroku.com.

2. Visit https://nodejs.org to install Node to create server environment.

Then proceed to open Terminal or Command Line Prompt to make sure you have installed the latest npm version by installing nmp again:

sudo npm install npm –g

3. Create a new directory and create a new project Node. Press Enter to accept the default value:

npm init

4. Install Node Dependencies service pack. Express for servers requiring message sending and body-parser to handle messages:

npm install express request body-parser --save

5. Create the index.js file in the directory and copy the code below to confirm the bot:

 var express = require('express') var bodyParser = require('body-parser') var request = require('request') var app = express() app.set('port', (process.env.PORT || 5000)) // Process application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: false})) // Process application/json app.use(bodyParser.json()) // Index route app.get('/', function (req, res) { res.send('Hello world, I am a chat bot') }) // for Facebook verification app.get('/webhook/', function (req, res) { if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') { res.send(req.query['hub.challenge']) } res.send('Error, wrong token') }) // Spin up the server app.listen(app.get('port'), function() { console.log('running on port', app.get('port')) }) 

6. Create a file and name the file Procfile, then copy the code below to let Heroku know which file to run:
web: node index.js

Confirm all code with Git then create a new Heroku code and "push" the code to the cloud:

 web: node index.js 

7. Confirm all code with Git then create a new Heroku code and "push" the code to the cloud:

 git init git add . git commit --message 'hello world' heroku create git push heroku master 

1.2. Set up the Facebook App application

1. Visit https://developers.facebook.com/apps/ to create or configure Facebook App or Page.

How to build a bot that automatically chat on Facebook Messenger Picture 2How to build a bot that automatically chat on Facebook Messenger Picture 2

2. On the application, switch to the Messenger tab and then click Setup Webhook . Here enter the URL of Heroku server and the token.

How to build a bot that automatically chat on Facebook Messenger Picture 3How to build a bot that automatically chat on Facebook Messenger Picture 3

3. Get Page Access Token and save this code.

How to build a bot that automatically chat on Facebook Messenger Picture 4How to build a bot that automatically chat on Facebook Messenger Picture 4

4. Go back to Terminal and enter the following command to activate the Facebook app to send the message. Note, use the token you used earlier.

  1.  curl -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" 

1.3. Set up Bot

1. Add API endpoint to index.js to perform message processing. Note, including the token you received earlier:

 app.post('/webhook/', function (req, res) { messaging_events = req.body.entry[0].messaging for (i = 0; i < messaging_events.length; i++) { event = req.body.entry[0].messaging[i] sender = event.sender.id if (event.message && event.message.text) { text = event.message.text sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200)) } } res.sendStatus(200) }) var token = "" 

2. Add a function to respond to the message:

 function sendTextMessage(sender, text) { messageData = { text:text } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { recipient: {id:sender}, message: messageData, } }, function(error, response, body) { if (error) { console.log('Error sending messages: ', error) } else if (response.body.error) { console.log('Error: ', response.body.error) } }) } 

3. Confirm the code again and push to Heroku:

 git add . git commit -m 'updated the bot to speak' git push heroku master 

4. Access Facebook and click Message to start chatting.

How to build a bot that automatically chat on Facebook Messenger Picture 5How to build a bot that automatically chat on Facebook Messenger Picture 5

2. Customize bot messages "say"

2.1. Send a Message message structure

Facebook Messenger can send a Message message structure in the form of a card or button.

How to build a bot that automatically chat on Facebook Messenger Picture 6How to build a bot that automatically chat on Facebook Messenger Picture 6

1. Copy the code below some index.js to send a test message in the form of 2 cards:

 function sendGenericMessage(sender) { messageData = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": "First card", "subtitle": "Element #1 of an hscroll", "image_url": "http://messengerdemo.parseapp.com/img/rift.png", "buttons": [{ "type": "web_url", "url": "https://www.messenger.com", "title": "web url" }, { "type": "postback", "title": "Postback", "payload": "Payload for first element in a generic bubble", }], }, { "title": "Second card", "subtitle": "Element #2 of an hscroll", "image_url": "http://messengerdemo.parseapp.com/img/gearvr.png", "buttons": [{ "type": "postback", "title": "Postback", "payload": "Payload for second element in a generic bubble", }], }] } } } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { recipient: {id:sender}, message: messageData, } }, function(error, response, body) { if (error) { console.log('Error sending messages: ', error) } else if (response.body.error) { console.log('Error: ', response.body.error) } }) } 

2. Update Webhook API to search for special messages to activate on the card:

 app.post('/webhook/', function (req, res) { messaging_events = req.body.entry[0].messaging for (i = 0; i < messaging_events.length; i++) { event = req.body.entry[0].messaging[i] sender = event.sender.id if (event.message && event.message.text) { text = event.message.text if (text === 'Generic') { sendGenericMessage(sender) continue } sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200)) } } res.sendStatus(200) }) 

2.2. Respond to user messages

What happens when a user clicks on a button or card on Message? In this case, update the Webhook API again to send the postback function:

  ``` app.post('/webhook/', function (req, res) { messaging_events = req.body.entry[0].messaging for (i = 0; i < messaging_events.length; i++) { event = req.body.entry[0].messaging[i] sender = event.sender.id if (event.message && event.message.text) { text = event.message.text if (text === 'Generic') { sendGenericMessage(sender) continue } sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200)) } if (event.postback) { text = JSON.stringify(event.postback) sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token) continue } } res.sendStatus(200) }) ``` 

Add Git, confirm and push up Heroku again.

Now you can chat with bot and enter "Generic" to see the bot.

Refer to some of the following articles:

  1. How to know if someone has read your message on Facebook Message?
  1. Steps to create Facebook ads
  1. Turn off Facebook, take time to visit these 37 Web sites to add new knowledge every day
  1. Trick to turn off notifications from Facebook on Chrome browser

Good luck!

3.7 ★ | 14 Vote