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-messenger-app

v4.2.0

Published

NodeJS API adapter for Messenger Platform

Downloads

83

Readme

Facebook Messenger Platform App

Node API adapter in ECMAScript 2015 (ES6)

npm npm JavaScript Style Guide npm

Codacy Badge bitHound Overall Score

Installation

Install the fb-messenger-app package in your node server app's local node_modules folder.

npm install --Save fb-messenger-app

How to start

I take for granted that you've already setup your Messenger Platform app:

  1. Created a Facebook App and Page
  2. Setup the Webhook
  3. Got a Page Access Token
  4. Subscribed the App to the Page

After installing the fb-messenger-app package with npm as shown above, import it in your app

const MessengerApp = require('fb-messenger-app')

Then create a new messenger instance passing your Facebook App page access token (this token will include all messenger permissions)

var messenger = new MessengerApp(MY_PAGE_ACCESS_TOKEN)

Receive Messages

You'll have to listen for POST calls at your webhook. Callbacks will be made to this webhook. For this purpose, _handleCallback will listen and dispatch each callback type by emitting its corresponding event.

app.post('/webhook', function (req, res) {
  var data = req.body
  messenger._handleCallback(res, data)
})

Send Messages to the user

All messages must be send through the sendApiMessage method. It'll make POST calls to facebook's Graph API with your app's page access token, and a JSON payload with the 'recipient's id' and the message object to be send. For more information about the payload supported by facebook go ahead an read more here.

messenger.sendApiMessage(USER_ID, {text: 'Howdy!'})

var myImage = {
  attachment:
    { 
      type: 'image',
      payload: { 
        url: 'https://petersapparel.com/img/shirt.png'
      }
    }
  }

messenger.sendApiMessage(USER_ID, myImage)

Using callbacks

A successful send API request returns a JSON with the identifier of the user and the message.

{
  "recipient_id": "1008372609250235",
  "message_id": "mid.1456970487936:c34767dfe57ee6e339"
}

On the other hand, a when the send API request fails, a JSON is returned with the corresponding error code and message. Messenger Platform errors are grouped by code, with a different message depending on the error condition. Read more here

{
  "error": {
    "message": "Invalid OAuth access token.",
    "type": "OAuthException",
    "code": 190,
    "fbtrace_id": "BLBz/WZt8dN"
  }
}

Finally, an example would be the following.

messenger.sendApiMessage(USER_ID, myBrandProducts, function (err, body) {
  if (err) return console.log('Something went wrong: could not send my brand products')
  console.log('Generic message with my brand products where send to %d', USER_ID)
})

Notifications

Optionally, depending on the case, sometimes you'll want to bring the user attention with a normal push. Other times, a silent notification would be enough, and, why not, it would be appropiate not to bother the user at all. We can achieve this by adding the notificationType parameter.

Types

If missing, a regular push notification will be sent.

  • REGULAR : will emit a sound/vibration and a phone notification
  • SILENT_PUSH : will just emit a phone notification
  • NO_PUSH : will not emit either
messenger.sendTextMessage(USER_ID, 'Hey! Check this out!', 'REGULAR')
messenger.sendTextMessage(USER_ID, "Check this out, there's no hurry...", 'SILENT_PUSH')
messenger.sendTextMessage(USER_ID, 'If you see this message, check this out', 'NO_PUSH')

Configure the notification type default

Set the bot's default notification type when instantiating it.

var messenger = new MessengerApp(MY_PAGE_ACCESS_TOKEN, 'SILENT_PUSH')

Sender Actions

Set typing indicators or send read receipts.

  • mark_seen : Mark last message as read
  • typing_on : Turn typing indicators on
  • typing_off : Turn typing indicators off
messenger.senderAction.sendSenderActionRequest(USER_ID, 'typing_on')

You can send specific actions during given time intervals.

Make the bot type for a given period of time
messenger.senderAction.sendTypingInterval(USER_ID, 2000)
Mark the last message as read when after a given timeout
messenger.senderAction.sendMarkSeenInterval(USER_ID, 1000)

Verification

There are two moments where you'll want to verify that things are fine.

validate your webhook to make sure you're subscribed to any change
app.post('/webhook', function (req, res) {
  messenger.verify.webhook(req, res)
})
validate the requests signature to make sure they come from facebook (express.js)
const app = express()
app.use(bodyParser.json({
  verify: messenger.verify.signature.bind(undefined, APP_SECRET)
}))

API

Constructor
var messenger = new MessengerApp(token [, options])

The following table describes the properties of the options object.

| Property | Description | Type | Default | | ------------------ |:--------------------------------------------------:|:------:| --------:| | notificationType | Determines how messages will be pushed to the user | String | 'REGULAR' | | apiUrl | Facebook's Graph API | String | 'https//graph.facebook.com/v2.6/' |

Methods
messenger.sendApiMessage(recipient, message [, notificationType] [, cb])

messenger.sendSenderAction(recipient, senderAction [, cb])

messenger.getUserProfile(userId [, cb])

messenger.subscribeApp([cb])

messenger.getUserPsid(tokeb [, cb])

messenger.unlinkAccount(psid [, cb])

messenger.threadSetting.setGreetingText(text [, cb])

messenger.threadSetting.setGetStartedButton(payload [, cb])

messenger.threadSetting.setPersistentMenu(menuItems [, cb])

messenger.threadSetting.deleteGetStartedButton([cb])

messenger.threadSetting.deletePersistentMenu([cb])

messenger.threadSetting.sendSettingRequest(method, params [, cb])

messenger.senderAction.sendSenderActionRequest(recipient, senderAction [, cb])

messenger.senderAction.sendTypingInterval(recipient, time [, cb])

messenger.senderAction.sendMarkSeenInterval(recipient, time [, cb])

messenger._handleCallback(res, data)

messenger._handleEvent(type, event)

messenger.verify.webhook(verifyToken, req, res)

messenger.verify.signature(appSecret, req, res, buf)

License

Code

MIT License.