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.
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.
2. On the application, switch to the Messenger tab and then click Setup Webhook . Here enter the URL of Heroku server and the token.
3. Get Page Access Token and save this code.
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.
-
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.
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.
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:
- How to know if someone has read your message on Facebook Message?
- Steps to create Facebook ads
- Turn off Facebook, take time to visit these 37 Web sites to add new knowledge every day
- Trick to turn off notifications from Facebook on Chrome browser
Good luck!
You should read it
- Instructions on how to mute chat on Facebook
- How to create snowfall effect on Facebook Messenger
- You should not ignore the group chat tricks on Facebook Messenger
- How to chat typeface in Facebook Messenger
- The easiest way to Install Facebook Messenger
- Fixed a bug with Facebook Messenger being escaped on iOS
- Only with Messenger tips, you'll know where the phone owner is
- Facebook Messenger is jumping from the morning, there is no radical solution
May be interested
- 17 billion video chat in 2017, Messenger is ready to challenge Skypeif you want specific numbers that show the 'huge size' of facebook messenger then this is what you need.
- How to use Facebook Messenger Web versionin addition to the facebook chat feature for users, you can easily make voice calls or video calls everywhere without losing a single fee.
- Facebook Messenger is jumping from the morning, there is no radical solutionfrom this morning (april 11), many facebook messenger users in vietnam have feedback on the character of the chat line on this messaging application, which is jumpy and uncontrollable.
- Facebook Messenger Kids: How to use?facebook has announced a new chat app called facebook messenger kids. the app allows parents to have control over who can chat with their children. this is how to use the application.
- How to create snowfall effect on Facebook Messengerfacebook messenger has updated the effect of creating snowfall when users chat with friends. with this effect, our conversation will be much more lively.
- To chat Facebook must use the standalone Messenger applicationfacebook will force ios and android users to download standalone facebook messenger apps if they want to continue chatting, and the company will remove messaging functionality from traditional facebook apps.
- The easiest way to Install Facebook Messengerfacebook messenger is a standalone application that allows you to chat and send messages with your facebook friends without accessing the facebook app. in some countries, you can create a messenger account without a facebook account.
- Simple way to give nick nicknames on Facebook Messengerone of the reasons that facebook is being used by so many people is that this social network constantly offers improvements to enhance the features and experiences for users. messenger application is no exception when adding a nickname feature to your chat nick.
- Guide to Facebook Messenger chat on Operaopera on the computer pinned the chat app facebook messenger, whatsapp and telegram in the sidebar, making it easy for users to chat.
- How to Delete a Group on Facebook Messengertipsmake today will guide you how to remove chat group (chat) from the list of messenger conversations on ios, android or messenger web version.