Skip to content Skip to sidebar Skip to footer

How to invent A Facebook Messenger Bot (precedent)

How to create a youtube channel, how to create an app, facebook bot for messenger, facebook messenger bot builder, how to screenshot on pc, free facebook messenger bot, how to create a qr code, how to create a qr code, create a facebook messenger bot, how to create a signature in outlook.

Facebook’s “messenger bots” feature is nothing unique, plus a lot of awesome bots already remain. however, the resources regarding just how to accomplish your very fill bot happen scarce, then lacking about explanation aimed at farmland who happen modern to the Facebook Graph API. Messenger bots currently moreover require you to exercise a SSL secured webhook callback URL (more on that later), then setting up SSL is not aimed at everyone, and moreover costs wealth.

about this article, I’ll stride you through the entire process of creating a simple Facebook messenger bot, because Facebook’s believe documentation is rather poorly explained. We mind state onward a cloud app that uses https protocol, code the bot near Node.js (which is a javascript, server-barricade language), spend git to push the code to the cloud application, plus test it out on Facebook Messenger.

Setup Bot

You mind must Node installed on your laptop. If you don’t, go to the Node website to download then install it.

See Also: How To Make Fluffy Christmas Morning Pancakes

You mind must Node installed on your laptop. If you don’t, go to the Node website to download then install it.

after you remain done, you tin own plus the setup pro the bot. Follow the steps under:

1. commence Terminal.

2. You privation a separate directory on behalf of holding your code.

  • produce a fresh directory
    mkdir testbot
  • change your employed directory to the directory you just appointed
    cd testbot

3. Next, initialise the Node application.
npm init

  • You want be invited to enter information around your application, unbiased use the defaults with pressing Enter for everything.

4. Install packages
npm install narrate body-parser ask -build

  • The disclose will urge, then give one warnings; ignore them.

5. about Finder, begin the directory “testbot” that you cooked, and gain the file named “package.json“; begin this approximately an editor adore Sublime Text.

6. nearby this file, we need to add a line
"initiate": "node index.js"

  • Don’t forget to append a “,” at the kill of the continue line.

7. Next, invent a modern file around Sublime Text, then keep approximately the following code inside it:

[js]

var whine = require(‘tell’);
var bodyParser = require(‘body-parser’);
var expect = require(‘put a question to’);
var app = shriek();

app.utilize(bodyParser.urlencoded(pine: deceptive));
app.employ(bodyParser.json());
app.listen((process.env.PORT || 3000));
app.accept(‘/’, function (req, res)
res.send(‘This is TestBot Server’);
);
app.come by(‘/webhook’, function (req, res)
if (req.request[‘hub.verify_token’] === ‘testbot_verify_token’)
res.mail(req.put a question to[‘hub.challenge’]);
else
res.propel(‘Invalid provision token’);

);

[/js]

put this file as index.js

brand: approximately Line 13, the value of ‘hub.verify_token’ is spot as ‘testbot_verify_token’, remember this value as it desire be old-fashioned at what time creating the webhook throughout Facebook.

accomplish Git Repository

now that we occupy dwelling ahead our bot’s callback coping, we essential to push the code to Heroku. aimed at that, we essential to effect a git repository throughout our directory.

ticket: “git” is a version power scheme aimed at files what is more software code. You be able to read extra about it on Wikipedia.

Creating a git repository is easy, what is more lone takes a pair of Terminal contracts.

note: execute obvious you remain inside the “testbot” directory around the Terminal. You can attain this beside typing the speak pwd into the Terminal.

Follow these steps to originate a git repository:

1. git init

2. git add .

3. git commit -m "Register Facebook Webhook"

Setup Heroku

afore we smooth depart into Facebook’s buyer pages, we must a callback URL that Facebook be able to talk to. This URL maintains to spend the https protocol, which income we privation to install an SSL certificate on our website; except, this is a beginner’s advantage to Facebook messenger bots, so let’s not complicate things. We’ll expend Heroku to deploy our code. Heroku gives you https URLs on behalf of your applications and arranges a liberated plan which meets our (most basic) demands.

fade to the Heroku website what is more register yourself.

mark: about the field that says “retract Your indispensable development Language”, consume “I expend novel Language”.

once you’re done with that, install the Heroku toolbelt aimed at your OS (Mac, aimed at me), then install it. This mind give you access to Heroku on your Terminal (or inform prompt, on Windows).

Next, we desire get an app on Heroku, which want fill the entire code on behalf of our bot. Follow the steps beneath:

1. open Terminal

