Facebook Messenger SDK
🚨 No longer maintained 🚨
Express app for chatbot development with Facebook Messenger
This is an Express app for chatbot development on Facebook Messenger that uses Facebook Messenger API, specifically the Send API by providing a set of methods and route handlers to better deal with a few common tasks while developing any kind of typical chatbot:
# Install via NPM
$ npm install --save fb.me
// src/on-handlers.ts
export async function onMessageHandler(sender, text) {
// Handler message text here...
}
export async function onPostbackHandler(sender, postback) {
// Handler postback payload here...
}
export async function onQuickReplyHandler(sender, quickReply) {
// Handler quick reply here...
}
// src/server.js
/** Import project dependencies */
const https = require('https');
const express = require('express');
const {
messageflow,
handleDomainWhitelisting,
setMessengerProfile,
} = require('fb.me');
/** Import other modules */
const {
onMessageHandler,
onPostbackHandler,
onQuickReplyHandler,
} = require('./on-handlers');
/** Setting up */
const PORT = process.env.PORT;
const config = {
appId: '<FB_APP_ID>',
pageAccessToken: '<FB_PAGE_ACCESS_TOKEN>',
pageId: '<FB_PAGE_ID>',
url: '<FB_GRAPH_URL>',
verifyToken: 'FB_VERIFY_TOKEN',
fetchTimeout: 599e3,
notificationType: 'REGULAR',
typingDelay: 5e2,
onMessage: onMessageHandler,
onPostback: onPostbackHandler,
onQuickReply: onQuickReplyHandler,
};
const options = {
agent: new https.Agent({ keepAlive: true }),
};
const app = express()
.use(express.json())
.use(express.urlencoded({ extended: false }))
.use('/', messageflow(config, options));
/** NOTE: Custom error handling */
app.use((err, req, res, next) => {
console.error('🚨 Handle error', err);
return res.send(err instanceof Error ? err.message : err);
});
app.listen(PORT, async () => {
/** NOTE: Set domain whitelisting on server boots up */
await handleDomainWhitelisting({
url: config.url,
pageAccessToken: config.pageAccessToken,
domains: [
'https://should-whitelist-url.com',
],
});
/** NOTE: Setup messenger profile */
await setMessengerProfile({
url: config.url,
pageAccessToken: config.pageAccessToken,
body: {
get_started: {
payload: 'FACEBOOK_WELCOME',
},
},
});
console.info(`@ Express server running at port ${PORT}...`;
});
// src/server.ts
// @ts-check
/** Import project dependencies */
import https from 'https';
import express from 'express';
import messageflow from 'fb.me';
import handleMessengerProfile from 'fb.me/handle-messenger-profile';
import handleDomainWhitelisting from 'fb.me/handle-domain-whitelisting';
/** Import other modules */
import {
onMessageHandler,
onPostbackHandler,
onQuickReplyHandler,
} from './on-handlers';
/** Setting up */
const PORT = process.env.PORT;
const config = {
appId: '<FB_APP_ID>',
pageAccessToken: '<FB_PAGE_ACCESS_TOKEN>',
pageId: '<FB_PAGE_ID>',
url: '<FB_GRAPH_URL>',
verifyToken: 'FB_VERIFY_TOKEN',
fetchTimeout: 599e3,
notificationType: 'REGULAR',
typingDelay: 5e2,
onMessage: onMessageHandler,
onPostback: onPostbackHandler,
onQuickReply: onQuickReplyHandler,
};
const options = {
agent: new https.Agent({ keepAlive: true }),
};
const app = express()
.use(express.json())
.use(express.urlencoded({ extended: false }))
.use('/', messageflow(config, options));
/** NOTE: Custom error handling */
app.use((err, req, res, next) => {
console.error('🚨 Handle error', err);
return res.send(err instanceof Error ? err.message : err);
});
app.listen(PORT, async () => {
/** NOTE: Set domain whitelisting on server boots up */
await handleDomainWhitelisting({
url: config.url,
pageAccessToken: config.pageAccessToken,
domains: [
'https://should-whitelist-url.com',
],
});
/** NOTE: Setup messenger profile */
await handleMessengerProfile.set({
url: config.url,
pageAccessToken: config.pageAccessToken,
body: {
get_started: {
payload: 'FACEBOOK_WELCOME',
},
},
});
console.info(`@ Express server running at port ${PORT}...`;
});
appId
<string> Facebook Application ID.pageAccessToken
<string> Facebook page access token.pageId
<string> Facebook Page ID.url
<string> Facebook Graph URL, e.g. https://graph.facebook.com/v2.11
verifyToken
<string> Facebook verify token.fetchTimeout
<number> Optional timeout for HTTP requests, e.g. 599e3
notificationType
<string> Optional notification type. Possible values: NO_PUSH
, REGULAR
, SILENT_PUSH
.typingDelay
<number> Optional delay in between messages.message
<Object> Message object.mid
<string> Message ID.seq
<string> Sequence number.quick_reply
<Object> Optional custom data provided by the sending app. A quick_reply
payload is only provided with a text message when the user tap on a Quick Replies button.payload
<string> Custom data provided by the app.attachment
<Object> Optional array containing attachment data.
text
<string> Optional text of the message. A text
is only provided when the event is a text message event.uri
<string> URL to the generated messenger code.appConfig
<MessageflowConfig> Application configuration.express.Router
an Express router which contains a HTTP GET route. The route handler returns a promise which resolves with a successful response in the type of HandleMessengerCodeResponse that contains the URL to the image of the generated messenger code.verifyToken
<string> Facebook verify token.express.Router
an Express router which contains a HTTP GET route. The route handler sends the hub.challenge
token from the payload sent by Facebook HTTP server to verify the webhook setup.appConfig
<MessageflowConfig> Application configuration.options
<Object> Optional request options. See node-fetch options for more details.express.Router
an Express router which contains a HTTP POST route. The route handle will forward the correct message based on its message type to the corresponding event handler to do more stuff on the received message. A message
message will be forwarded to the handleReceiveMessage method that needs to be defined by the user in the appConfig
whereas a postback
message will handled by the handleReceivePostback method.url
<string> Facebook Graph URL.pageAccessToken
<string> Facebook page access token.domains
<string|Array<string>> Optional domain string or a list of domains to be whitelisted.options
<Object> Optional request options. See node-fetch options for more details.result
<string> If the operation is successful, the value is Successfully updated whitelisted domains
.url
<string> Facebook Graph URL.pageAccessToken
<string> Facebook page access token.ref
<string> Optional ref
string to pass to the chatbot when it is opened via scanning the code on Messenger. 250 character limit and accepts only these characters: a-z A-Z 0-9 +/=-.:_
.imageSize
<string> Optional image size, in pixels. Supported range: 100 - 2000px. Defaults to 1000px.options
<Object> Optional request options. See node-fetch options for more details.uri
<string> URL to the image of the generated messenger code.url
<string> Facebook Graph URL.pageAccessToken
<string> Facebook page access token.fields
<Array<string>> A list of Messenger Profile properties to delete.options
<Object> Optional request options. See node-fetch options for more details.result
<string> If the operation is successful, the value is success
.url
<string> Facebook Graph URL.pageAccessToken
<string> Facebook page access token.fields
<string|Array<string>> A list/ comma-separated list of Messenger Profile properties to retrieve, e.g. account_linking_url,persistent_menu,get_started,greeting,whitelisted_domains,payment_settings,target_audience,home_url
options
<Object> Optional request options. See node-fetch options for more details.result
<string> If the operation is successful, the value is success
.url
<string> Facebook Graph URL.pageAccessToken
<string> Facebook page access token.body
<Object> Set the value of one or more Messenger Profile properties in the format of '<PROPERTY_NAME>': '<NEW_PROPERTY_VALUE>'
. Only properties specified in the request body will be overwritten.options
<Object> Optional request options. See node-fetch options for more details.result
<string> If the operation is successful, the value is success
.appConfig
<MessageflowConfig> Application configuration.event
<FacebookMessageEvent> Facebook message event. See messages Webhook Event Reference for more details.options
<Object> Optional request options. See node-fetch options for more details.any
>> The method will forward the correct message based on its message type to the corresponding event handler to do more stuff on the received message. A text
message will be forwarded to the onMessage
method that needs to be defined by the user in the appConfig
whereas a quickReply
message will handled by the onQuickReply
method.appConfig
<MessageflowConfig> Application configuration.event
<FacebookMessageEvent> Facebook message event. See messages Webhook Event Reference for more details.options
<Object> Optional request options. See node-fetch options for more details.any
>> The method will forward all postback payload to a user-defined onPostback
method in appConfig
.MIT License © Rong Sen Ng