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

@cxco/facebook-messenger

v2.0.1

Published

Ready-to-go integration between DigitalCX and Facebook's messenger platform

Downloads

1

Readme

@cxco/facebook-messenger

Introduction

DigitalCX's ready-to-go integration between DigitalCX and Facebook's messenger platform. This project requires you to set up an application on Facebook's Messenger platform. This project provides you with the webhook logic that you can expose on top of your pre-existing Express.js server.

Pre-requirements

Facebook Messenger Pre-requirements To start using the Facebook Messenger Integration (FMI) we have some requirements:

This module gets its content from a database (DigitalCX), so before you can proceed with anything, you’ll need to have a database created and published. Only then you can get the following information to connect to the right database:

  • Customer Key
  • Project Key
  • Api Key
  • Culture

In order to connect the FMI module to Facebook Messenger, you need to set up a project on Facebook. You can read all about it in their documentation.

To use the FMI node module you need to have a pre-existing Express server. This module is used as a middleware inside your Express server to make the communication between DigitalCX database and Facebook Messenger possible. The module provides webhook logic that you can expose on top of your Express server.

Getting Started

This is a Node.js module available through the npm registry. Before installing, download and install Node.js. This module was developed using Node.js v10.15.3.

Installation is done using the npm install command:

npm i @cxco/facebook-messenger

This module has been set up using Facebook Messenger's Node.js Getting Started guide.

Using the package

@cxco/facebook-messenger is a Express.js middleware function. Use it as such, passing in the necessary configuration options.

const express = require('express')
const messenger = require('@cxco/facebook-messenger')
// session tracking middleware (See Session Tracking section):
const middleware = require('./middleware')
const bodyParser =  require('body-parser'),

const app = express()

app.use(bodyParser.json())

app.use(middleware())

app.use('/messenger', messenger({
    project: {
        apiKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        customerKey: 'customerKey',
        projectKey: 'projectKey',
        culture: 'culture',
        context: [{ 'Implementation': 'FbMessenger' }]
    },
    messenger: {
        webhookVerificationToken: 'verification token',
        pageAccessToken: 'Facebook generated page access token'
    },
    messages: {
        noResponse: 'No response from DigitalCX',
        applicationError: 'Something went wrong! Please contact support'
    },
    express: {
        dcxSession: 'locals.session'
    }
}))

app.listen(3000)

Configuration

The DigitalCX Facebook Messenger integration offers a number of configuration options, some of them required and some of them optional. All configuration options need to be passed along wrapped in a single object and presented as the first parameter:

Global Options

|Parameter Name|Type|Description|Required|Example| |:-|:-|:-|:-|:-| |project|object|An object containing the information required to connect and authenticate your application with and to the DigitalCX engine. See "project options"|yes|{   "projectKey":"projectKey",   "customerKey":"customerKey",   "apiKey":"api key",,   "culture":"en"}| |messenger|object|An object containing the facebook tokens and settings required by the @cxco/facebook-messenger library.|yes|{   "webhookVerificationToken":"token",    "pageAccessToken":"token"}| |messages|object|An object containing the two possible (error) messages that can originate within the @cxco/facebook-messenger library. These error messages will be directly passed over to the caller whenever one such error occurs.|yes|{   "noResponse":"msg",    "applicationError":"msg"}| |express|object|An object that defines where the session is stored inside the request object. This package will use a variable in the request to keep track of the session. See section Session for more details. |yes|{dcxSession: 'locals.session'}|

Project Options

|Parameter Name|Type|Description|Required|Example| |:-|:-|:-|:-|:-| | apiKey | string | The given API Key | yes | "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" | | context | Object[] | Dimension to send in requests to DigitalCX | no | [{ 'Implementation': 'FbMessenger' }] | | culture | string | Language country code | yes | "en" | | customerKey | string | The given customer key | yes | "customerA" | | env | string | specifies which base url to use. Defaults to the production URL | no | "https://proxy.domain.com/customerA/projects/projectB" | projectKey | string | The given project key | yes | "projectB" | |

Once running, @cxco/facebook-messenger will expose the a '/webhook' endpoint. If you configure the middleware to be executed on a specific route then the routes will be nested.

Example:

// middleware executes in '/messenger' route
app.use('/messenger', messenger(config))

Then the middleware route will be: 'https://<your-express-server>/messenger/webhook'.

Session tracking

DigitalCX uses Session Properties to persist state on the session and keep state for values between different interactions, which becomes apparent for Dialogs where the previous and current Interaction are strongly tied together.

In the Facebook Messenger integration, the server running it needs to keep track of that session but because it receives request from several users it must keep a reference between "Facebook User" and the DCX Session.

There are many ways implement such a storage. As an example just for testing purposes, we used an in-memory database called "Lokijs". In the example below we use a database to store and write the necessary variables into the request object. Our middleware will later use this variable to read/write the DCX session variables.

// middleware.js
const loki = require('lokijs')
module.exports = function() {

   var db = new loki('database.json',{
       verbose: true,
       autosave: true,
       autosaveInterval: 4000
   })

   var sessions = db.addCollection('sessions', { autoupdate: true })

    return function (req, res, next) {
        const { entry } = req.body
        // sender information from Facebook payload
        const { sender } = entry[0].messaging[0]
        // initialize locals object
        req.locals = req.locals || {}

        const currentSession = findSession(sessions, sender.id)

        if(currentSession) {
            req.locals.session = currentSession
        } else {
            addSession(sessions, sender.id)
            req.locals.session = findSession(sessions, sender.id)
        }

        next()
    }
}

function findSession(collection, _sessionId) {

    return collection.findOne({ sessionId: _sessionId });
}

function addSession(collection, _sessionId) {
    collection.insert({ sessionId: _sessionId });
}

Features

  • Hooks into any Express.js server as Express middleware.
  • Offers full support for Q&A's, events, dialogs and transactional dialogs.
  • Each instance can be configured to integrate with a single customer-project-culture combination.
  • Multiple instances can easily be created

Build and Test

To run the test suite, first install the dependencies, then run npm test:

npm i
npm test