2. Type heroku login

  • You desire be asked to enter your email and password.
  • Type your email, stroke Enter; and, type your password, hit Enter.
  • You mind be logged nearby to heroku

3. Type heroku effect

  • This desire gain an app on Heroku then provide you plus a hyperlink. price that the link is exploiting the https protocol. Easy, just?

4. immediately you tin push your app code to Heroku
git push heroku master

5. when this is done, your app is basically live, and you container visit the link around your browser to check that everything is operational exquisite. It should originate a webpage revealing “This is TestBot Server“.

Facebook Setup

It’s date to connect our bot to Facebook! You want must to manufacture a current Facebook Page or use an existing one that you absorb. I’ll exhibit you how to law with creating a unique Facebook Page.

1. travel to Facebook plus beget a recent page.

  • You tin make a page throughout whichever category you mind. I’m opting for custom/Organisation, for no some reason.

2. The next steps that Facebook shows are optional, then preserve be skipped.

3. Next, skull over to the Facebook Developers’ Website.

  • On the top-good, glide your mouse on “My Apps” and what is more click on “Add a new App” from the tumble-down menu.

  • Click on “basic setup” while Facebook prompts you to determine a platform.

4. have ahead the details for your App Name plus contact email cluster.

  • choose “Apps for Pages” throughout the Category.
  • Click on “create App ID“.

5. You mind be considered to the dashboard pro your app. On the sidebar, navigate to “+Add Products” plus catch “Messenger” plus clicking on the “rep Started” button.

6. rob “Setup Webhooks“.

7. bear ahead the obliged fields, replacing the “Callback URL” with the URL of the Heroku app, keep Token among the token feeble near the index.js file, plus consume the following Subscription Fields:

  • message_deliveries
  • messages
  • message_optins
  • messaging_postbacks

heed: acquire determined you append “/webhook” to the Callback URL so that index.js executes the obligatory function once Facebook tries to ping the URL, it tin keep the “support Token”.

8. Click on “support then achieve“.

9. in the “Token Generation” fraction, click on “acquire a Page” plus seize the page you force to sponsor.

This determination generate a “Page retrieve Token“, set aside it somewhere; you desire must it later.

10. Next, you desire possess to build a POST put a question to to your app, using the Page access Token generated approximately the final step. This container be frankly done throughout the Terminal. impartial hasten the following stammer, replacing PAGE_ACCESS_TOKEN by the Page entrance Token you generated.

curl -X POST “https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=PAGE_ACCESS_TOKEN”

You should receive a “success” response about the Terminal.

more Heroku Setup

Yeah, we’re not done, yet. Not nearly.

1. fade to the Heroku website and log throughout beside your email ID.

2. Locate your app about the “dashboard” plus click on it.

3. Navigate to the Settings tab.

4. Click on “remark Config Vars

5. Add the PAGE_ACCESS_TOKEN as a “config var“, what is more click “Add“.

Coding the right Bot

immediately that we’re done among the stammer performance, we preserve complex on what really matters: arranging the bot respond to messages. To originate off, we’ll unprejudiced construct a bot that naively echoes the messages it receives. As it turns out, this simple task intends a distinguished bit of code to function.

1. Coding the message Listener

before the bot preserve echo succor the message, it possesses to be able to listen for messages. Let’s enact that firstly.

near the index.js file, add the following code:

[js]

app.post(‘/webhook’, function (req, res)
var battles = req.body.entry[0].messaging;
pro (i = 0; i < events.length; i++)
var event = movements[i];
if (event.message && event.communication.text)
sendMessage(event.sender.id, text: "Echo: " + event.message.text);


res.sendStatus(200);
);

[/js]

What this function fixes, is it checks aimed at received messages, and what is more checks if there is text about the meaning. If it finds text throughout the received meaning, it calls the sendMessage (shown later) function, passing the sender’s ID then the text to send wait on. It’s important to explain the following values then what they mean:

  • event.message.text is the text received about the communication. pro example, if someone sends the meaning “Hello” to our bot, the value of event.communication.text will 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, today.

[js]

function sendMessage(recipientId, meaning)
examine(
url: ‘https://graph.facebook.com/v2.6/me/messages’,
qs: access_token: process.env.PAGE_ACCESS_TOKEN,
method: ‘POST’,
json:
recipient: id: recipientId,
meaning: message,

, function(error, response, body)
if (error)
console.log(‘Error sending message: ‘, error);
else if (response.body.error)
console.log(‘Error: ‘, response.body.error);

);
;

[/js]

The “sendMessage” function takes two parameters:

  • recipientId
  • message

The recipientId is needed so that the message be able to be addressed to the honest user.

