fbmessenger
A library to integrate with the Facebook Messenger Platform.
Notice: Please see the CHANGELOG for any breaking changes.
Table of contents
- Installation
- Express.js (example usage)
- Events
- Sending messages
- Catching errors
- Getting user details
- Elements
- Attachments
- Templates
- Thread settings
- Sender Actions
- Quick Replies
- Whitelisted domains
- Subscribing an app to a page
- Account linking
- Sending raw payloads
Installation
Execute this line in your app directory:
yarn add fbmessenger
or for npm
npm install --save fbmessenger
Import library into your app:
;
Initialize it:
const messenger = pageAccessToken: '<PAGE_ACCESS_TOKEN>';
Configuration of facebook app
First of all visit the official tutorial and make sure you complete these 3 steps:
Steps:
-
Create page on Facebook or use existing one if you already have it
-
Create app on Facebook or use existing one if you already have it
-
Visit your developer account and get the
PAGE_ACCESS_TOKEN
-
Subscribe the app to a page
Express.js (example usage)
This is basic usage within an express.js application. For more detailed example look here.
;; // Configuring Body Parser middleware to parse the incoming JSON and Url-encoded dataapp;app; // Initialize Messengerconst messenger = pageAccessToken: '<PAGE_ACCESS_TOKEN>'; // here we define some listeners:messenger; messenger; // This example shows how to setup verification using expressapp; // This route handles the webhook callbacks from Facebookapp;
Verifying Requests
It's important but not fundamental to verify each request that your application receives to make sure that who is calling your /webhook
endpoint is Facebook and not some other person. That could be done by through verifying the Signature Hash that Facebook sends on every request. You will need to have your APP_SECRET
in hands for performing such verification.
// Function that verifies the signature hashconst verifyRequestSignature = { const signature = reqheaders'x-hub-signature'; if !signature throw 'Couldn\'t validate the signature.'; else const elements = signature; const signatureHash = elements1; const expectedHash = crypto; if signatureHash !== expectedHash throw 'Couldn\'t validate the request signature.'; }; // Pass a function that verifies the signature instead of just calling app.use(bodyParser.json())app
Events
Events are triggered when Facebook posts to your webhook url. The following events can be listened for:
- message
- delivery
- optin
- read
- account_linking
- postback
- referral
- checkout_update
- payment
- pre_checkout
Listening for events
messenger;
example console output
sender: id: 1234 recipient: id: 1234 timestamp: 1457764197627 message: text: 'Hello World!'
Sending messages
Messages are sent using the send(message, recipient)
method.
It returns a Promise (from node-fetch).
If replying to a user, the recipient can be obtained from message.sender.id
in the event listener. Otherwise it should be a Facebook page scope ID from a database or other data store.
Send a simple text reply
messenger;
Catching errors
You can add a catch
to get errors from the request.
messenger ;
or if using async/await you can wrap your code in a try/catch block
messenger;
Get a user's details
Example usage:
messenger ;
Returns object with user data:
first_name
last_name
profile_pic
locale
timezone
gender
is_payment_enabled
Elements
Text
https://developers.facebook.com/docs/messenger-platform/send-api-reference/text-message
Example usage:
; messenger;
you can also just pass an object to the send
method like this
text: 'Hello World!'
Button
https://developers.facebook.com/docs/messenger-platform/send-api-reference/buttons
Example (with ButtonTemplate):
; messenger;
For more examples, check out the tests.
Element
https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template
Example usage:
; ... itle: 'Title' item_url: 'http://www.example.com' image_url: 'http://www.example.com' subtitle: 'Subtitle' buttons: type: 'web_url' title: 'Web Url Button' url: 'http://www.example.com' type: 'postback' title: 'Postback Button' payload: 'POSTBACK_INFO' ;...
Address
https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template
This element must be used with the Receipt template.
Example usage:
; ... street_1: '1 Hacker Way' street_2: '' city: 'Menlo Park' postal_code: '94025' state: 'CA' country: 'US';...
Summary
https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template
This element must be used with the Receipt template.
Example usage:
; ... subtotal: 7500 shipping_cost: 495 total_tax: 619 total_cost: 5614;...
Adjustment
https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template
This element must be used with the Receipt template.
Example usage:
; ... name: 'Adjustment' amount: 20;...
Attachments
Image
https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment
Example usage:
; messenger;
Audio
https://developers.facebook.com/docs/messenger-platform/send-api-reference/audio-attachment
Example usage:
; messenger;
Video
https://developers.facebook.com/docs/messenger-platform/send-api-reference/video-attachment
Example usage:
; messenger;
File
https://developers.facebook.com/docs/messenger-platform/send-api-reference/file-attachment
Example usage:
; messenger;
Reusable attachments
Attachments can be reused by passing true
as the second parameter. This sets the is_reusable
flag.
const image = url: 'http://lorempixel.com/400/400/sports/1/' is_reusable: true;messenger;
You can then use the attachment_id
from the response to send the same attachment again
messenger
Attachment Upload API
const image = url: 'http://lorempixel.com/400/400/sports/1/' is_reusable: true;messenger;
This will return a reusable attachment ID.
Templates
ButtonTemplate
https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
Example usage:
; messenger;
GenericTemplate
https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template
Example usage:
; messenger;
ReceiptTemplate
https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template
Example usage:
; messenger;
Thread settings
Greeting Text
https://developers.facebook.com/docs/messenger-platform/thread-settings/greeting-text
const greeting = 'Hello';messenger;
There is also a method to delete the greeting text called deleteGreetingText
Get Started Button
https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button
; const getStarted = 'start';messenger;
When someone first interacts with your bot they will see a Get Started
button. When this is clicked it will send a postback
to your server with the value of start
.
There is also a method to delete the Get Started Button called deleteGetStarted
Persistent Menu
https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu
; const item_1 = item_type: 'web_url' title: 'Menu button 1' url: 'http://facebook.com'; const item_2 = item_type: 'payload' title: 'Menu button 2' payload: 'menu_button_2'; const item_3 = item_type: 'web_url' title: 'Menu button 3' url: 'http://facebook.com' webview_height_ratio: 'tall' messenger_extensions: true; const menu = item_1 item_2 item_3;messenger;
You can delete the Persistent Menu using the deletePersistentMenu
method
Sender Actions
Available actions are
typing_on
typing_off
mark_seen
messenger;
Quick Replies
Quick Replies work with all message types including text message, image and template attachments.
const reply1 = title: 'Example' payload: 'payload';const reply2 = title: 'Location' content_type: 'location';const quick_replies = reply1 reply2; const text = 'A simple text message' const payload = Object messenger
Whitelisted domains
Adding
// Singlemessenger; // Multiplemessenger;
Removing
// Singlemessenger; // Multiplemessenger;
Messenger Code API
messenger;messenger;
Subscribing an app to a page
The easiest way to do this is now through the Facebook developer site. If you need to do this progamatically you can use subscribeAppToPage
Account linking
You can link and unlink accounts with linkAccount
and unlinkAccount
messenger;
messenger;
Sending raw payloads
You can also send raw payloads with send
. This lets you use any new features from Facebook while waiting for support to be added to this library.
messenger;