@messageflow/send-as

Utility library for Facebook Messenger's Send API in Node.js

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
@messageflow/send-as
000.1.16 years ago6 years agoMinified + gzip package size for @messageflow/send-as in KB

Readme

@messageflow/send-as

Utility library for Facebook Messenger's Send API in Node.js




!Versionversion-badgeversion-url !Node versionnode-version-badgenode-version-url !MIT Licensemit-license-badgemit-license-url
!Downloadsdownloads-badgedownloads-url !Total downloadstotal-downloads-badgedownloads-url !Packagephobiapackagephobia-badgepackagephobia-url !Bundlephobiabundlephobia-badgebundlephobia-url
!Build Statustravis-badgetravis-url !CircleCIcircleci-badgecircleci-url !Dependency Statusdaviddm-badgedaviddm-url !codecovcodecov-badgecodecov-url !Coverage Statuscoveralls-badgecoveralls-url
!codebeat badgecodebeat-badgecodebeat-url !Codacy Badgecodacy-badgecodacy-url !Code of Conductcoc-badgecoc-url
Facebook Messenger Send APIfb-send-api-url is the main API used to send messages to users. Besides sending plain text messages, the API allows one to send:-

  1. Quick replies
  2. Rich media messages (images, audios, videos, or files)
  3. Templates (generic template, button template, receipt template, list template)

This simple utility library makes sending all these types of messages easier but ONLY a few of them are supported with utility method as of now due to usage. However, one can always use the base method to send any message type as custom payload.
| Message Type | Utility method | | --- | :---: | | custom payloadcustom-payload-ref-url | ✅ | | read receiptread-receipt-ref-url | ✅ | | typing bubbletyping-bubble-ref-url | ✅ | | texttext-ref-url | ✅ | | quickrepliesquick-reply-ref-url | ✅ | | button templatebutton-template-ref-url | ✅ | | generic templategeneric-template-ref-url | ✅ | | receipt templatereceipt-template-ref-url | ✅ |

Table of contents

