fb.me

Express app for chatbot development with Facebook Messenger

  • fb.me

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
fb.me
260.3.0-alpha.46 years ago6 years agoMinified + gzip package size for fb.me in KB

Readme

fb.me

Express app for chatbot development with Facebook Messenger




!NPMnodei-badgenodei-url
!Versionversion-badgeversion-url !Downloadsdownloads-badgedownloads-url !MIT Licensemit-license-badgemit-license-url !Code of Conductcoc-badgecoc-url
!Build Statustravis-badgetravis-url !NSP Statusnsp-badgensp-url !Dependency Statusdaviddm-badgedaviddm-url !Codecovcodecov-badgecodecov-url !Coverage Statuscoveralls-badgecoveralls-url
!codebeat-badgecodebeat-url !codacy-badgecodacy-url
This is an Expressexpressjs-url app for chatbot development on Facebook Messenger that uses Facebook Messenger API, specifically the Send APIsend-api-url by providing a set of methods and route handlers to better deal with a few common tasks while developing any kind of typical chatbot:

1. Handling messages (text, or quick replies) 2. Handling messenger profile of chatbots 3. Handling postbacks 4. Setting messenger code for chatbots 5. Verifying the chatbot setup (verifying webhook and whitelisting domains)

Table of contents

- Install - Usage
- [Node.js](#nodejs)
- [Native ES modules or TypeScript](#native-es-modules-or-typescript)
- 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)

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

FacebookMessageEvent

- mid <stringstring-mdn-url> Message ID. - seq <stringstring-mdn-url> Sequence number. - quick_reply <Objectobject-mdn-url> 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 Repliesquick-replies-url button.
- `payload` <[string][string-mdn-url]> Custom data provided by the app.
- attachment <Object
object-mdn-url> Optional array containing attachment data.
- `type` <[string][string-mdn-url]> `audio`, `fallback`, `file`, `image`, `location` or `video`.
- `payload` <[Object][object-mdn-url]> `multimedia` or `location` payload.
  - `url` <[string][string-mdn-url]> URL of the file. _A `url` payload is only provided with a `multimedia` payload._
  - `coordinates` <[Object][object-mdn-url]> Coordinates of a location. _A `coordinates` payload is only provided with a `location` payload._
    - `lat` <[number][number-mdn-url]> Latitude.
    - `long` <[number][number-mdn-url]> Longitude.
- text <stringstring-mdn-url> Optional text of the message. A text is only provided when the event is a text message event.

HandleMessengerCodeResponse


messengerCode(appConfig)

verifySetup(verifyToken)

  • verifyToken <stringstring-mdn-url> Facebook verify token.
  • returns: express.Router an Expressexpressjs-url 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.

webhook(appConfig, options)

handleDomainWhitelisting(url, pageAccessToken, domains, options)

- result <string
string-mdn-url> If the operation is successful, the value is Successfully updated whitelisted domains.

handleMessengerCode(url, pageAccessToken, ref, imageSize, options)

- uri <stringstring-mdn-url> URL to the image of the generated messenger code.

deleteMessengerProfile(url, pageAccessToken, fields, options)

- result <stringstring-mdn-url> If the operation is successful, the value is success.

getMessengerProfile(url, pageAccessToken, fields, options)

- result <stringstring-mdn-url> If the operation is successful, the value is success.

setMessengerProfile(url, pageAccessToken, body, options)

- result <stringstring-mdn-url> If the operation is successful, the value is success.

handleReceiveMessage(appConfig, event, options)

handleReceivePostback(appConfig, event, options)

License

MIT License © Rong Sen Ng