Skip to content

API Reference Version 3.0.0

Philipp Naderer-Puiu edited this page May 30, 2017 · 2 revisions

Classes

GraphApiError
MultipartStream
FBMessenger

GraphApiError

Kind: global class

new GraphApiError()

Error to be thrown for Graph API exceptions and errors. The original response with all error details is stored in the response property.

graphApiError.message

The error message.

Kind: instance property of GraphApiError

graphApiError.response

Original response JSON returned by the Graph API.

Kind: instance property of GraphApiError

MultipartStream

Kind: global class

new MultipartStream(name, source)

Object to wrap file uploads to the Graph API via multipart/form-data. The input can be a Stream for binary reading or a Path to the file.

Param Type Description
name string the name of the file
source io.Stream | fs.Path input binary stream or a path to the file

multipartStream.name

Name of the file

Kind: instance property of MultipartStream

multipartStream.stream : io.Stream | fs.Path

Input source or path

Kind: instance property of MultipartStream

FBMessenger

Kind: global class

new FBMessenger(pageAccessToken, batched)

A Facebook Messenger bot client. It manages the HTTPS-based communication with the API endpoint and handles potential error. The supported Graph API level is v2.9.

Param Type Description
pageAccessToken string the bot's access token to a Facebook page
batched boolean batch requests into a single Graph API call until .sendBatch() is called. Note: MultipartStream attachments can't be batched and are immediately sent.

fbMessenger.sendBatch()

Sends all queued requests if the client operates in the batched request mode. The Graph API v2.8 accepts up to 50 sub-request per batch request.

Kind: instance method of FBMessenger
See: Graph API - Making Batch Requests
Example

const bot = new FBMessenger("my-page-token", true);
for (let i = 1; i <= 50; i++) {
  bot.sendTextMessage(userId, "A message #" + i);
}
bot.sendBatch();

fbMessenger.sendSenderAction(id, action)

Sends a typing indicators or send read receipts to the given user id.

Kind: instance method of FBMessenger
See: Messenger Platform - Sender Actions

Param Type Description
id string recipient user id
action string the specific sender action to send: mark_seen, typing_on, or typing_off

fbMessenger.sendTextMessage(id, messageText, notificationType, tag)

Sends a plain text message to the user.

Kind: instance method of FBMessenger
See: Messenger Platform - Text Message

Param Type Description
id string recipient user id
messageText string the message text
notificationType string push notification type, defaults to REGULAR
tag string message tag to send outside the 24+1 time window

fbMessenger.sendReusableAttachment(id, type, attachment, notificationType, tag)

Sends an reusable attachment to the user.

Kind: instance method of FBMessenger
See: Messenger Platform - Attachment Reuse

Param Type Description
id string recipient user id
type string the Send API content type of the reusable attachment
attachment string the id of the reusable attachment
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

Example

bot.sendReusableAttachment(userId, "image", "1234567890");

fbMessenger.sendImageAttachment(id, image, reusable, notificationType, tag)

Sends an image attachment via uploading them or sharing a URL to the image. Supported formats are jpg, png and gif.

Kind: instance method of FBMessenger
See: Messenger Platform - Image Attachment

Param Type Description
id string recipient user id
image string | MultipartStream the image to send via URL or multipart stream
reusable boolean true if the image can be cached by Facebook, defaults to false
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

Example

// via multipart upload
let {Path} = require("fs");
let filePath = new Path(module.resolve("/path/to/photo.jpg"));
let multipart = new MultipartStream("photo.jpg", filePath);
bot.sendImageAttachment(userId, multipart);

// via URL
bot.sendImageAttachment(userId, "http://example.org/photo.jpg");

fbMessenger.sendAudioAttachment(id, audio, reusable, notificationType, tag)

Sends an image attachment via uploading them or sharing a URL to the recording. Supported format is mp3.

Kind: instance method of FBMessenger
See: Messenger Platform - Audio Attachment

Param Type Description
id string recipient user id
audio string | MultipartStream the audio file to send via URL or multipart stream
reusable boolean true if the audio can be cached by Facebook, defaults to false
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

Example

