SlideShare a Scribd company logo
HOW TO “BUILD A FACEBOOK MESSENGER
BOT” FOR YOUR BUSINESS
By: www.edtechnology.in
Objective
• To build a simple bot that can send simple messages more likely
to say echo bot.
• A bot that will send a message back whatever we send as text
format.
Procedure
Create Facebook developer App
•https://developers.facebook.com/
Create NodeJs Backend
•Create server.js, config.js, and
API.js file
•Install request and restify two
NPM modules
Create a Facebook Page After that select messenger
product and click setup,
then generate the page
token from there
Messenger Bot ready to
use
1 2 3 4 5
Short Tour
1. Create your facebook page, from
your facekook account.
2. Create a facebook developer account.
1
2
3
4
3. Select messenger product and click
setup, then generate the page token
4. Create Node Js Backend.
The config.js File
• The file includes general configuration and
tokens so we can use it when it’s required.
Code
‘use strict’;
module.exports ={
“FB”: {
“PAGE_ACCESS_TOKEN”:
“page_access_token”,
“VERIFY_TOKEN”:“verify_token”,
“APP_SECRET”:“app_secret”
}
}
The API.js File
• The file helps to connect with facebook messenger platform and can send and
receive the messages.
• It consists of the following:
• registerHook() Function will verify the hub challange code when we register our server in facebook.
• incoming() Function is for checking which event we are getting either we are getting text,
attachment or anything else.
• sendMessage() This is for the sending data to the messenger by using Graph API URL.
• txt() function is the common payload template that we will call when we have to send text
message.
Code
‘use strict’;
const request = require(‘request’);
class FB{
constructor(config) {
try {
if(!config || config.PAGE_ACCESS_TOKEN ===undefined ||
config.VERIFY_TOKEN === undefined || config.APP_SECRET ===
undefined) { throw new Error(“Unable to access tokens!”);}
else {
this.PAGE_ACCESS_TOKEN=config.PAGE_ACCESS_TOKEN;
this.VERIFY_TOKEN=config.VERIFY_TOKEN;
this.APP_SECRET = config.APP_SECRET;
}
} catch(e) {console.log(e);
}
}
registerHook(req, res) {
let {mode, verify_token, challenge} = req.query.hub;
if(mode === ‘subscribe’ &&verify_token === this.VERIFY_TOKEN) {
return res.end(challenge);
} else {
console.log(“Could not register webhook!”);
return res.status(403).end();
}
}
Code
incoming(req, res, cb) {
let data = req.body;
if(data.object === ‘page’) {
data.entry.forEach(pageObj => {
pageObj.messaging.forEach(msgEvnt=> {
let messageObj = {
sender: msgEvent.sender.id,
timeOfMessage:msgEvent.timestamp,
message: msgEvent.message
}
cb(messageObj);
});
});
}
res.send(200);
}
sendMessage(payload) {
return new Promise((resolve, reject) => {
request({
uri:‘https://graph.facebook.com/v2.6/me/messages’,
qs: {
access_token: this.PAGE_ACCESS_TOKEN
},
method: ‘POST’,
json: payload
}, (error, response, body) => {
if(!error && response.statusCode === 200){
resolve({messageId: body.message_id});
} else {reject(error);}
});
});
}
Code
txt(id, text, messaging_type = ‘RESPONSE’) {
let obj = {
messaging_type,
recipient: {
id
},
message: {
text
}
}
this.sendMessage(obj)
.catch(error => console.log(error));
}
}
module.exports = FB;
The server.js File
• The file helps create a restify server
Code
‘use strict’;
const Restify = require(‘restify’);
const server = Restify.createServer({
name: ‘Simplebot’
});
const PORT = process.env.PORT || 3000;
server.use(Restify.jsonp());
server.use(Restify.bodyParser());
const config = require(‘./config’);
const API = require(‘./API’);
const f = new API(config.FB)
server.get(‘/’, (req, res, next) => {
f.registerHook(req, res);
return next();
});
server.post(‘/’, (req, res, next) => {
f.incoming(req, res, msg => {
const {
message,
sender
} = msg;
if(message.text) {
f.txt(sender, `You just said ${message.text}`);
}
});
return next();
});
server.listen(PORT, () => console.log(`running on port ${PORT}`));
Establish Connection
• Create two routes one for GET and One For POST.
• To verify request will come from facebook we are calling registerHook() to verify the hub
challenge code.
• Now in Post method we will use incoming() to check did we got the text from the user
and by using txt() function we will send the text message again.
• That’s it in coding part now run your node server and but we need live HTTPS URL rather
than the localhost so Download ngrok and make the port live.
• You will get Two URL and copy HTTPS one.
• In the webhook section of the Facebook app add URL and the verification token that you
declared in config.js.
References
http://www.edtechnology.in/machine-learning/how-to-build-a-facebook-messenger-bot-for-your-
business/

