How to Develop Facebook Messenger Bot (Guide)
Facebook'southward "messenger bots" feature is nothing new, and a lot of awesome bots already exist. Nonetheless, the resources regarding exactly how to build your very own bot are scarce, and lacking in caption for people who are new to the Facebook Graph API. Messenger bots at present also crave you to use a SSL secured webhook callback URL (more on that later), and setting upwardly SSL is non for anybody, and also costs coin.
In this article, I'll walk yous through the entire process of creating a simple Facebook messenger bot, considering Facebook's own documentation is rather poorly explained. We volition gear up a cloud app that uses https protocol, code the bot in Node.js (which is a javascript, server-side language), employ git to button the code to the cloud awarding, and test it out on Facebook Messenger.
Setup Bot
You lot will demand Node installed on your laptop. If you don't, become to the Node website to download and install it.
Once you are done, you tin keep with the setup for the bot. Follow the steps below:
1. Launch Terminal.
2. Y'all need a separate directory for belongings your code.
- Make a new directory
mkdir testbot
- Change your working directory to the directory you but created
cd testbot
iii. Next, initialise the Node application.
npm init
- Yous will be asked to enter information about your application, merely employ the defaults by pressing Enter for everything.
4. Install packages
npm install express trunk-parser asking --save
- The command volition run, and give some warnings; ignore them.
5. In Finder, open the directory "testbot" that you created, and find the file named "package.json"; open this in an editor similar Sublime Text.
half dozen. In this file, we need to add a line
"start": "node index.js"
- Don't forget to suspend a "," at the cease of the previous line.
seven. Next, create a new file in Sublime Text, and put in the following code inside it:
[js]
var express = crave('limited');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.employ(bodyParser.urlencoded({extended: faux}));
app.employ(bodyParser.json());
app.listen((process.env.PORT || 3000));
app.get('/', function (req, res) {
res.send('This is TestBot Server');
});
app.become('/webhook', function (req, res) {
if (req.query['hub.verify_token'] === 'testbot_verify_token') {
res.send(req.query['hub.challenge']);
} else {
res.send('Invalid verify token');
}
});
[/js]
Save this file as index.js
Annotation: In Line xiii, the value of 'hub.verify_token' is set every bit 'testbot_verify_token', recall this value equally it will exist used when creating the webhook in Facebook.
Create Git Repository
Now that we have set up our bot'southward callback handling, we need to push the code to Heroku. For that, nosotros need to create a git repository in our directory.
Note:"git" is a version command system for files and software code. You tin can read more than well-nigh information technology on Wikipedia.
Creating a git repository is easy, and only takes a couple of Terminal commands.
Note:Make sure yous are inside the "testbot" directory in the Last. Yous can practise this by typing the control pwd
into the Last.
Follow these steps to create a git repository:
1. git init
2. git add .
3. git commit -grand "Annals Facebook Webhook"
Setup Heroku
Earlier nosotros even go into Facebook's developer pages, we demand a callback URL that Facebook can talk to. This URL needs to use the https protocol, which means nosotros demand to install an SSL document on our website; but, this is a beginner's guide to Facebook messenger bots, so allow's not complicate things. We'll utilize Heroku to deploy our lawmaking. Heroku gives yous https URLs for your applications and has a free programme which meets our (very basic) demands.
Become to the Heroku website and annals yourself.
Note:In the field that says "Pick Your Primary Development Linguistic communication", use "I use another Language".
Once you're done with that, install the Heroku toolbelt for your OS (Mac, for me), and install it. This will give you access to Heroku on your Last (or control prompt, on Windows).
Next, nosotros volition create an app on Heroku, which will hold the entire code for our bot. Follow the steps below:
1. Launch Terminal
2. Type heroku login
- You will exist asked to enter your email and password.
- Blazon your electronic mail, hit Enter; and so, blazon your countersign, hit Enter.
- You lot will be logged in to heroku
3. Type heroku create
- This will create an app on Heroku and provide you with a hyperlink. Note that the link is using the https protocol. Easy, right?
4. Now you tin push your app code to Heroku
git push heroku principal
5. Once this is washed, your app is basically alive, and you can visit the link in your browser to check that everything is working fine. It should open up a webpage saying "This is TestBot Server".
Facebook Setup
It's time to connect our bot to Facebook! You volition need to create a new Facebook Folio or use an existing 1 that yous ain. I'll show you lot how to proceed past creating a new Facebook Page.
1. Go to Facebook and create a new page.
- You tin can create a page in whichever category you lot want. I'm opting for Company/System, for no particular reason.
two. The next steps that Facebook shows are optional, and can be skipped.
3. Next, head over to the Facebook Developers' Website.
- On the top-correct, hover your mouse on "My Apps" and and so click on "Add a New App" from the drop-downwardly carte.
- Click on "bones setup" when Facebook prompts yous to cull a platform.
4. Make full upward the details for your App Proper name and contact email address.
- Select "Apps for Pages" in the Category.
- Click on "Create App ID".
5. Yous will be taken to the dashboard for your app. On the sidebar, navigate to "+Add Products" and select "Messenger" past clicking on the "Get Started" button.
6. Select "Setup Webhooks".
7. Fill upwardly the required fields, replacing the "Callback URL" with the URL of the Heroku app, Verify Token with the token used in the alphabetize.js file, and select the following Subscription Fields:
- message_deliveries
- messages
- message_optins
- messaging_postbacks
Note:Make sure you lot suspend "/webhook" to the Callback URL then that index.js executes the required function when Facebook tries to ping the URL, it can verify the "Verify Token".
viii. Click on "Verify and Relieve".
9. In the "Token Generation" section, click on "Select a Page" and select the page y'all created earlier.
This volition generate a "Page Admission Token", save it somewhere; you volition need it later.
x. Adjacent, you will have to make a Postal service query to your app, using the Folio Access Token generated in the last pace. This tin exist hands done in the Terminal. Merely run the following command, replacing PAGE_ACCESS_TOKEN with the Page Access Token you generated.
scroll -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=PAGE_ACCESS_TOKEN"
You lot should receive a "success" response in the Final.
More Heroku Setup
Yes, nosotros're non done, yet. Not near.
1. Go to the Heroku website and log in with your email ID.
2. Locate your app in the "dashboard" and click on it.
3. Navigate to the Settings tab.
iv. Click on "Reveal Config Vars"
5. Add the PAGE_ACCESS_TOKEN as a "config var", and click "Add".
Coding the Actual Bot
Now that we're done with the grunt piece of work, we tin focus on what actually matters: making the bot respond to messages. To commencement off, we'll just design a bot that simply echoes the letters it receives. As it turns out, this simple task requires a considerable bit of lawmaking to part.
i. Coding the Message Listener
Before the bot can echo dorsum the message, it needs to be able to listen for letters. Permit's do that first.
In the index.js file, add the following code:
[js]
app.mail('/webhook', function (req, res) {
var events = req.torso.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var issue = events[i];
if (event.message && event.message.text) {
sendMessage(event.sender.id, {text: "Echo: " + upshot.message.text});
}
}
res.sendStatus(200);
});
[/js]
What this function does, is it checks for received messages, then checks if there is text in the message. If it finds text in the received message, information technology calls the sendMessage (shown subsequently) function, passing the sender's ID and the text to transport back. Information technology'south important to empathize the following values and what they hateful:
- event.message.text is the text received in the bulletin. For example, if someone sends the message "Hello" to our bot, the value of upshot.message.text volition be "Hello".
- event.sender.id is the id of the person who sent the message to the bot. This is required so that the bot knows whom to address the response to.
2. Coding the sendMessage Function
Lets code the "sendMessage" function, at present.
[js]
function sendMessage(recipientId, bulletin) {
request({
url: 'https://graph.facebook.com/v2.half dozen/me/letters',
qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
method: 'Postal service',
json: {
recipient: {id: recipientId},
message: message,
}
}, office(error, response, body) {
if (error) {
console.log('Error sending bulletin: ', fault);
} else if (response.torso.error) {
panel.log('Error: ', response.body.error);
}
});
};
[/js]
The "sendMessage" part takes two parameters:
- recipientId
- bulletin
The recipientId is required then that the message can be addressed to the right user.
The message is the actual text that is to exist sent in the response.
3. Pushing the Changes to Heroku
If yous have completed the steps above, your bot should be able to echo dorsum the received text. Just start, you lot have to push button the changes to the application hosted on Heroku. To exercise this, follow the steps given below:
1. Launch Final.
2. Modify directory to your testbot directory
cd testbot
3. Do the following steps:
- git add .
- Note:There is a "." at the terminate of "git add"
- git commit -m "First commit"
- git push heroku master
4. Now send a bulletin to your page, and the bot will echo the message dorsum to you.
Conditional Responses aka Making the Bot Smarter
We tin use text matching to allow our Facebook messenger bot to respond according to certain special keywords.
To attain this, nosotros demand to add another function. I'k naming it "conditionalResponses", merely yous can choose whatever name y'all prefer.
1. Coding the conditionalResponses Part
[js]
function conditionalResponses(recipientId, text) {
text = text || "";
var what = text.match(/what/gi); //check if text cord contains the discussion "what"; ignore case
var beebom = text.match(/beebom/gi); //check if text cord contains the word "beebom"; ignore example
var who = text.friction match(/who/gi); //check if text string contains the give-and-take "who"; ignore example
var you = text.match(/you/gi); //check if text string contains the word "you"; ignore case
//if text contains both "what" and "beebom", do this:
if(what != aught &&; beebom != null) {
message = {
text: "Beebom is a website offering tech resource. Welcome."
}
sendMessage(recipientId, message);
return true;
}
//if text contains both "who" and "you", exercise this:
if(who != null && y'all != nil) {
message = {
text: "I take been asked not to discuss my identity online."
}
sendMessage(recipientId, message);
return truthful;
}
//if nix matched, return false to go on execution of inner role.
return false;
};
[/js]
In lines 4 to 7, we accept defined variables depending on matching the received string against item words. The best function well-nigh using "text.match()" is that information technology uses Regular Expressions (commonly called regex, read more here.). Information technology is good for us, because this ways that as long equally even a part of a word in the received text matches with either of the words nosotros mentioned in text.lucifer(), the variable will not exist zero. This means, that if the received message was "What'south Beebom?", "var what" and "var beebom" volition not be aught, considering the discussion "What'south" contains the word "what". So nosotros are saved from creating extra statements for every variation in which someone might say "What".
2. Editing the Message Listener
We too need to edit the Message Listener we coded, to ensure that information technology tries to match the received text with the "conditionalResponses" office also.
[js]
app.post('/webhook', role (req, res) {
var events = req.torso.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (issue.message && event.bulletin.text) {
//first try to check whether received message qualifies for conditional response.
if(!conditionalResponses(consequence.sender.id, event.message.text)) {
//if it doesn't, simply echo the received message back to the sender.
sendMessage(outcome.sender.id, {text: "Repeat: " + event.message.text});
}
}
}
res.sendStatus(200);
});
[/js]
The changes in the listener might not look very drastic, simply their effects sure are. Now, the listener first tries to respond with conditional responses, and if there is no valid condition for the received message, it just echoes the message back to the user.
3. Pushing the Changes to Heroku
Before you can endeavour out the new features, you will have to push the updated code to the app hosted on Heroku. Follow the steps beneath to do this:
ane. Launch Terminal.
ii. Change directory to your testbot directory
cd testbot
3. Practice the following steps:
- git add .
- Note:In that location is a "." at the finish of "git add"
- git commit -m "Adding provisional capabilities"
- git push heroku primary
4. At present send a message to your page, and the bot will echo the message dorsum to you.
Even More Functionality
Our bot at present responds to a pocket-size prepare of commands in nice, well structured responses. Merely it'southward still not very useful. Allow'due south make some more than changes to the code to make our bot a more "functional" piece of software. We'll exist revamping a lot of functions, and calculation a couple more, then become excited.
1. Editing the Message Listener
Our bulletin listener, at this stage, works just ok. Withal, it's not very nicely formatted and if nosotros were to keep increasing the nested if statements to add extra "condition checks", it will chop-chop go ugly to look at, difficult to understand and slower at execution. We don't desire that, now, do nosotros? Permit'southward make some changes.
Annotation:There's a line of code in the message listener that reads"res.sendStatus(200)", this line sends a condition 200 code to Facebook, telling it that the function successfully executed. According to Facebook's documentation, Facebook waits for a maximum of twenty seconds to receive a 200 status, before information technology decides that the bulletin didn't go through and stops execution of the lawmaking.
Our new message listener looks similar this. We use the "res.sendStatus(200)" command to cease execution of the part every bit soon as a status is matched and executed.
[js]
app.postal service('/webhook', function (req, res) {
var events = req.torso.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var issue = events[i];
if (event.message && event.message.text) {
//first cheque bulletin text against introResponse conditions
if(introResponse(event.sender.id, issue.message.text)) {
res.sendStatus(200);
}
//for lack of a ameliorate name, I chosen this newResponse :p; check this adjacent
else if(newResponse(event.sender.id, event.bulletin.text)) {
res.sendStatus(200);
}
//else, just echo back the original message
else {
//supercede echo with valid command listing
sendMessage(issue.sender.id, {text: "Repeat: " + outcome.bulletin.text});
}
}
}
res.sendStatus(200);
});
[/js]
2. Coding the newResponse Function
Our message listener now checks the message text confronting a set of conditions in"newResponse" as well, but beginning, we need to lawmaking the newResponse function. We will be using this function to check if the user asked for article suggestions from the Beebom website, search the query term on the website, and present the link to the user. Once again, we will use regular expressions to match text with specific keywords.
[js]
part newResponse(recipientId, text) {
text = text || "";
var propose = text.match(/suggest/gi);
var random = text.friction match(/random/gi);
var article = text.lucifer(/article/gi);
var iphone = text.lucifer(/iphone/gi);
var android = text.match(/android/gi);
var mac = text.match(/mac/gi);
var browser = text.match(/browser/gi);
var vpn = text.match(/vpn/gi);
//check if user is asking for article suggestions at all
if(suggest != null && article != null) {
var query = "";
//if commodity suggestions are queried, check the topic the user is looking for
if(android != cypher) {
query = "Android";
} else if (mac != null) {
query = "Mac";
} else if (iphone != goose egg) {
query = "iPhone";
} else if (browser != null) {
query = "Browser";
} else if (vpn != null) {
query = "VPN";
}
sendButtonMessage(recipientId, query);
return truthful
}
return false;
};
[/js]
We are using another custom function called"sendButtonMessage"to transport the message in instance the user is asking for article suggestions. Nosotros will create this next.
3.Coding the sendButtonMessage Function
The sendButtonMessage function takes 2 parameters, a recipient ID and a query.The recipient ID is used to place the user to whom the message must be sent, and the query is used to identify the topic on which the user wants article suggestions.
[js]
function sendButtonMessage(recipientId, query) {
var messageData = {
recipient: {
id: recipientId
},
message: {
zipper: {
blazon: "template",
payload: {
template_type: "button",
text: "This is what I establish for "+query,
buttons:[{
blazon: "web_url",
url: "https://beebom.com/?southward="+query,
title: "Beebom: " + query
}]
}
}
}
};
callSendAPI(messageData);
}
[/js]
Once over again, we are using a custom function; this time to ship the final message, with the commodity links, to the user. The function is, in many ways, similar to the"sendMessage"function we coded earlier, merely is more than generic in the fashion it takes the message data, which suits us, considering our message data changes with the query that the user makes.
iv.Coding the callSendAPI Role
The"callSendAPI"office takes a single parameter, the"messageData". This parameter contains the entire message information, formatted properly co-ordinate to Facebook rules, so that the messenger can display it properly to the user.
[js]
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.vi/me/messages',
qs: { access_token: procedure.env.PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, office (error, response, torso) {
if (!fault && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = trunk.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
panel.error("Unable to transport message.");
console.mistake(response);
console.error(error);
}
});
}
[/js]
5.Pushing the Changes to Heroku
Nosotros're at the final pace towards making our upgraded bot alive. We just demand to push button all the lawmaking changes to Heroku. The process is the aforementioned as earlier, and is outlined below:
1. Launch Terminal.
2. Modify directory to thetestbotdirectory.
cd testbot
three. Do the following:
- git add together .
- Note:At that place is a"."at the terminate of that control.
- git commit -m "improving condition checks and formatting"
- git push heroku master
4. At present send a message such as "Propose an article on Android", or "Beebom, advise me whatsoever commodity on the topic Android"; and the bot will send a nicely formatted message with a link that you lot can tap on to open the manufactures related to your query.
See ALSO: 16 Facebook Messenger Tips And Tricks Y'all Should Know
Dig Deeper
Now that yous know how to get started with developing Facebook messenger bots, get through the Facebook documentation on how to develop Facebook messenger bots. While the documentation is not good for beginners, you're non a beginner anymore. Y'all should check out the official documentation and try to figure out how to brand your bot even smarter. Teaser: You can send messages with images and buttons as well! It's also possible to apply services such every bit Wit.ai and Api.ai to code your bot and and then integrate it with Facebook, but in my feeble attempts to use those services, Wit.ai doesn't work too well, and Api.ai has a sharp learning bend for beginners.
Accept you e'er developed a Facebook messenger bot? If you have, how did you lot go about developing information technology, and what can information technology do? Did you employ services like Wit.ai and Api.ai to create your bot? If yous oasis't ever tried your hands on coding a bot, go and develop your own Facebook messenger bot, make information technology smarter and better, and let us know about your experience in the comments below.
Source: https://beebom.com/how-create-facebook-messenger-bot/
Posted by: krakertheiven.blogspot.com
0 Response to "How to Develop Facebook Messenger Bot (Guide)"
Post a Comment