// via multipart upload
let {Path} = require("fs");
let filePath = new Path(module.resolve("/path/to/music.mp3"));
let multipart = new MultipartStream("music.mp3", filePath);
bot.sendAudioAttachment(userId, multipart);

// via URL
bot.sendAudioAttachment(userId, "http://orf.at/fm4.mp3");

fbMessenger.sendVideoAttachment(id, video, reusable, notificationType, tag)

Sends an image attachment via uploading them or sharing a URL to the video. Supported format is mp4.

Kind: instance method of FBMessenger
See: Messenger Platform - Video Attachment

Param Type Description
id string recipient user id
video string | MultipartStream the video to send via URL or multipart stream
reusable boolean true if the video can be cached by Facebook, defaults to false
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

Example

// via multipart upload
let {Path} = require("fs");
let filePath = new Path(module.resolve("/path/to/video.mp4"));
let multipart = new MultipartStream("video.mp4", filePath);
bot.sendVideoAttachment(userId, multipart);

// via URL
bot.sendVideoAttachment(userId, "http://orf.at/orfIII.mp4");

fbMessenger.sendFileAttachment(id, file, reusable, notificationType, tag)

Sends a file to download via upload or by providing an URL to the file.

Kind: instance method of FBMessenger
See: Messenger Platform - File Attachment

Param Type Description
id string recipient user id
file string | MultipartStream the file to send via URL or multipart stream
reusable boolean true if the file can be cached by Facebook, defaults to false
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

fbMessenger.sendGenericTemplate(id, elements, notificationType, sharable, imageAspectRatio, tag)

Sends a generic template with images in a horizontal scrollable carousel of items.

Kind: instance method of FBMessenger
See: Messenger Platform - Generic Template

Param Type Description
id string recipient user id
elements Array horizontal scrollable carousel of items.
notificationType string push notification type, defaults to REGULAR.
sharable boolean if false it disables the share button in Messenger client, defaults to true
imageAspectRatio string aspect ratio used to render images, must be horizontal or square, defaults to horizontal
tag string message tag to send outside the 24+1 time window

Example

bot.sendGenericTemplate(message.sender.id, [
  {
    "title":"„Pokemon Go“: Headline",
    "image_url":"http://orf.at/4699402.jpg",
    "subtitle":"Pikachu und Co. erobern erneut die Welt.",
    "buttons":[
      {
        "type":"web_url",
        "url":"http://orf.at/stories/2349101/",
        "title":"Story lesen \uD83D\uDC53"
      },
      {
        "type":"postback",
        "title":"Mehr zu Pokemon Go",
        "payload": "news:stories:pokemongo"
      }
    ]
  },
  {
    "title":"Alles steht Kopf",
    "image_url":"http://orf.at/pixar.jpg",
    "subtitle":"„Alles steht Kopf“ spielt im Hirn.",
    "buttons":[
      {
        "type":"web_url",
        "url":"http://orf.at/stories/2300732/",
        "title":"Story lesen \uD83D\uDC53"
      },
      {
        "type":"postback",
        "title":"Mehr über Pixar",
        "payload": "news:stories:pixar"
      }
    ]
  }
]);

fbMessenger.sendButtonTemplate(id, text, buttons, sharable, notificationType, tag)

Sends a text and buttons attachment to request input from the user.

Kind: instance method of FBMessenger
See: Messenger Platform - Button Template

Param Type Description
id string recipient user id
text string the text at the top of the buttons
buttons Array an array of buttons
sharable boolean if false it disables the share button in Messenger client, defaults to true
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

Example

bot.sendButtonTemplate(userId, "Who will win?", [
  {
    "type": "postback",
    "title": "Austria",
    "payload": "vote:austria"
  },
  {
    "type": "postback",
    "title": "Germany",
    "payload": "vote:germay"
  },
  {
    "type":"web_url",
    "url":"http://sport.ORF.at",
    "title":"Visit sport.ORF.at"
  }
]);

fbMessenger.sendAdvancedTemplate(id, payload, notificationType, tag)

Sends a template with the provided payload. This is useful to send list templates, receipt templates, airline templates, or other specific templates not covered by the generic and button template call.