More Related Content

Similar to CHATBOT using Facebook Messenger

pptindustrial (1).pptx
pptindustrial (1).pptxpptindustrial (1).pptx
pptindustrial (1).pptx
quotedcaprio
 
Write FB Bot in Python3
Write FB Bot in Python3Write FB Bot in Python3
Write FB Bot in Python3
Jim Yeh
 
IRREPORT.pptx
IRREPORT.pptxIRREPORT.pptx
IRREPORT.pptx
quotedcaprio
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
Katy Slemon
 
Global Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handsonGlobal Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handson
Takuya Tejima
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
Katy Slemon
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps OfflinePedro Morais
 
Pushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTCPushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTC
Rich Waters
 
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
BizTalk360
 
FINALPPT.pptx
FINALPPT.pptxFINALPPT.pptx
FINALPPT.pptx
quotedcaprio
 
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
Rob Tweed
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...
EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...
EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...
Rob Tweed
 
Deploying your static web app to the Cloud
Deploying your static web app to the CloudDeploying your static web app to the Cloud
Deploying your static web app to the Cloud
Christoffer Noring
 
pptindustrial (1).pptx
pptindustrial (1).pptxpptindustrial (1).pptx
pptindustrial (1).pptx
HinataTachibana1
 
Passport js authentication in nodejs how to implement facebook login feature ...
Passport js authentication in nodejs how to implement facebook login feature ...Passport js authentication in nodejs how to implement facebook login feature ...
Passport js authentication in nodejs how to implement facebook login feature ...
Katy Slemon
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
Nicholas McClay
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
Caesar Chi
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web apps
daviddemello
 
How to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorizationHow to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorization
Katy Slemon
 

Similar to CHATBOT using Facebook Messenger (20)

pptindustrial (1).pptx
pptindustrial (1).pptxpptindustrial (1).pptx
pptindustrial (1).pptx
 
Write FB Bot in Python3
Write FB Bot in Python3Write FB Bot in Python3
Write FB Bot in Python3
 
IRREPORT.pptx
IRREPORT.pptxIRREPORT.pptx
IRREPORT.pptx
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
Global Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handsonGlobal Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handson
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 
Pushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTCPushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTC
 
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
 
FINALPPT.pptx
FINALPPT.pptxFINALPPT.pptx
FINALPPT.pptx
 
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
EWD 3 Training Course Part 13: Putting Everything so far into Practice using ...
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
 
EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...
EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...
EWD 3 Training Course Part 36: Accessing REST and Web Services from a QEWD ap...
 
Deploying your static web app to the Cloud
Deploying your static web app to the CloudDeploying your static web app to the Cloud
Deploying your static web app to the Cloud
 
pptindustrial (1).pptx
pptindustrial (1).pptxpptindustrial (1).pptx
pptindustrial (1).pptx
 
Passport js authentication in nodejs how to implement facebook login feature ...
Passport js authentication in nodejs how to implement facebook login feature ...Passport js authentication in nodejs how to implement facebook login feature ...
Passport js authentication in nodejs how to implement facebook login feature ...
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web apps
 
How to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorizationHow to implement golang jwt authentication and authorization
How to implement golang jwt authentication and authorization
 

More from Navjyotsinh Jadeja

1.3 Understanding cyber crimes in detail
1.3 Understanding cyber crimes in detail1.3 Understanding cyber crimes in detail
1.3 Understanding cyber crimes in detail
Navjyotsinh Jadeja
 
1.2 Who are Cyber Criminals
1.2 Who are Cyber Criminals1.2 Who are Cyber Criminals
1.2 Who are Cyber Criminals
Navjyotsinh Jadeja
 
what is cyber crime and how it started
what is cyber crime and how it startedwhat is cyber crime and how it started
what is cyber crime and how it started
Navjyotsinh Jadeja
 
Software myths | Software Engineering Notes
Software myths | Software Engineering NotesSoftware myths | Software Engineering Notes
Software myths | Software Engineering Notes
Navjyotsinh Jadeja
 
Market basket analysis | Association Rules Mining | R Programming
Market basket analysis | Association Rules Mining | R ProgrammingMarket basket analysis | Association Rules Mining | R Programming
Market basket analysis | Association Rules Mining | R Programming
Navjyotsinh Jadeja
 
M2M vs IoT: The Key Differences and Similarities
M2M vs IoT: The Key Differences and SimilaritiesM2M vs IoT: The Key Differences and Similarities
M2M vs IoT: The Key Differences and Similarities
Navjyotsinh Jadeja
 
