fb.me
v0.3.0-alpha.4
Published
Express app for chatbot development with Facebook Messenger
Downloads
10
Maintainers
Readme
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:
- Handling messages (text, or quick replies)
- Handling messenger profile of chatbots
- Handling postbacks
- Setting messenger code for chatbots
- Verifying the chatbot setup (verifying webhook and whitelisting domains)
Table of contents
- Pre-requisites
- Setup
- API Reference
- MessageflowConfig
- FacebookMessageEvent
- HandleMessengerCodeResponse
- messengerCode(appConfig)
- verifySetup(verifyToken)
- webhook(appConfig[, options])
- handleDomainWhitelisting(url, pageAccessToken[, domains, options])
- handleMessengerCode(url, pageAccessToken[, ref, imageSize, options])
- deleteMessengerProfile(url, pageAccessToken, fields[, options])
- getMessengerProfile(url, pageAccessToken, fields[, options])
- setMessengerProfile(url, pageAccessToken, body[, options])
- handleReceiveMessage(appConfig, event[, options])
- handleReceivePostback(appConfig, event[, options])
- License
Pre-requisites
Setup
Install
# Install via NPM
$ npm install --save fb.me
Usage
// 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...
}
Node.js
// 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}...`;
});
Native ES modules or TypeScript
// 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}...`;
});
API Reference
MessageflowConfig
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.
FacebookMessageEvent
message
<Object> Message object.mid
<string> Message ID.seq
<string> Sequence number.quick_reply
<Object> Optional custom data provided by the sending app. Aquick_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. Atext
is only provided when the event is a text message event.
HandleMessengerCodeResponse
uri
<string> URL to the generated messenger code.
messengerCode(appConfig)
appConfig
<MessageflowConfig> Application configuration.- returns:
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.
verifySetup(verifyToken)
verifyToken
<string> Facebook verify token.- returns:
express.Router
an Express router which contains a HTTP GET route. The route handler sends thehub.challenge
token from the payload sent by Facebook HTTP server to verify the webhook setup.
webhook(appConfig[, options])
appConfig
<MessageflowConfig> Application configuration.options
<Object> Optional request options. See node-fetch options for more details.- returns:
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. Amessage
message will be forwarded to the handleReceiveMessage method that needs to be defined by the user in theappConfig
whereas apostback
message will handled by the handleReceivePostback method.
handleDomainWhitelisting(url, pageAccessToken[, domains, options])
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.- returns: <Promise<Object>> Promise which resolves with status of the operation.
result
<string> If the operation is successful, the value isSuccessfully updated whitelisted domains
.
handleMessengerCode(url, pageAccessToken[, ref, imageSize, options])
url
<string> Facebook Graph URL.pageAccessToken
<string> Facebook page access token.ref
<string> Optionalref
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.- returns: <Promise<Object>> Promise which resolves with an object that contains the URL to the image of the generated messenger code.
uri
<string> URL to the image of the generated messenger code.
deleteMessengerProfile(url, pageAccessToken, fields[, options])
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.- returns: <Promise<Object>> Promise which resolves with status of the operation.
result
<string> If the operation is successful, the value issuccess
.
getMessengerProfile(url, pageAccessToken, fields[, options])
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.- returns: <Promise<Object>> Promise which resolves with status of the operation.
result
<string> If the operation is successful, the value issuccess
.
setMessengerProfile(url, pageAccessToken, body[, options])
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.- returns: <Promise<Object>> Promise which resolves with status of the operation.
result
<string> If the operation is successful, the value issuccess
.
handleReceiveMessage(appConfig, event[, options])
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.- returns: <Promise<
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. Atext
message will be forwarded to theonMessage
method that needs to be defined by the user in theappConfig
whereas aquickReply
message will handled by theonQuickReply
method.
handleReceivePostback(appConfig, event[, options])
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.- returns: <Promise<
any
>> The method will forward all postback payload to a user-definedonPostback
method inappConfig
.
License
MIT License © Rong Sen Ng