npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fb.me

v0.3.0-alpha.4

Published

Express app for chatbot development with Facebook Messenger

Downloads

10

Readme

NPM

Version Downloads MIT License Code of Conduct

Build Status NSP Status Dependency Status Codecov Coverage Status

codebeat-badge codacy-badge

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:

  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

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. 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.
      • type <string> audio, fallback, file, image, location or video.
      • payload <Object> multimedia or location payload.
        • url <string> URL of the file. A url payload is only provided with a multimedia payload.
        • coordinates <Object> Coordinates of a location. A coordinates payload is only provided with a location payload.
    • text <string> Optional text of the message. A text 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 the hub.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. 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.

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 is Successfully updated whitelisted domains.

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

  • 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.
  • 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])

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 is success.

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 is success.

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. 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.

handleReceivePostback(appConfig, event[, options])

License

MIT License © Rong Sen Ng