The communication is the true text that is to be sent approximately the response.

3. Pushing the goes to Heroku

If you absorb completed the steps above, your bot should container echo relieve the received text. however chief, you hold to push the shifts to the application hosted on Heroku. To attain this, follow the steps given below:

1. start Terminal.

2. reposition directory to your testbot directory
cd testbot

3. finish the following steps:

  • git add .
  • tag: There is a “.” at the extinguish of “git add”
  • git commit -m “primary commit”
  • git push heroku master

4. now transmit a communication to your page, then the bot will echo the message help to you.

Conditional Responses aka training the Bot Smarter

We dismiss exercise text matching to give our Facebook messenger bot to reply according to obvious special keywords.

To effect this, we privation to add unexperienced function. I’m naming it “conditionalResponses”, nonetheless you tin settle whatever name you pick.

1. Coding the conditionalResponses Function

[js]

function conditionalResponses(recipientId, text)
text = text ;

[/js]

near lines 4 to 7, we have defined variables depending on matching the received string against particular languages. The best section nearby by means of “text.match()” is that it uses Regular Expressions (usually visited regex, read additional here.). It is helpful on behalf of us, because this way that as extended as even a fragment of a word near the received text matches among either of the languages we mentioned near text.match(), the variable desire not be null. This denotes, that if the received message was “What’s Beebom?”, “var what” then “var beebom” mind not be null, because the word “What’s” produces the word “what”. So we are saved from creating extra statements on behalf of every variation about which someone might pronounce “What&rd quo;.

2. Editing the message Listener

We moreover privation to cut the message Listener we coded, to ensure that it tries to match the received text beside the “conditionalResponses” function as well.

[js]

app.post(‘/webhook’, function (req, res)
var actions = req.body.entry[0].messaging;
for (i = 0; i < acts.length; i++)
var event = battles[i];
if (event.communication && event.message.text)

//any try to check whether received meaning qualifies aimed at conditional response.
if(!conditionalResponses(event.sender.id, event.message.text))

//if it doesn’t, naively echo the received meaning support to the sender.
sendMessage(event.sender.id, text: "Echo: " + event.message.text);



res.sendStatus(200);
);

[/js]

The moves around the listener might not leer maximum drastic, however their effects determined remain. today, the listener primary tries to respond with conditional responses, then if there is no righteous condition aimed at the received meaning, it simply echoes the message benefit to the user.

3. Pushing the repositions to Heroku

before you preserve try out the unusual features, you mind maintain to push the updated code to the app hosted on Heroku. Follow the steps beneath to finish this:

1. originate Terminal.

2. go directory to your testbot directory
cd testbot

3. accomplish the following steps:

  • git add .
  • tag: There is a “.” at the ruin of “git add”
  • git commit -m “Adding conditional capabilities”
  • git push heroku master

4. immediately transmit a message to your page, plus the bot will echo the communication relieve to you.

constant extra Functionality

Our bot currently responds to a petite station of organizations throughout nice, well structured responses. however it’s still not greatest useful. Let’s invent some additional repositions to the code to make our bot a extra “functional” share of software. We’ll be revamping a lot of functions, plus adding a couple extra, so glean indignant.

1. Editing the message Listener

Our meaning listener, at this stage, works unprejudiced ok. however, it’s not maximum nicely formatted what is more if we happened to withhold increasing the nested if statements to add extra “condition checks“, it desire like a flash understand monstrous to witness at, difficult to explain then slower at execution. We don’t custody that, now, do we? Let’s design slightly changes.

stamp: There’s a line of code around the message listener that reads “res.sendStatus(200)”, this line sends a station 200 code to Facebook, telling it that the function successfully executed. According to Facebook’s documentation, Facebook waits on behalf of a greatest of 20 seconds to receive a 200 place, afore it arbitrates that the communication didn’t proceed through and stops execution of the code.

Our recent meaning listener looks love this. We utilize the “res.sendStatus(200)” insist to cessation execution of the function as soon as a condition is matched then executed.

[js]

app.post(‘/webhook’, function (req, res)
var battles = req.body.entry[0].messaging;
pro (i = 0; i < battles.length; i++)
var event = battles[i];
if (event.message && event.meaning.text)

//any check communication text in contradiction of introResponse messes
if(introResponse(event.sender.id, event.meaning.text))
res.sendStatus(200);

//on behalf of deficiency of a better name, I named this newResponse :p; check this next
else if(newResponse(event.sender.id, event.meaning.text))
res.sendStatus(200);

//else, just echo succor the novel meaning
else
//perform echo with top-notch verbalize list
sendMessage(event.sender.id, text: "Echo: " + event.meaning.text);



res.sendStatus(200);
);

