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

@messageflow/send-as

v0.1.1

Published

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

Downloads

135

Readme

Version Node version MIT License

Downloads Total downloads Packagephobia Bundlephobia

Build Status CircleCI Dependency Status codecov Coverage Status

codebeat badge Codacy Badge Code of Conduct

Facebook Messenger Send API 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 payload | ✅ | | read receipt | ✅ | | typing bubble | ✅ | | text | ✅ | | quick_replies | ✅ | | button template | ✅ | | generic template | ✅ | | receipt template | ✅ |

Table of contents

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

  • id <string> PSID of the message recipient.

SendAsParams

  • url <string> URL to send message to.
  • recipient <Recipient> Description of the message recipient.
  • message <Object> Description of the message to be sent.
    • text <string> Message text. Must be UTF-8 and has a 2000 character limit. text or attachment must be set.
    • attachment <Object> Used to send messages with media or structured messages. text or attachment must be set.
    • quick_replies <Object> Optional array of quick_reply to be sent with messages.
    • metadata <string> Optional custom string that is delivered as a message echo. 1000 character limit.
  • notificationType <string> Optional push notification type.
    • REGULAR: sound/ vibration.
    • SILENT_PUSH: on-screen notification only.
    • NO_PUSH: no notification.
  • typingDelay <number> Optional typing delay in milliseconds. Defaults to 500.
  • options <Object> Optional request options. See node-fetch options for more details.

SendAsReadReceiptParams

SendAsTypingBubbleParams

  • url <string> URL to send message to.
  • recipient <Recipient> Description of the message recipient.
  • showTyping <boolean> If true, display typing bubble. Defaults to true.
  • options <Object> Optional request options. See node-fetch options for more details.

SendAsTextParams

  • url <string> URL to send message to.
  • recipient <Recipient> Description of the message recipient.
  • message <Object> Description of the message to be sent.
    • text <string> Message text. Must be UTF-8 and has a 2000 character limit.
  • notificationType <string> Optional push notification type.
    • REGULAR: sound/ vibration.
    • SILENT_PUSH: on-screen notification only.
    • NO_PUSH: no notification.
  • typingDelay <number> Optional typing delay in milliseconds. Defaults to 500.
  • options <Object> Optional request options. See node-fetch options for more details.

SendAsQuickReplyParams

  • url <string> URL to send message to.
  • recipient <Recipient> Description of the message recipient.
  • message <Object> Description of the message to be sent.
    • text <string> Non-empty message text to send with the quick replies. text or attachment must be set. 2000 character limit.
    • attachment <Object> Optional attachment to send with the quick replies. text or attachment must be set.
    • quick_replies <Array<quick_reply>> An array of objects the describe the quick reply buttons to send. A maximum of 11 quick replies are supported.
  • notificationType <string> Optional push notification type.
    • REGULAR: sound/ vibration.
    • SILENT_PUSH: on-screen notification only.
    • NO_PUSH: no notification.
  • typingDelay <number> Optional typing delay in milliseconds. Defaults to 500.
  • options <Object> Optional request options. See node-fetch options for more details.

SendAsButtonTemplateParams

  • url <string> URL to send message to.
  • recipient <Recipient> Description of the message recipient.
  • message <Object> Description of the message to be sent.
    • attachment <Object> An object describing attachments to the message.
      • type <string> Value must be template.
      • payload <Object> Payload of the template.
        • template_type <string> Value must be button.
        • text <string> Must be UTF-8 encoded text. 640 character limit.
        • buttons <Array<button>> An array of 1 - 3 buttons that appear as call-to-actions.
  • notificationType <string> Optional push notification type.
    • REGULAR: sound/ vibration.
    • SILENT_PUSH: on-screen notification only.
    • NO_PUSH: no notification.
  • typingDelay <number> Optional typing delay in milliseconds. Defaults to 500.
  • options <Object> Optional request options. See node-fetch options for more details.

SendAsGenericTemplateParams

  • url <string> URL to send message to.
  • recipient <Recipient> Description of the message recipient.
  • message <Object> Description of the message to be sent.
    • attachment <Object> An object describing attachments to the message.
      • type <string> Value must be template.
      • payload <Object> Payload of the template.
        • template_type <string> Value must be generic.
        • elements <Array<Object>> 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> Title of the template. 80 character limit.
          • subtitle <string> Optional subtitle of the template. 80 character limit.
          • image_url <string> Optional image URL of the template.
          • default_action <Object> Optional default action executed when the template is tapped. Has the same properties as URL button, except the title.
          • buttons <Array<button>> Optional array of buttons to append to the template. 3 buttons limit for each element.
        • sharable <boolean> Optional native share button in Messenger for the the template message. Defaults to false.
        • image_aspect_ratio <string> 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.
  • notificationType <string> Optional push notification type.
    • REGULAR: sound/ vibration.
    • SILENT_PUSH: on-screen notification only.
    • NO_PUSH: no notification.
  • typingDelay <number> Optional typing delay in milliseconds. Defaults to 500.
  • options <Object> Optional request options. See node-fetch options for more details.

SendAsReceiptTemplateParams

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

Response

  • recipient_id <string> Unique ID for the user which is usually the PSID.
  • message_id <string> Unique ID for the message.

ErrorResponse

  • error <Object> Error object when a request fails.
    • message <string> Error message.
    • type <string> Error type.
    • code <number> Error code.
    • fbtrace_id <string> Unique ID for tracing the error request.

sendAs(params)

  • params <SendAsParams> Parameters required to call the method.
  • returns: <Promise<Response>> Promise which resolves with a JSON object containing identifiers for the message and its recipient.

The method throws an ErrorResponse when the request is not a successful.

sendAsReadReceipt(params)

  • params <SendAsReadReceiptParams> Parameters required to call the method.
  • returns: <Promise<Response>> Promise which resolves with a JSON object containing identifiers for the message and its recipient.

The method throws an ErrorResponse when the request is not a successful.

sendAsTypingBubble(params)

sendAsText(params)

  • params <SendAsTextParams> Parameters required to call the method.
  • returns: <Promise<Response>> Promise which resolves with a JSON object containing identifiers for the message and its recipient.

The method throws an ErrorResponse when the request is not a successful.

sendAsQuickReply(params)

  • params <SendAsQuickReplyParams> Parameters required to call the method.
  • returns: <Promise<Response>> Promise which resolves with a JSON object containing identifiers for the message and its recipient.

The method throws an ErrorResponse when the request is not a successful.

sendAsButtonTemplate(params)

The method throws an ErrorResponse when the request is not a successful.

sendAsGenericTemplate(params)

The method throws an ErrorResponse when the request is not a successful.

sendAsReceiptTemplate(params)

The method throws an ErrorResponse when the request is not a successful.

License

MIT License © Rong Sen Ng