Risk Mitigation, Monitoring and Management Plan (RMMM)
Risk Mitigation, Monitoring and Management Plan (RMMM)Risk Mitigation, Monitoring and Management Plan (RMMM)
Risk Mitigation, Monitoring and Management Plan (RMMM)
Navjyotsinh Jadeja
 
COCOMO model | How to calculate effort, staffing and Duration of Project
COCOMO model | How to calculate effort, staffing and Duration of ProjectCOCOMO model | How to calculate effort, staffing and Duration of Project
COCOMO model | How to calculate effort, staffing and Duration of Project
Navjyotsinh Jadeja
 
How to make Gantt chart in Excel
How to make Gantt chart in ExcelHow to make Gantt chart in Excel
How to make Gantt chart in Excel
Navjyotsinh Jadeja
 

More from Navjyotsinh Jadeja (9)

1.3 Understanding cyber crimes in detail
1.3 Understanding cyber crimes in detail1.3 Understanding cyber crimes in detail
1.3 Understanding cyber crimes in detail
 
1.2 Who are Cyber Criminals
1.2 Who are Cyber Criminals1.2 Who are Cyber Criminals
1.2 Who are Cyber Criminals
 
what is cyber crime and how it started
what is cyber crime and how it startedwhat is cyber crime and how it started
what is cyber crime and how it started
 
Software myths | Software Engineering Notes
Software myths | Software Engineering NotesSoftware myths | Software Engineering Notes
Software myths | Software Engineering Notes
 
Market basket analysis | Association Rules Mining | R Programming
Market basket analysis | Association Rules Mining | R ProgrammingMarket basket analysis | Association Rules Mining | R Programming
Market basket analysis | Association Rules Mining | R Programming
 
M2M vs IoT: The Key Differences and Similarities
M2M vs IoT: The Key Differences and SimilaritiesM2M vs IoT: The Key Differences and Similarities
M2M vs IoT: The Key Differences and Similarities
 
Risk Mitigation, Monitoring and Management Plan (RMMM)
Risk Mitigation, Monitoring and Management Plan (RMMM)Risk Mitigation, Monitoring and Management Plan (RMMM)
Risk Mitigation, Monitoring and Management Plan (RMMM)
 
COCOMO model | How to calculate effort, staffing and Duration of Project
COCOMO model | How to calculate effort, staffing and Duration of ProjectCOCOMO model | How to calculate effort, staffing and Duration of Project
COCOMO model | How to calculate effort, staffing and Duration of Project
 
How to make Gantt chart in Excel
How to make Gantt chart in ExcelHow to make Gantt chart in Excel
How to make Gantt chart in Excel
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 