Kind: instance method of FBMessenger
See

Param Type Description
id string recipient user id
payload Object the payload depending on the template to send
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

Example

bot.sendAdvancedTemplate(message.sender.id, {
  "template_type": "airline_checkin",
  "intro_message": "Check-in is available now!",
  "locale": "en_US",
  "pnr_number": "XYZDD",
  "flight_info": [
    {
      "flight_number": "RG1234",
      "departure_airport": {
        "airport_code": "VIE",
        "city": "Vienna International Airport",
        "terminal": "T3",
        "gate": "F16"
      },
      "arrival_airport": {
        "airport_code": "TSR",
        "city": "Timișoara",
        "terminal": "T1",
        "gate": "G1"
      },
      "flight_schedule": {
        "boarding_time": "2016-12-24T10:00",
        "departure_time": "2016-12-24T11:00",
        "arrival_time": "2016-12-24T12:10"
      }
    }
  ],
  "checkin_url": "https:\/\/www.orf.at"
);

fbMessenger.sendQuickReplies(id, attachmentOrText, quickReplies, reusable, notificationType, tag)

Sends a quick reply to present buttons to the user.

Kind: instance method of FBMessenger
See: Messenger Platform - Quick Replies

Param Type Description
id string recipient user id
attachmentOrText string | MultipartStream attachment for the message
quickReplies Array the provided quick replies
reusable boolean true if the attachment can be cached by Facebook, defaults to false
notificationType string push notification type, defaults to REGULAR.
tag string message tag to send outside the 24+1 time window

Example

bot.sendQuickReplies(message.sender.id, "http://orf.at/animated.gif", [
  {
    "content_type": "text",
    "title": "WTF?!",
    "payload": "quick:wtf:" + Date.now()
  },
  {
    "content_type": "text",
    "title": "Cool!",
    "payload": "quick:cool:" + Date.now()
  }
]);

fbMessenger.setGreetingText(greetings)

Sets the thread greeting text for the start of a conversation with the bot.

Kind: instance method of FBMessenger
See: Messenger Platform - Greeting Text

Param Type Description
greetings string an array of greetings in different locales

Example

bot.setThreadGreetingText([
  {
    "locale": "default",
    "text": "Hello World!"
  },
  {
    "locale": "en_US",
    "text": "Hello USA!"
  }
]);

fbMessenger.setGetStartedButton(payloadString)

Sets a Get Started button for the welcome screen.

Kind: instance method of FBMessenger
See: Messenger Platform - Get Started Button

Param Type Description
payloadString string the payload string to reply to the bot

Example

let payloadString = JSON.stringify({ event: "user_pressed_started" });
bot.setThreadGetStartedButton(payloadString);

fbMessenger.setPersistentMenu(menuItems)

Sets a persistent menu always available for a user. This menu should contain top-level actions that users can enact at any point. You must set up a "Get Started" button if you also wish to use persistent menu. call_to_actions is limited to 3 items for the top level, and 5 items for any submenus.

This method changed from 2.x to 3.x due the new Messenger APIs.

Kind: instance method of FBMessenger
See: Messenger Platform - Persistent Menu

Param Type Description
menuItems Array an array menus; each menu requires a specified locale and an array of call to action items, and an optional composer input setting

Example

bot.setPersistentMenu([
  {
    "locale": "default",
    "composer_input_disabled": true,
    "call_to_actions": [
      {
        "type": "postback",
        "title": "Current News",
        "payload": "read:news"
      },
      {
        "type": "postback",
        "title": "Bundesliga Results",
        "payload": "read:buli.results"
      },
      {
        "type": "web_url",
        "url": "http://sport.ORF.at",
        "title": "Visit sport.ORF.at"
      },
      {
        "title": "About",
        "type": "nested",
        "call_to_actions": [
           {
             "type":"web_url",
             "url":"http://sport.ORF.at/about/",
             "title": "About Sport"
          },
          {
             "type":"web_url",
             "url":"http://news.ORF.at/about/",
             "title":"About News"
          }
        ]
      }
    ]
  },
  {
    "locale": "de",
    "composer_input_disabled": false,
    "call_to_actions": [
      {
        "type": "postback",
        "title": "Aktuelle Nachrichten",
        "payload": "read:news"
      },
      {
        "type": "postback",
        "title": "Fußballspiele",
        "payload": "read:buli.results"
      },
      {
        "type":"web_url",
        "url":"http://sport.ORF.at",
        "title":"Visit sport.ORF.at"
      }
    ]
  }
]);

fbMessenger.getUserProfile(userId, fields)

Gets basic public accessible user profile information.

Kind: instance method of FBMessenger

Param Type Description
userId string the user's id
fields Array optional fields to retrieve.

Example

bot.getUserProfile(userId, ["locale", "timezone"]);

fbMessenger.whitelistDomains(domains)

Whitelists an array of domains as suitable for Web Views and other plugins. Up to 10 domains allowed.

Kind: instance method of FBMessenger
See: Messenger Platform - Domain Whitelisting

Param Type Description
domains Array a list of domains to whitelist

Example

bot.whitelistDomains(["https://orf.at", "https://ringojs.org"]);

fbMessenger.setAccountLinkUrl(accountLinkingUrl)

Allows to specify an `account_linking_url

Kind: instance method of FBMessenger
See: Messenger Platform - Account Linking

Param Type Description
accountLinkingUrl string the authentication callback URL

Example

bot.setAccountLinkUrl("https://auth.example.org/foo/bar.aspx");

fbMessenger.setAudienceType(audienceType, countries)

Lets specify target audiences for the bot.

Kind: instance method of FBMessenger
See: Messenger Platform - Target Audience

Param Type Description
audienceType string the audience type to set; valid values are all, custom, or none
countries object the country object containing a whitelist or a blacklist property

Example

bot.setAudienceType("custom", {
  "whitelist": ["DE", "AT", "CH"]
});

bot.setAudienceType("all");

fbMessenger.setHomeUrl(homeUrl)

Enables a chat extension in the composer drawer.

Kind: instance method of FBMessenger
See: Messenger Platform - Home URL

Param Type Description
homeUrl object a home url object with the required properties url, web view ratio, and testing status

Example

bot.setHomeUrl({
  "url": "https://dev.orf.at/",
  "webview_height_ratio": "tall",
  "webview_share_button": "show",
  "in_test": true
});

fbMessenger.deleteProfileFields(fields)

Allows to delete specific fields of the bot's messenger profile.

Kind: instance method of FBMessenger

Param Type Description
fields Array fields to unset

Example

bot.deleteProfileFields(["home_url"]);

fbMessenger.getDailyUniqueActiveThreads()

Retrieves the daily unique active thread count metric via the Pages Insights API.

Kind: instance method of FBMessenger
See: Messenger Platform - Page Messaging Insights
Example

const duatc = bot.getDailyUniqueActiveThreads();

fbMessenger.getDailyUniqueConversations()

Retrieves the daily unique conversation count via the Pages Insights API.

Kind: instance method of FBMessenger
See: Messenger Platform - Page Messaging Insights
Example

const duc = bot.getDailyUniqueConversations();

fbMessenger.getMessengerCode(type, imageSize, ref) ⇒ string

Get the messenger code for the current page.

Kind: instance method of FBMessenger
Returns: string - the URL of the Messenger code or null
See: Messenger Platform - Messenger Code

Param Type Description
type string optional the code type to generate; default is standard
imageSize string optional image size of the code; defaults to 1000
ref string optional referral parameter containing only a-z A-Z 0-9 +/=-.:_

Example

const url = bot.getMessengerCode();

fbMessenger.uploadAttachment(type, url) ⇒ string

Uploads an reusable attachment that you may later send out to many users. Even if the method is named uploadAttachment you must specify it as an URL and not as an multipart attachment.

Kind: instance method of FBMessenger
Returns: string - the reusable non-expiring attachment id
See: Messenger Platform - Attachment Upload

Param Type Description
type string media type of the attachment, must be image, audio, video, or file
url string url of the attachment where the Messenger platform can fetch from

Example

const attachmentId = bot.uploadAttachment("image", "https://example.org/foo.jpg");
Clone this wiki locally