- Install - Usage
- [Node.js](#nodejs)
- [Native ES modules or TypeScript](#native-es-modules-or-typescript)
- Recipient - SendAsParams - SendAsReadReceiptParams - SendAsTypingBubbleParams - SendAsTextParams - SendAsQuickReplyParams - SendAsButtonTemplateParams - SendAsGenericTemplateParams - SendAsReceiptTemplateParams - Response - ErrorResponse - sendAs(params) - sendAsReadReceipt(params) - sendAsTypingBubble(params) - sendAsText(params) - sendAsQuickReply(params) - sendAsButtonTemplate(params) - sendAsGenericTemplate(params) - sendAsReceiptTemplate(params)

Pre-requisites

Setup

Install

# Install via NPM
$ npm install --save @messageflow/send-as

Usage

Node.js

const {
  sendAs,
  // sendAsButtonTemplate,
  // sendAsGenericTemplate,
  // sendAsQuickReply,
  // sendAsReadReceipt,
  // sendAsReceiptTemplate,
  // sendAsText,
  // sendAsTypingBubble,
} = require('@messageflow/send-as');

/** Send as custom payload */
void async function demoSendAsCustomPayload() {
  try {
    const recipient = {
      /**
       * These IDs are page-scoped IDs (PSID).
       * This means that the IDs are unique for a given page.
       **/
      id: '<PSID>',
    };
    const message = {
      attachment: {
        type: 'template',
        payload: {
          template_type: 'media',
          elements: [
            {
              media_type: '<image|video>',
              url: '<FACEBOOK_URL>',
            },
          ],
        },
      },
    };
    const d = await sendAs({
      message,
      recipient,
      url: '<FACEBOOK_GRAPH_URL>/me/messages?access_token=<FACEBOOK_PAGE_ACCESS_TOKEN>',
    });

    assert.deepEqual(d, {
      message_id: 'mid.$cAAJsujCd2ORj_1qmrFdzhVa-4cvO',
      recipient_id: '<PSID>',
    }); // OK
  } catch (e) {
    console.error('Failed to send as custom payload', e);
  }
}();

Native ES modules or TypeScript

import {
  sendAs,
  // sendAsButtonTemplate,
  // sendAsGenericTemplate,
  // sendAsQuickReply,
  // sendAsReadReceipt,
  // sendAsReceiptTemplate,
  // sendAsText,
  // sendAsTypingBubble,
} from '@messageflow/send-as';

/** Send as custom payload */
void async function demoSendAsCustomPayload() {
  try {
    const recipient = {
      /**
       * These IDs are page-scoped IDs (PSID).
       * This means that the IDs are unique for a given page.
       **/
      id: '<PSID>',
    };
    const message = {
      attachment: {
        type: 'template',
        payload: {
          template_type: 'media',
          elements: [
            {
              media_type: '<image|video>',
              url: '<FACEBOOK_URL>',
            },
          ],
        },
      },
    };
    const d = await sendAs({
      message,
      recipient,
      url: '<FACEBOOK_GRAPH_URL>/me/messages?access_token=<FACEBOOK_PAGE_ACCESS_TOKEN>',
    });

    assert.deepEqual(d, {
      message_id: 'mid.$cAAJsujCd2ORj_1qmrFdzhVa-4cvO',
      recipient_id: '<PSID>',
    }); // OK
  } catch (e) {
    console.error('Failed to send as custom payload', e);
  }
}();

API Reference

Recipient

SendAsParams

- text <stringstring-mdn-url> Message text. Must be UTF-8 and has a 2000 character limit. text or attachment must be set. - attachment <Objectobject-mdn-url> Used to send messages with media or structured messages. text or attachment must be set. - quick_replies <Objectobject-mdn-url> Optional array of quick_reply to be sent with messages. - metadata <stringstring-mdn-url> Optional custom string that is delivered as a message echo. 1000 character limit. - REGULAR: sound/ vibration. - SILENT_PUSH: on-screen notification only. - NO_PUSH: no notification.

SendAsReadReceiptParams

SendAsTypingBubbleParams

SendAsTextParams

- text <stringstring-mdn-url> Message text. Must be UTF-8 and has a 2000 character limit. - REGULAR: sound/ vibration. - SILENT_PUSH: on-screen notification only. - NO_PUSH: no notification.

SendAsQuickReplyParams

- text <stringstring-mdn-url> Non-empty message text to send with the quick replies. text or attachment must be set. 2000 character limit. - attachment <Objectobject-mdn-url> Optional attachment to send with the quick replies. text or attachment must be set. - quick_replies <Arrayarray-mdn-url<quickreplysend-api-quick-reply-url>> An array of objects the describe the quick reply buttonssend-messages-buttons-url to send. A maximum of 11 quick replies are supported. - REGULAR: sound/ vibration. - SILENT_PUSH: on-screen notification only. - NO_PUSH: no notification.

SendAsButtonTemplateParams

- attachment <Objectobject-mdn-url> An object describing attachments to the message.
- `type` <[string][string-mdn-url]> Value must be `template`.
- `payload` <[Object][object-mdn-url]> Payload of the template.
  - `template_type` <[string][string-mdn-url]> Value must be `button`.
  - `text` <[string][string-mdn-url]> Must be UTF-8 encoded text. 640 character limit.
  - `buttons` <[Array][array-mdn-url]<[button][send-messages-buttons-url]>> An array of 1 - 3 buttons that appear as call-to-actions.
- REGULAR: sound/ vibration. - SILENT_PUSH: on-screen notification only. - NO_PUSH: no notification.

SendAsGenericTemplateParams

- attachment <Objectobject-mdn-url> An object describing attachments to the message.
- `type` <[string][string-mdn-url]> Value must be `template`.
- `payload` <[Object][object-mdn-url]> Payload of the template.
  - `template_type` <[string][string-mdn-url]> Value must be `generic`.
  - `elements` <[Array][array-mdn-url]<[Object][object-mdn-url]>> An array of element objects that describe instances of the generic template to be sent. A horizontally scrollable carousel forms when more than 1 element in a template. 10 elements limit.
    - `title` <[string][string-mdn-url]> Title of the template. 80 character limit.
    - `subtitle` <[string][string-mdn-url]> Optional subtitle of the template. 80 character limit.
    - `image_url` <[string][string-mdn-url]> Optional image URL of the template.
    - `default_action` <[Object][object-mdn-url]> Optional default action executed when the template is tapped. Has the same properties as [URL button][send-api-url-button-url], except the `title`.
    - `buttons` <[Array][array-mdn-url]<[button][send-messages-buttons-url]>> Optional array of buttons to append to the template. 3 buttons limit for each element.
  - `sharable` <[boolean][boolean-mdn-url]> Optional native share button in Messenger for the the template message. Defaults to `false`.
  - `image_aspect_ratio` <[string][string-mdn-url]> Optional aspect ratio used to render images specified by `element.image_url`. Must be `horizontal` (1.91:1) or `square` (1:1). Defaults to `horizontal`.
- REGULAR: sound/ vibration. - SILENT_PUSH: on-screen notification only. - NO_PUSH: no notification.

SendAsReceiptTemplateParams

- attachment <Objectobject-mdn-url> An object describing attachments to the message.
- `type` <[string][string-mdn-url]> Value must be `template`.
- `payload` <[Object][object-mdn-url]> Payload of the template.
  - `template_type` <[string][string-mdn-url]> Value must be `receipt`.
  - `recipient_name` <[string][string-mdn-url]> The recipient's name.
  - `order_number` <[string][string-mdn-url]> Unique order number.
  - `currency` <[string][string-mdn-url]> Currency of the payment.
  - `payment_method` <[string][string-mdn-url]> Custom string about which payment method and account a customer used, e.g. _Visa 1234_
  - `summary` <[Object][object-mdn-url]> Payment summary.
    - `total_cost` <[number][number-mdn-url]> Total cost of the order, including sub-total, shipping, and tax.
    - `subtotal` <[number][number-mdn-url]> Optional sub-total of the order.
    - `shipping_cost` <[number][number-mdn-url]> Optional shipping cost of the order.
    - `total_tax` <[number][number-mdn-url]> Optional tax of the order.
  - `sharable` <[boolean][boolean-mdn-url]> Optional native share button in Messenger for the the template message. Defaults to `false`.
  - `merchant_name` <[string][string-mdn-url]> Optional merchant's name. It is shown as logo text if this presents.
  - `timestamp` <[number][number-mdn-url]> Optional timestamp of the order in seconds.
  - `elements` <[Object][object-mdn-url]> Optional array of elements of the order. 100 elements limit. Order of the elements is not guaranteed.
    - `title` <[string][string-mdn-url]> Name of the item.
    - `price` <[number][number-mdn-url]> Price of the item. It is a free item when the value is `0`.
    - `subtitle` <[string][string-mdn-url]> Optional description of the item.
    - `quantity` <[number][number-mdn-url]> Optional quantity of the item.
    - `currency` <[string][string-mdn-url]> Optional currency of the item price.
    - `image_url` <[string][string-mdn-url]> Optional image URL of the item.
  - `address` <[Object][object-mdn-url]> Optional shipping address of the order.
    - `street_1` <[string][string-mdn-url]> Street address, line 1.
    - `city` <[string][string-mdn-url]> City name of the address.
    - `postal_code` <[string][string-mdn-url]> Postal code of the address.
    - `state` <[string][string-mdn-url]> State abbreviation for U.S. addresses, or the region/ province for non U.S. addresses.
    - `country` <[string][string-mdn-url]> 2-letter country code of the address.
    - `street_2` <[string][string-mdn-url]> Optional street address, line 2.
  - `adjustments` <[Object][object-mdn-url]> Optional array of payment adjustments, such as discounts.
    - `name` <[string][string-mdn-url]> Name of the adjustment.
    - `amount` <[number][number-mdn-url]> Amount of the adjustment.
- REGULAR: sound/ vibration. - SILENT_PUSH: on-screen notification only. - NO_PUSH: no notification.

Response

ErrorResponse

- message <stringstring-mdn-url> Error message. - type <stringstring-mdn-url> Error type. - code <numbernumber-mdn-url> Error code. - fbtrace_id <stringstring-mdn-url> Unique ID for tracing the error request.

sendAs(params)


The method throws an ErrorResponse
errorresponse-ref-url when the request is not a successful.

sendAsReadReceipt(params)


The method throws an ErrorResponseerrorresponse-ref-url when the request is not a successful.

sendAsTypingBubble(params)

sendAsText(params)


The method throws an ErrorResponseerrorresponse-ref-url when the request is not a successful.

sendAsQuickReply(params)


The method throws an ErrorResponseerrorresponse-ref-url when the request is not a successful.

sendAsButtonTemplate(params)


The method throws an ErrorResponseerrorresponse-ref-url when the request is not a successful.

sendAsGenericTemplate(params)


The method throws an ErrorResponseerrorresponse-ref-url when the request is not a successful.

sendAsReceiptTemplate(params)


The method throws an ErrorResponseerrorresponse-ref-url when the request is not a successful.

License

MIT License © Rong Sen Ng