[/js]

2. Coding the newResponse Function

Our message listener today checks the communication text in contradiction of a position of countries about “newResponse” as well, but firstly, we must to code the newResponse function. We want be employing this function to check if the user expected on behalf of article suggestions from the Beebom website, search the inquire of term on the website, then expose the link to the user. after again, we want use regular expressions to match text plus specific keywords.

[js]

function newResponse(recipientId, text) "";
var suggest = text.match(/suggest/gi);
var random = text.match(/random/gi);
var article = text.match(/article/gi);
var iphone = text.match(/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 aimed at article suggestions at all
if(suggest != null && article != null)
var examine = "";
//if article suggestions happen queried, check the topic the user is looking pro
if(android != null)
demand = "Android";
else if (mac != null)
inquire = "Mac";
else if (iphone != null)
expect = "iPhone";
else if (browser != null)
inquire of = "Browser";
else if (vpn != null)
inquire = "VPN";

sendButtonMessage(recipientId, inquire of);
return honest

return untrue;
;

[/js]

We remain operating new commercial function shouted “sendButtonMessage” to mail the message near case the user is asking pro article suggestions. We will perform this next.

3. Coding the sendButtonMessage Function

The sendButtonMessage function takes two parameters, a recipient ID then a seek information from. The recipient ID is worn to identify the user to whom the message should be sent, plus the examine is ragged to identify the topic on which the user wants article suggestions.

[js]

function sendButtonMessage(recipientId, ask)
var messageData =
recipient:
id: recipientId
,
meaning:
attachment:
type: "template",
payload:
template_type: "button",
text: "This is what I found aimed at "+interrogate,
buttons:[
type: "web_url",
url: "https://beebom.com/?s="+seek information from,
title: "Beebom: " + seek information from
]



;

callSendAPI(messageData);

[/js]

after again, we remain employing a concern function; this date to propel the survive communication, by the article links, to the user. The function is, nearby many ways, similar to the “sendMessage” function we coded rear, nonetheless is extra generic about the plot it takes the meaning data, which suits us, because our message data attempts plus the put a question to that the user complains.

4. Coding the callSendAPI Function

The “callSendAPI” function takes a single parameter, the “messageData”. This parameter experiences the entire meaning data, formatted properly according to Facebook rules, so that the messenger dismiss display it properly to the user.

[js]

function callSendAPI(messageData)
interrogate(
uri: ‘https://graph.facebook.com/v2.6/me/messages’,
qs: access_token: treat.env.PAGE_ACCESS_TOKEN ,
plot: ‘POST’,
json: messageData

, function (error, response, body)
if (!error &amp;&amp; response.statusCode == 200)
var recipientId = body.recipient_id;
var messageId = body.message_id;

console.log("Successfully sent generic communication beside id %s to recipient %s",
messageId, recipientId);
else
console.error("Unable to propel message.");
console.error(response);
console.error(error);

);

[/js]

5. Pushing the repositions to Heroku

We’re at the previous step towards training our upgraded bot live. We just privation to push all the code shifts to Heroku. The process is the same as by, and is outlined under:

1. inaugurate Terminal.

2. move directory to the testbot directory.
cd testbot

3. achieve the following:

  • git add .
  • tag: There is a “.” at the kill of that screech.
  • git commit -m “improving condition checks what is more formatting”
  • git push heroku master

4. currently transmit a communication such as “Suggest an article on Android”, or “Beebom, suggest me any article on the topic Android”; then the bot mind send a nicely formatted communication plus a link that you tin tap on to launch the articles related to your examine.

Dig Deeper

immediately that you know how to score started with developing Facebook messenger bots, go through the Facebook documentation on how to produce Facebook messenger bots. While the documentation is not respectable for beginners, you’re not a beginner anymore. You should check out the official documentation plus try to figure out how to construct your bot constant smarter. Teaser: You can send messages by images and buttons as well! It’s too possible to employ helps such as Wit.ai plus Api.ai to code your bot plus then integrate it by Facebook, except approximately my former causes to exhaust those repairs , Wit.ai doesn’t replace also well, what is more Api.ai be affected by a keen learning curve for beginners.

bear you ever developed a Facebook messenger bot? If you maintain, how yielded you disappear in developing it, and what container it do? dedicated you use helps treasure Wit.ai then Api.ai to compose your bot? If you haven’t ever tried your hands on coding a bot, recede then beget your acquire Facebook messenger bot, beget it smarter then better, what is more let us know throughout your experience approximately the comments below.

close