CHATBOT using Facebook Messenger

  • 1. HOW TO “BUILD A FACEBOOK MESSENGER BOT” FOR YOUR BUSINESS By: www.edtechnology.in
  • 2. Objective • To build a simple bot that can send simple messages more likely to say echo bot. • A bot that will send a message back whatever we send as text format.
  • 3. Procedure Create Facebook developer App •https://developers.facebook.com/ Create NodeJs Backend •Create server.js, config.js, and API.js file •Install request and restify two NPM modules Create a Facebook Page After that select messenger product and click setup, then generate the page token from there Messenger Bot ready to use 1 2 3 4 5
  • 4. Short Tour 1. Create your facebook page, from your facekook account. 2. Create a facebook developer account. 1 2
  • 5. 3 4 3. Select messenger product and click setup, then generate the page token 4. Create Node Js Backend.
  • 6. The config.js File • The file includes general configuration and tokens so we can use it when it’s required.
  • 7. Code ‘use strict’; module.exports ={ “FB”: { “PAGE_ACCESS_TOKEN”: “page_access_token”, “VERIFY_TOKEN”:“verify_token”, “APP_SECRET”:“app_secret” } }
  • 8. The API.js File • The file helps to connect with facebook messenger platform and can send and receive the messages. • It consists of the following: • registerHook() Function will verify the hub challange code when we register our server in facebook. • incoming() Function is for checking which event we are getting either we are getting text, attachment or anything else. • sendMessage() This is for the sending data to the messenger by using Graph API URL. • txt() function is the common payload template that we will call when we have to send text message.
  • 9. Code ‘use strict’; const request = require(‘request’); class FB{ constructor(config) { try { if(!config || config.PAGE_ACCESS_TOKEN ===undefined || config.VERIFY_TOKEN === undefined || config.APP_SECRET === undefined) { throw new Error(“Unable to access tokens!”);} else { this.PAGE_ACCESS_TOKEN=config.PAGE_ACCESS_TOKEN; this.VERIFY_TOKEN=config.VERIFY_TOKEN; this.APP_SECRET = config.APP_SECRET; } } catch(e) {console.log(e); } } registerHook(req, res) { let {mode, verify_token, challenge} = req.query.hub; if(mode === ‘subscribe’ &&verify_token === this.VERIFY_TOKEN) { return res.end(challenge); } else { console.log(“Could not register webhook!”); return res.status(403).end(); } }
  • 10. Code incoming(req, res, cb) { let data = req.body; if(data.object === ‘page’) { data.entry.forEach(pageObj => { pageObj.messaging.forEach(msgEvnt=> { let messageObj = { sender: msgEvent.sender.id, timeOfMessage:msgEvent.timestamp, message: msgEvent.message } cb(messageObj); }); }); } res.send(200); } sendMessage(payload) { return new Promise((resolve, reject) => { request({ uri:‘https://graph.facebook.com/v2.6/me/messages’, qs: { access_token: this.PAGE_ACCESS_TOKEN }, method: ‘POST’, json: payload }, (error, response, body) => { if(!error && response.statusCode === 200){ resolve({messageId: body.message_id}); } else {reject(error);} }); }); }
  • 11. Code txt(id, text, messaging_type = ‘RESPONSE’) { let obj = { messaging_type, recipient: { id }, message: { text } } this.sendMessage(obj) .catch(error => console.log(error)); } } module.exports = FB;
  • 12. The server.js File • The file helps create a restify server
  • 13. Code ‘use strict’; const Restify = require(‘restify’); const server = Restify.createServer({ name: ‘Simplebot’ }); const PORT = process.env.PORT || 3000; server.use(Restify.jsonp()); server.use(Restify.bodyParser()); const config = require(‘./config’); const API = require(‘./API’); const f = new API(config.FB) server.get(‘/’, (req, res, next) => { f.registerHook(req, res); return next(); }); server.post(‘/’, (req, res, next) => { f.incoming(req, res, msg => { const { message, sender } = msg; if(message.text) { f.txt(sender, `You just said ${message.text}`); } }); return next(); }); server.listen(PORT, () => console.log(`running on port ${PORT}`));
  • 14. Establish Connection • Create two routes one for GET and One For POST. • To verify request will come from facebook we are calling registerHook() to verify the hub challenge code. • Now in Post method we will use incoming() to check did we got the text from the user and by using txt() function we will send the text message again. • That’s it in coding part now run your node server and but we need live HTTPS URL rather than the localhost so Download ngrok and make the port live. • You will get Two URL and copy HTTPS one. • In the webhook section of the Facebook app add URL and the verification token that you declared in config.js.

Editor's Notes

  1. When conducting research, it is easy to go to one source: Wikipedia. However, you need to include a variety of sources in your research. Consider the following sources: Who can I interview to get more information on the topic? Is the topic current and will it be relevant to my audience? What articles, blogs, and magazines may have something related to my topic? Is there a YouTube video on the topic? If so, what is it about? What images can I find related to the topic?
  2. When conducting research, it is easy to go to one source: Wikipedia. However, you need to include a variety of sources in your research. Consider the following sources: Who can I interview to get more information on the topic? Is the topic current and will it be relevant to my audience? What articles, blogs, and magazines may have something related to my topic? Is there a YouTube video on the topic? If so, what is it about? What images can I find related to the topic?
  3. When conducting research, it is easy to go to one source: Wikipedia. However, you need to include a variety of sources in your research. Consider the following sources: Who can I interview to get more information on the topic? Is the topic current and will it be relevant to my audience? What articles, blogs, and magazines may have something related to my topic? Is there a YouTube video on the topic? If so, what is it about? What images can I find related to the topic?
  4. Now, that you have narrowed your topic, you will want to organize your research in a structure that works. There are some common organizational patterns based on the kind of research you are doing. Organizational Structures: Cause and Effect- this kind of structure is great for explaining the causes and effects of a topic Compare and Contrast- in this pattern you highlight the similarities and differences of the topic Explain process- this structure is great for outlining a series of steps to follow; Definition- if you want to make sure your audience understands what something is using illustrations, meanings, clarifying misconceptions, you may want to use this structure Classification- a common organizational structure is grouping like topics or facts from the research together. For instance, in the internet safety about social media apps, you may organize the research where you look at each social media app one at a time
  5. You can use this slide as your opening or closing slide. Should you choose to use it as a closing, make sure you review the main points of your presentation. One creative way to do that is by adding animations to the various graphics on a slide. This slide has 4 different graphics, and, when you view the slideshow, you will see that you can click to reveal the next graphic. Similarly, as you review the main topics in your presentation, you may want each point to show up when you are addressing that topic. Add animation to images and graphics: Select your image or graphic. Click on the Animations tab. Choose from the options. The animation for this slide is “Split”. The drop-down menu in the Animation section gives even more animations you can use. If you have multiple graphics or images, you will see a number appear next to it that notes the order of the animations. Note: You will want to choose the animations carefully. You do not want to make your audience dizzy from your presentation.