New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

messaging-api-messenger

Package Overview
Dependencies
Maintainers
3
Versions
112
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

messaging-api-messenger - npm Package Compare versions

Comparing version 0.7.0-alpha.2 to 0.7.0-beta.1

src/__tests__/MessengerClient-broadcast.spec.js

248

lib/MessengerBatch.js
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _extends = Object.assign || function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i];for (var key in source) {if (Object.prototype.hasOwnProperty.call(source, key)) {target[key] = source[key];}}}return target;};
/* eslint-disable camelcase */
var _Messenger = require('./Messenger');var _Messenger2 = _interopRequireDefault(_Messenger);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _objectWithoutProperties(obj, keys) {var target = {};for (var i in obj) {if (keys.indexOf(i) >= 0) continue;if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;target[i] = obj[i];}return target;}

@@ -11,2 +13,14 @@

function createRequest(body) {

@@ -22,3 +36,3 @@ return {

idOrRecipient,
message,
msg,
options = {})

@@ -38,6 +52,7 @@ {

}
return createRequest(_extends({
messaging_type: messageType,
recipient,
message },
message: _Messenger2.default.createMessage(msg, options) },
options));

@@ -52,11 +67,236 @@

{
return createMessage(recipient, { text }, options);
return createMessage(recipient, _Messenger2.default.createText(text, options), options);
}
function createAttachment(
recipient,
attachment,
options)
{
return createMessage(
recipient,
_Messenger2.default.createAttachment(attachment, options),
options);
}
function createAudio(
recipient,
audio,
options)
{
return createMessage(
recipient,
_Messenger2.default.createAudio(audio, options),
options);
}
function createImage(
recipient,
image,
options)
{
return createMessage(
recipient,
_Messenger2.default.createImage(image, options),
options);
}
function createVideo(
recipient,
video,
options)
{
return createMessage(
recipient,
_Messenger2.default.createVideo(video, options),
options);
}
function createFile(
recipient,
file,
options)
{
return createMessage(recipient, _Messenger2.default.createFile(file, options), options);
}
function createTemplate(
recipient,
payload,
options)
{
return createMessage(
recipient,
_Messenger2.default.createTemplate(payload, options),
options);
}
function createButtonTemplate(
recipient,
text,
buttons,
options)
{
return createMessage(
recipient,
_Messenger2.default.createButtonTemplate(text, buttons, options),
options);
}
function createGenericTemplate(
recipient,
elements,
_ref =
{})
{var _ref$image_aspect_rat = _ref.image_aspect_ratio;let image_aspect_ratio = _ref$image_aspect_rat === undefined ? 'horizontal' : _ref$image_aspect_rat,options = _objectWithoutProperties(_ref, ['image_aspect_ratio']);
return createMessage(
recipient,
_Messenger2.default.createGenericTemplate(elements, _extends({},
options, {
image_aspect_ratio })),
options);
}
function createListTemplate(
recipient,
elements,
buttons,
_ref2 =
{})
{var _ref2$top_element_sty = _ref2.top_element_style;let top_element_style = _ref2$top_element_sty === undefined ? 'large' : _ref2$top_element_sty,options = _objectWithoutProperties(_ref2, ['top_element_style']);
return createMessage(
recipient,
_Messenger2.default.createListTemplate(elements, buttons, _extends({},
options, {
top_element_style })),
options);
}
function createOpenGraphTemplate(
recipient,
elements,
options)
{
return createMessage(
recipient,
_Messenger2.default.createOpenGraphTemplate(elements, options),
options);
}
function createReceiptTemplate(
recipient,
attrs,
options)
{
return createMessage(
recipient,
_Messenger2.default.createReceiptTemplate(attrs, options),
options);
}
function createMediaTemplate(
recipient,
elements,
options)
{
return createMessage(
recipient,
_Messenger2.default.createMediaTemplate(elements, options),
options);
}
function createAirlineBoardingPassTemplate(
recipient,
attrs,
options)
{
return createMessage(
recipient,
_Messenger2.default.createAirlineBoardingPassTemplate(attrs, options),
options);
}
function createAirlineCheckinTemplate(
recipient,
attrs,
options)
{
return createMessage(
recipient,
_Messenger2.default.createAirlineCheckinTemplate(attrs, options),
options);
}
function createAirlineItineraryTemplate(
recipient,
attrs,
options)
{
return createMessage(
recipient,
_Messenger2.default.createAirlineItineraryTemplate(attrs, options),
options);
}
function createAirlineFlightUpdateTemplate(
recipient,
attrs,
options)
{
return createMessage(
recipient,
_Messenger2.default.createAirlineFlightUpdateTemplate(attrs, options),
options);
}
const MessengerBatch = {
createRequest,
createMessage,
createText };exports.default =
createText,
createAttachment,
createAudio,
createImage,
createVideo,
createFile,
createTemplate,
createButtonTemplate,
createGenericTemplate,
createListTemplate,
createOpenGraphTemplate,
createReceiptTemplate,
createMediaTemplate,
createAirlineBoardingPassTemplate,
createAirlineCheckinTemplate,
createAirlineItineraryTemplate,
createAirlineFlightUpdateTemplate };exports.default =
MessengerBatch;

2306

lib/MessengerClient.js

@@ -13,3 +13,2 @@ 'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _extends = Object.assign || function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i];for (var key in source) {if (Object.prototype.hasOwnProperty.call(source, key)) {target[key] = source[key];}}}return target;};

var _isPlainObject = require('is-plain-object');var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _warning = require('warning');var _warning2 = _interopRequireDefault(_warning);

@@ -62,4 +61,2 @@ var _Messenger = require('./Messenger');var _Messenger2 = _interopRequireDefault(_Messenger);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _objectWithoutProperties(obj, keys) {var target = {};for (var i in obj) {if (keys.indexOf(i) >= 0) continue;if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;target[i] = obj[i];}return target;} /* eslint-disable camelcase */

function extractVersion(version) {

@@ -72,33 +69,21 @@ if (version.startsWith('v')) {

function validateQuickReplies(quickReplies) {
// quick_replies is limited to 11
(0, _invariant2.default)(
Array.isArray(quickReplies) && quickReplies.length <= 11,
'quick_replies is an array and limited to 11');
function handleError(err) {const
error = err.response.data.error;
const msg = `Messenger API - ${error.code} ${error.type} ${error.message}`;
throw new _axiosError2.default(msg, err);
}
quickReplies.forEach(quickReply => {
if (quickReply.content_type === 'text') {
// title has a 20 character limit, after that it gets truncated
(0, _invariant2.default)(
quickReply.title.trim().length <= 20,
'title of quick reply has a 20 character limit, after that it gets truncated');
// payload has a 1000 character limit
(0, _invariant2.default)(
quickReply.payload.length <= 1000,
'payload of quick reply has a 1000 character limit');
}
});
}
function handleError(err) {const
error = err.response.data.error;
const msg = `Messenger API - ${error.code} ${error.type} ${error.message}`;
throw new _axiosError2.default(msg, err);
}
class MessengerClient {
static connect(
accessTokenOrConfig,
version = '2.11')
{
return new MessengerClient(accessTokenOrConfig, version);
}

@@ -109,12 +94,28 @@

constructor(
accessTokenOrConfig,
version = '2.11')
{
let origin;
if (accessTokenOrConfig && typeof accessTokenOrConfig === 'object') {
const config = accessTokenOrConfig;
this._accessToken = config.accessToken;
(0, _invariant2.default)(
!config.version || typeof config.version === 'string',
'Type of `version` must be string.');
this._version = extractVersion(config.version || '2.11');
origin = config.origin;
} else {
this._accessToken = accessTokenOrConfig;
(0, _invariant2.default)(
typeof version === 'string',
'Type of `version` must be string.');
this._version = extractVersion(version);
}
constructor(accessToken, version = '2.11') {_initialiseProps.call(this);
this._accessToken = accessToken;
(0, _invariant2.default)(typeof version === 'string', 'Type of `version` must be string.');
this._version = extractVersion(version);
this._axios = _axios2.default.create({
baseURL: `https://graph.facebook.com/v${this._version}/`,
baseURL: `${origin || 'https://graph.facebook.com'}/v${this._version}/`,
headers: { 'Content-Type': 'application/json' } });

@@ -142,15 +143,30 @@

*/
getPageInfo({
access_token: customAccessToken } =
{}) {
return this._axios.
get(`/me?access_token=${customAccessToken || this._accessToken}`).
then(res => res.data, handleError);
}
/**
* Create Subscription
*
* https://developers.facebook.com/docs/graph-api/reference/app/subscriptions
*/
* Create Subscription
*
* https://developers.facebook.com/docs/graph-api/reference/app/subscriptions
*/
createSubscription({
app_id: appId,
object = 'page',
callback_url,
fields = [
'messages',
'messaging_postbacks',
'messaging_optins',
'messaging_referrals',
'messaging_handovers',
'messaging_policy_enforcement'],
include_values,
verify_token,
access_token: appAccessToken })

@@ -164,123 +180,124 @@

{
return this._axios.
post(`/${appId}/subscriptions?access_token=${appAccessToken}`, {
object,
callback_url,
fields: fields.join(','),
include_values,
verify_token }).
then(res => res.data, handleError);
}
/**
* Get User Profile
*
* https://www.quora.com/How-connect-Facebook-user-id-to-sender-id-in-the-Facebook-messenger-platform
* first_name, last_name, profile_pic, locale, timezone, gender
*/
* Get User Profile
*
* https://www.quora.com/How-connect-Facebook-user-id-to-sender-id-in-the-Facebook-messenger-platform
* first_name, last_name, profile_pic, locale, timezone, gender
*/
getUserProfile(
userId,
{ access_token: customAccessToken } = {})
{
return this._axios.
get(`/${userId}?access_token=${customAccessToken || this._accessToken}`).
then(res => res.data, handleError);
}
/**
* Messenger Profile
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api
*/
* Messenger Profile
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api
*/
getMessengerProfile(
fields,
{ access_token: customAccessToken } = {})
{
return this._axios.
get(
`/me/messenger_profile?fields=${fields.join(
',')
}&access_token=${customAccessToken || this._accessToken}`).
then(res => res.data.data, handleError);
}
setMessengerProfile(
profile,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/me/messenger_profile?access_token=${customAccessToken ||
this._accessToken}`,
profile).
then(res => res.data, handleError);
}
deleteMessengerProfile(
fields,
{ access_token: customAccessToken } = {})
{
return this._axios.
delete(
`/me/messenger_profile?access_token=${customAccessToken ||
this._accessToken}`,
{
data: {
fields } }).
then(res => res.data, handleError);
}
/**
* Get Started Button
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/get-started-button
*/
* Get Started Button
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/get-started-button
*/
getGetStarted(
options = {})
{
return this.getMessengerProfile(['get_started'], options).then(
res => res[0] ? res[0].get_started : null);
}
setGetStarted(
payload,
options = {})
{
return this.setMessengerProfile(
{
get_started: {
payload } },
options);
}
deleteGetStarted(options = {}) {
return this.deleteMessengerProfile(['get_started'], options);
}
/**
* Persistent Menu
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/persistent-menu
*/
* Persistent Menu
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/persistent-menu
*/
getPersistentMenu(
options = {})
{
return this.getMessengerProfile(['persistent_menu'], options).then(
res => res[0] ? res[0].persistent_menu : null);
}
setPersistentMenu(
menuItems,
_ref =

@@ -291,238 +308,254 @@

{})
{var _ref$composer_input_d = _ref.composer_input_disabled;let composerInputDisabled = _ref$composer_input_d === undefined ? false : _ref$composer_input_d,options = _objectWithoutProperties(_ref, ['composer_input_disabled']);
// menuItems is in type PersistentMenu
if (menuItems.some(item => item.locale === 'default')) {
return this.setMessengerProfile(
{
persistent_menu: menuItems },
options);
}
// menuItems is in type Array<MenuItem>
return this.setMessengerProfile(
{
persistent_menu: [
{
locale: 'default',
composer_input_disabled: composerInputDisabled,
call_to_actions: menuItems }] },
options);
}
deletePersistentMenu(
options = {})
{
return this.deleteMessengerProfile(['persistent_menu'], options);
}
/**
* Greeting Text
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/greeting
*/
* Greeting Text
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/greeting
*/
getGreeting(options = {}) {
return this.getMessengerProfile(['greeting'], options).then(
res => res[0] ? res[0].greeting : null);
}
setGreeting(
greeting,
options = {})
{
if (typeof greeting === 'string') {
return this.setMessengerProfile(
{
greeting: [
{
locale: 'default',
text: greeting }] },
options);
}
return this.setMessengerProfile(
{
greeting },
options);
}
deleteGreeting(options = {}) {
return this.deleteMessengerProfile(['greeting'], options);
}
/**
* Whitelisted Domains
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/domain-whitelisting
*/
* Whitelisted Domains
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/domain-whitelisting
*/
getWhitelistedDomains(
options = {})
{
return this.getMessengerProfile(['whitelisted_domains'], options).then(
res => res[0] ? res[0].whitelisted_domains : null);
}
setWhitelistedDomains(
domains,
options = {})
{
return this.setMessengerProfile(
{
whitelisted_domains: domains },
options);
}
deleteWhitelistedDomains(
options = {})
{
return this.deleteMessengerProfile(['whitelisted_domains'], options);
}
/**
* Account Linking URL
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/account-linking-url
*/
* Account Linking URL
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/account-linking-url
*/
getAccountLinkingURL(
options = {})
{
return this.getMessengerProfile(['account_linking_url'], options).then(
res => res[0] ? res[0] : null);
}
setAccountLinkingURL(
url,
options = {})
{
return this.setMessengerProfile(
{
account_linking_url: url },
options);
}
deleteAccountLinkingURL(
options = {})
{
return this.deleteMessengerProfile(['account_linking_url'], options);
}
/**
* Payment Settings
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/payment-settings
*/
* Payment Settings
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/payment-settings
*/
getPaymentSettings(
options = {})
{
return this.getMessengerProfile(['payment_settings'], options).then(
res => res[0] ? res[0] : null);
}
setPaymentPrivacyPolicyURL(
url,
options = {})
{
return this.setMessengerProfile(
{
payment_settings: {
privacy_url: url } },
options);
}
setPaymentPublicKey(
key,
options = {})
{
return this.setMessengerProfile(
{
payment_settings: {
public_key: key } },
options);
}
setPaymentTestUsers(
users,
options = {})
{
return this.setMessengerProfile(
{
payment_settings: {
test_users: users } },
options);
}
deletePaymentSettings(
options = {})
{
return this.deleteMessengerProfile(['payment_settings'], options);
}
/**
* Target Audience
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/target-audience
*/
* Target Audience
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/target-audience
*/
getTargetAudience(
options = {})
{
return this.getMessengerProfile(['target_audience'], options).then(
res => res[0] ? res[0] : null);
}
setTargetAudience(
type,
whitelist = [],
blacklist = [],
options = {})
{
return this.setMessengerProfile(
{
target_audience: {
audience_type: type,
countries: {
whitelist,
blacklist } } },
options);
}
deleteTargetAudience(
options = {})
{
return this.deleteMessengerProfile(['target_audience'], options);
}
/**
* Chat Extension Home URL
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/home-url
*/
* Chat Extension Home URL
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/home-url
*/
getHomeURL(options = {}) {
return this.getMessengerProfile(['home_url'], options).then(
res => res[0] ? res[0] : null);
}
setHomeURL(
url,
{
webview_share_button,
in_test },

@@ -532,232 +565,241 @@

options = {})
{
return this.setMessengerProfile(
{
home_url: {
url,
webview_height_ratio: 'tall',
in_test,
webview_share_button } },
options);
}
deleteHomeURL(options = {}) {
return this.deleteMessengerProfile(['home_url'], options);
}
/**
* Message tags
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/message-tags
*/
* Message tags
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/message-tags
*/
getMessageTags({
access_token: customAccessToken } =
{}) {
return this._axios.
get(
`/page_message_tags?access_token=${customAccessToken ||
this._accessToken}`).
then(res => res.data.data, handleError);
}
/**
* Send API
*
* https://developers.facebook.com/docs/messenger-platform/reference/send-api
*/
* Send API
*
* https://developers.facebook.com/docs/messenger-platform/reference/send-api
*/
// TODO: body flowtype
sendRawBody(body) {const
customAccessToken = body.access_token;
return this._axios.
post(
`/me/messages?access_token=${customAccessToken || this._accessToken}`,
body).
then(res => res.data, handleError);
}
sendMessage(
idOrRecipient,
message,
options = {})
{
const recipient =
typeof idOrRecipient === 'string' ?
{
id: idOrRecipient } :
idOrRecipient;
let messageType = 'UPDATE';
if (options.messaging_type) {
messageType = options.messaging_type;
} else if (options.tag) {
messageType = 'MESSAGE_TAG';
}
return this.sendRawBody(_extends({
messaging_type: messageType,
recipient,
message: _Messenger2.default.createMessage(message, options) },
(0, _lodash2.default)(options, 'quick_replies')));
}
sendMessageFormData(
recipient,
formdata,
options = {})
{
const recipientObject =
typeof recipient === 'string' ?
{
id: recipient } :
recipient;
let messageType = 'UPDATE';
if (options.messaging_type) {
messageType = options.messaging_type;
} else if (options.tag) {
messageType = 'MESSAGE_TAG';
}
formdata.append('messaging_type', messageType);
formdata.append('recipient', JSON.stringify(recipientObject));
return this._axios.
post(
`/me/messages?access_token=${options.access_token ||
this._accessToken}`,
formdata,
{
headers: formdata.getHeaders() }).
then(res => res.data, handleError);
}
/**
* Content Types
*
* https://developers.facebook.com/docs/messenger-platform/send-messages#content_types
*/
* Content Types
*
* https://developers.facebook.com/docs/messenger-platform/send-messages#content_types
*/
sendAttachment(
recipient,
attachment,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createAttachment(attachment, options),
options);
}
sendText(
recipient,
text,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createText(text, options),
options);
}
sendAudio(
recipient,
audio,
options)
{
const message = _Messenger2.default.createAudio(audio, options);
if (message && (0, _isPlainObject2.default)(message)) {
return this.sendMessage(recipient, message, options);
}
// $FlowFixMe
return this.sendMessageFormData(recipient, message, options);
}
sendImage(
recipient,
image,
options)
{
const message = _Messenger2.default.createImage(image, options);
if (message && (0, _isPlainObject2.default)(message)) {
return this.sendMessage(recipient, message, options);
}
// $FlowFixMe
return this.sendMessageFormData(recipient, message, options);
}
sendVideo(
recipient,
video,
options)
{
const message = _Messenger2.default.createVideo(video, options);
if (message && (0, _isPlainObject2.default)(message)) {
return this.sendMessage(recipient, message, options);
}
// $FlowFixMe
return this.sendMessageFormData(recipient, message, options);
}
sendFile(
recipient,
file,
options)
{
const message = _Messenger2.default.createFile(file, options);
if (message && (0, _isPlainObject2.default)(message)) {
return this.sendMessage(recipient, message, options);
}
// $FlowFixMe
return this.sendMessageFormData(recipient, message, options);
}
/**
* Message Templates
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/templates
*/
* Message Templates
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/templates
*/
sendTemplate(
recipient,
payload,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createTemplate(payload, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/button
sendButtonTemplate(
recipient,
text,
buttons,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createButtonTemplate(text, buttons, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/generic
sendGenericTemplate(
recipient,
elements,
_ref2 =

@@ -769,17 +811,20 @@

{})
{var _ref2$image_aspect_ra = _ref2.image_aspect_ratio;let image_aspect_ratio = _ref2$image_aspect_ra === undefined ? 'horizontal' : _ref2$image_aspect_ra,options = _objectWithoutProperties(_ref2, ['image_aspect_ratio']);
return this.sendMessage(
recipient,
_Messenger2.default.createGenericTemplate(elements, _extends({},
options, {
image_aspect_ratio })),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/list
sendListTemplate(
recipient,
elements,
buttons,
_ref3 =

@@ -791,450 +836,456 @@

{})
{var _ref3$top_element_sty = _ref3.top_element_style;let top_element_style = _ref3$top_element_sty === undefined ? 'large' : _ref3$top_element_sty,options = _objectWithoutProperties(_ref3, ['top_element_style']);
return this.sendMessage(
recipient,
_Messenger2.default.createListTemplate(elements, buttons, _extends({},
options, {
top_element_style })),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/open-graph
sendOpenGraphTemplate(
recipient,
elements,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createOpenGraphTemplate(elements, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/receipt
sendReceiptTemplate(
recipient,
attrs,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createReceiptTemplate(attrs, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/media
sendMediaTemplate(
recipient,
elements,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createMediaTemplate(elements, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#boarding_pass
sendAirlineBoardingPassTemplate(
recipient,
attrs,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createAirlineBoardingPassTemplate(attrs, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#check_in
sendAirlineCheckinTemplate(
recipient,
attrs,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createAirlineCheckinTemplate(attrs, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#itinerary
sendAirlineItineraryTemplate(
recipient,
attrs,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createAirlineItineraryTemplate(attrs, options),
options);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#update
sendAirlineFlightUpdateTemplate(
recipient,
attrs,
options)
{
return this.sendMessage(
recipient,
_Messenger2.default.createAirlineFlightUpdateTemplate(attrs, options),
options);
}
/**
* Quick Replies
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies
*/
* Typing
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/sender-actions
*/
sendSenderAction(
idOrRecipient,
action,
{ access_token: customAccessToken } = {})
{
const recipient =
typeof idOrRecipient === 'string' ?
{
id: idOrRecipient } :
idOrRecipient;
return this.sendRawBody({
recipient,
sender_action: action,
access_token: customAccessToken });
}
markSeen(
recipient,
options = {})
{
return this.sendSenderAction(recipient, 'mark_seen', options);
}
typingOn(
recipient,
options = {})
{
return this.sendSenderAction(recipient, 'typing_on', options);
}
typingOff(
recipient,
options = {})
{
return this.sendSenderAction(recipient, 'typing_off', options);
}
/**
* Typing
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/sender-actions
*/
* Send Batch Request
*
* https://developers.facebook.com/docs/graph-api/making-multiple-requests
*/
sendBatch(
batch,
{ access_token: customAccessToken } = {})
{
(0, _invariant2.default)(
batch.length <= 50,
'limit the number of requests which can be in a batch to 50');
const bodyEncodedbatch = batch.map(item => {
if (item.body) {
return _extends({},
item, {
body: Object.keys(item.body).
map(key => {
// $FlowFixMe item.body should not possible as undefined.
const val = item.body[key];
return `${encodeURIComponent(key)}=${encodeURIComponent(
typeof val === 'object' ? JSON.stringify(val) : val)
}`;
}).
join('&') });
}
return item;
});
return this._axios.
post('/', {
access_token: customAccessToken || this._accessToken,
batch: bodyEncodedbatch }).
then(res => res.data, handleError);
}
/**
* Send Batch Request
*
* https://developers.facebook.com/docs/graph-api/making-multiple-requests
*/
* Broadcast API
*
* https://developers.facebook.com/docs/messenger-platform/reference/broadcast-api
*/
/**
* Broadcast API
*
* https://developers.facebook.com/docs/messenger-platform/reference/broadcast-api
*/
* Create Message Creative
*
* https://developers.facebook.com/docs/messenger-platform/reference/sponsored-messages#creative
*/
createMessageCreative(
messages = [],
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/me/message_creatives?access_token=${customAccessToken ||
this._accessToken}`,
{
messages }).
/**
* Create Message Creative
*
* https://developers.facebook.com/docs/messenger-platform/reference/sponsored-messages#creative
*/
then(res => res.data, handleError);
}
/**
* Send Broadcast Message
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages#sending
*/
* Send Broadcast Message
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages#sending
*/
sendBroadcastMessage(messageCreativeId, options = {}) {
return this._axios.
post(
`/me/broadcast_messages?access_token=${options.access_token ||
this._accessToken}`, _extends({
message_creative_id: messageCreativeId },
options)).
then(res => res.data, handleError);
}
/**
* Send Sponsored Message
*
* https://developers.facebook.com/docs/messenger-platform/reference/sponsored-messages#message
*/
* Send Sponsored Message
*
* https://developers.facebook.com/docs/messenger-platform/reference/sponsored-messages#message
*/
sendSponsoredMessage(adAccountId, message) {
return this._axios.
post(
`/act_${adAccountId}/sponsored_message_ads?access_token=${
this._accessToken
}`,
message).
then(res => res.data, handleError);
}
/**
* Label API
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts
*/
* Label API
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts
*/
/**
* Create Label
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#create_label
*/
* Create Label
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#create_label
*/
createLabel(
name,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/me/custom_labels?access_token=${customAccessToken ||
this._accessToken}`,
{
name }).
then(res => res.data, handleError);
}
/**
* Associating a Label to a PSID
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#associate_label
*/
* Associating a Label to a PSID
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#associate_label
*/
associateLabel(
userId,
labelId,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/${labelId}/label?access_token=${customAccessToken ||
this._accessToken}`,
{
user: userId }).
then(res => res.data, handleError);
}
/**
* Removing a Label From a PSID
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#associate_label
*/
* Removing a Label From a PSID
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#associate_label
*/
dissociateLabel(
userId,
labelId,
{ access_token: customAccessToken } = {})
{
return this._axios.
delete(
`/${labelId}/label?access_token=${customAccessToken ||
this._accessToken}`,
{
data: { user: userId } }).
then(res => res.data, handleError);
}
/**
* Retrieving Labels Associated with a PSID
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#get_all_labels
*/
* Retrieving Labels Associated with a PSID
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#get_all_labels
*/
getAssociatedLabels(
userId,
{ access_token: customAccessToken } = {})
{
return this._axios.
get(
`/${userId}/custom_labels?access_token=${customAccessToken ||
this._accessToken}`).
then(res => res.data, handleError);
}
/**
* Retrieving Label Details
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#get_label_details
*/
* Retrieving Label Details
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#get_label_details
*/
getLabelDetails(labelId, options = {}) {
const fields = options.fields ? options.fields.join(',') : 'name';
return this._axios.
get(
`/${labelId}?fields=${fields}&access_token=${options.access_token ||
this._accessToken}`).
then(res => res.data, handleError);
}
/**
* Retrieving a List of All Labels
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#get_all_labels
*/
* Retrieving a List of All Labels
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#get_all_labels
*/
getLabelList(options = {}) {
const fields = options.fields ? options.fields.join(',') : 'name';
return this._axios.
get(
`/me/custom_labels?fields=${fields}&access_token=${options.access_token ||
this._accessToken}`).
then(res => res.data, handleError);
}
/**
* Deleting a Label
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#delete_label
*/
* Deleting a Label
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/target-broadcasts#delete_label
*/
deleteLabel(
labelId,
{ access_token: customAccessToken } = {})
{
return this._axios.
delete(
`/${labelId}?access_token=${customAccessToken || this._accessToken}`).
then(res => res.data, handleError);
}
/**
* Starting a Reach Estimation
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/estimate-reach#start
*/
* Starting a Reach Estimation
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/estimate-reach#start
*/
startReachEstimation(
customLabelId,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/me/broadcast_reach_estimations?access_token=${customAccessToken ||
this._accessToken}`,
{
custom_label_id: customLabelId }).
then(res => res.data, handleError);
}
/**
* Retrieving a Reach Estimate
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/estimate-reach#get
*/
* Retrieving a Reach Estimate
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/estimate-reach#get
*/
getReachEstimate(
reachEstimationId,
{ access_token: customAccessToken } = {})
{
return this._axios.
get(
`/${reachEstimationId}?access_token=${customAccessToken ||
this._accessToken}`).
then(res => res.data, handleError);
}
/**
* Broadcast Metrics
*
* Once a broadcast has been delivered, you can find out the total number of people it reached.
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/#metrics
*/
* Broadcast Metrics
*
* Once a broadcast has been delivered, you can find out the total number of people it reached.
* https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages/#metrics
*/
getBroadcastMessagesSent(
broadcastId,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/${broadcastId}/insights/messages_sent?access_token=${customAccessToken ||
this._accessToken}`).
then(res => res.data.data, handleError);
}
/**
* Upload API
*
* https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api
*/
* Upload API
*
* https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api
*/
uploadAttachment(
type,
attachment,
options = {})
{
const args = [];
const isReusable = options.is_reusable || false;
if (typeof attachment === 'string') {
args.push({
message: {
attachment: {
type,
payload: {
url: attachment,
is_reusable: isReusable } } } });

@@ -1244,3 +1295,12 @@

} else {
const form = new _formData2.default();
form.append(
'message',
JSON.stringify({
attachment: {
type,
payload: {
is_reusable: isReusable } } }));

@@ -1251,183 +1311,246 @@

form.append('filedata', attachment, (0, _lodash2.default)(options, ['is_reusable']));
args.push(form, {
headers: form.getHeaders() });
}
return this._axios.
post(
`/me/message_attachments?access_token=${options.access_token ||
this._accessToken}`,
...args).
then(res => res.data, handleError);
}
uploadAudio(attachment, options) {
return this.uploadAttachment('audio', attachment, options);
}
uploadImage(attachment, options) {
return this.uploadAttachment('image', attachment, options);
}
uploadVideo(attachment, options) {
return this.uploadAttachment('video', attachment, options);
}
uploadFile(attachment, options) {
return this.uploadAttachment('file', attachment, options);
}
/**
* Messenger Code API
*
* https://developers.facebook.com/docs/messenger-platform/discovery/messenger-codes
*/
* Messenger Code API
*
* https://developers.facebook.com/docs/messenger-platform/discovery/messenger-codes
*/
generateMessengerCode(options = {}) {
return this._axios.
post(
`/me/messenger_codes?access_token=${options.access_token ||
this._accessToken}`, _extends({
type: 'standard' },
options)).
then(res => res.data, handleError);
}
/**
* Handover Protocol API
*
* https://developers.facebook.com/docs/messenger-platform/handover-protocol
*/
* Handover Protocol API
*
* https://developers.facebook.com/docs/messenger-platform/handover-protocol
*/
/**
* Pass Thread Control
*
* https://developers.facebook.com/docs/messenger-platform/reference/handover-protocol/pass-thread-control
*/
* Pass Thread Control
*
* https://developers.facebook.com/docs/messenger-platform/reference/handover-protocol/pass-thread-control
*/
passThreadControl(
recipientId,
targetAppId,
metadata,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/me/pass_thread_control?access_token=${customAccessToken ||
this._accessToken}`,
{
recipient: { id: recipientId },
target_app_id: targetAppId,
metadata }).
then(res => res.data, handleError);
}
passThreadControlToPageInbox(
recipientId,
metadata,
options = {})
{
return this.passThreadControl(
recipientId,
263902037430900,
metadata,
options);
}
/**
* Take Thread Control
*
* https://developers.facebook.com/docs/messenger-platform/reference/handover-protocol/take-thread-control
*/
takeThreadControl(
recipientId,
metadata,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/me/take_thread_control?access_token=${customAccessToken ||
this._accessToken}`,
{
recipient: { id: recipientId },
metadata }).
then(res => res.data, handleError);
}
/**
* Request Thread Control
*
* https://developers.facebook.com/docs/messenger-platform/handover-protocol/request-thread-control/
*/
requestThreadControl(
recipientId,
metadata,
{ access_token: customAccessToken } = {})
{
return this._axios.
post(
`/me/request_thread_control?access_token=${customAccessToken ||
this._accessToken}`,
{
recipient: { id: recipientId },
metadata }).
then(res => res.data, handleError);
}
/**
* Take Thread Control
*
* https://developers.facebook.com/docs/messenger-platform/reference/handover-protocol/take-thread-control
*/
* Secondary Receivers List
*
* https://developers.facebook.com/docs/messenger-platform/reference/handover-protocol/secondary-receivers
*/
getSecondaryReceivers({
access_token: customAccessToken } =
{}) {
return this._axios.
get(
`/me/secondary_receivers?fields=id,name&access_token=${customAccessToken ||
this._accessToken}`).
then(res => res.data.data, handleError);
}
/**
* Secondary Receivers List
*
* https://developers.facebook.com/docs/messenger-platform/reference/handover-protocol/secondary-receivers
*/
* Page Messaging Insights API
*
* https://developers.facebook.com/docs/messenger-platform/reference/messaging-insights-api
*/
getInsights(metrics, options = {}) {
return this._axios.
get(
`/me/insights/?${_querystring2.default.stringify(_extends({
metric: metrics.join(','),
access_token: options.access_token || this._accessToken },
options))
}`).
then(res => res.data.data, handleError);
}
getActiveThreads(options = {}) {
return this.getInsights(
['page_messages_active_threads_unique'],
options).
then(result => result[0]);
}
getBlockedConversations(options = {}) {
return this.getInsights(
['page_messages_blocked_conversations_unique'],
options).
then(result => result[0]);
}
getReportedConversations(options = {}) {
return this.getInsights(
['page_messages_reported_conversations_unique'],
options).
then(result => result[0]);
}
getReportedConversationsByReportType(options = {}) {
return this.getInsights(
['page_messages_reported_conversations_by_report_type_unique'],
options).
then(result => result[0]);
}
getOpenConversations(options = {}) {
return this.getInsights(
['page_messages_open_conversations_unique'],
options).
then(result => result[0]);
}
getNewConversations(options = {}) {
return this.getInsights(
['page_messages_new_conversations_unique'],
options).
then(result => result[0]);
}
/**
* Page Messaging Insights API
*
* https://developers.facebook.com/docs/messenger-platform/reference/messaging-insights-api
*/
* Built-in NLP API
*
* https://developers.facebook.com/docs/messenger-platform/built-in-nlp
*/
setNLPConfigs(
config = {},
{ access_token: customAccessToken } = {})
{
return this._axios.
post(`/me/nlp_configs?${_querystring2.default.stringify(config)}`, {
access_token: customAccessToken || this._accessToken }).
then(res => res.data, handleError);
}
enableNLP(options = {}) {
return this.setNLPConfigs({ nlp_enabled: true }, options);
}
disableNLP(options = {}) {
return this.setNLPConfigs({ nlp_enabled: false }, options);
}
/**
* Built-in NLP API
*
* https://developers.facebook.com/docs/messenger-platform/built-in-nlp
*/
* Logging Custom Events
*
* https://developers.facebook.com/docs/app-events/bots-for-messenger#logging-custom-events
*/
logCustomEvents({
app_id,
page_id,
page_scoped_user_id,
events,
access_token: customAccessToken })

@@ -1439,16 +1562,30 @@

{
return this._axios.
post(
`/${app_id}/activities?access_token=${customAccessToken ||
this._accessToken}`,
{
event: 'CUSTOM_APP_EVENTS',
custom_events: JSON.stringify(events),
advertiser_tracking_enabled: 0,
application_tracking_enabled: 0,
extinfo: JSON.stringify(['mb1']),
page_id,
page_scoped_user_id }).
then(res => res.data, handleError);
}
/**
* Logging Custom Events
*
* https://developers.facebook.com/docs/app-events/bots-for-messenger#logging-custom-events
*/
* https://developers.facebook.com/docs/messenger-platform/identity/id-matching#examples
*/
getUserField({
field,
user_id,
app_secret,
app,
page,
access_token: customAccessToken })

@@ -1461,48 +1598,30 @@

{
const accessToken = customAccessToken || this._accessToken;
// $appsecret_proof= hash_hmac('sha256', $access_token, $app_secret);
const appsecretProof = _crypto2.default.
createHmac('sha256', app_secret).
update(accessToken).
digest('hex');
const appQueryString = app ? `&app=${app}` : '';
const pageQueryString = page ? `&page=${page}` : '';
return this._axios.
get(
`/${user_id}/${field}?access_token=${accessToken}&appsecret_proof=${appsecretProof}${appQueryString}${pageQueryString}`).
then(res => res.data, handleError);
}
/**
* https://developers.facebook.com/docs/messenger-platform/identity/id-matching#examples
*/
* Given a user ID for a bot in Messenger, retrieve the IDs for apps owned by the same business
*/
getIdsForApps({
user_id,
app_secret,
app,
page,
access_token })

@@ -1514,32 +1633,22 @@

{
return this.getUserField({
field: 'ids_for_apps',
user_id,
app_secret,
app,
page,
access_token });
}
/**
* Given a user ID for a bot in Messenger, retrieve the IDs for apps owned by the same business
*/
* Given a user ID for a Page (associated with a bot), retrieve the IDs for other Pages owned by the same business
*/
getIdsForPages({
user_id,
app_secret,
app,
page,
access_token })

@@ -1551,40 +1660,11 @@

{
return this.getUserField({
field: 'ids_for_pages',
user_id,
app_secret,
app,
page,
access_token });
/**
* Given a user ID for a Page (associated with a bot), retrieve the IDs for other Pages owned by the same business
*/}exports.default = MessengerClient;MessengerClient.connect = (accessToken, version = '2.11') => new MessengerClient(accessToken, version);var _initialiseProps = function _initialiseProps() {this.getPageInfo = ({ access_token: customAccessToken } = {}) => this._axios.get(`/me?access_token=${customAccessToken || this._accessToken}`).then(res => res.data, handleError);this.createSubscription = ({ app_id: appId, object = 'page', callback_url, fields = ['messages', 'messaging_postbacks', 'messaging_optins', 'messaging_referrals', 'messaging_handovers', 'messaging_policy_enforcement'], include_values, verify_token, access_token: appAccessToken }) => this._axios.post(`/${appId}/subscriptions?access_token=${appAccessToken}`, { object, callback_url, fields: fields.join(','), include_values, verify_token }).then(res => res.data, handleError);this.getUserProfile = (userId, { access_token: customAccessToken } = {}) => this._axios.get(`/${userId}?access_token=${customAccessToken || this._accessToken}`).then(res => res.data, handleError);this.getMessengerProfile = (fields, { access_token: customAccessToken } = {}) => this._axios.get(`/me/messenger_profile?fields=${fields.join(',')}&access_token=${customAccessToken || this._accessToken}`).then(res => res.data.data, handleError);this.setMessengerProfile = (profile, { access_token: customAccessToken } = {}) => this._axios.post(`/me/messenger_profile?access_token=${customAccessToken || this._accessToken}`, profile).then(res => res.data, handleError);this.deleteMessengerProfile = (fields, { access_token: customAccessToken } = {}) => this._axios.delete(`/me/messenger_profile?access_token=${customAccessToken || this._accessToken}`, { data: { fields } }).then(res => res.data, handleError);this.getGetStarted = (options = {}) => this.getMessengerProfile(['get_started'], options).then(res => res[0] ? res[0].get_started : null);this.setGetStarted = (payload, options = {}) => this.setMessengerProfile({ get_started: { payload } }, options);this.deleteGetStarted = (options = {}) => this.deleteMessengerProfile(['get_started'], options);this.getPersistentMenu = (options = {}) => this.getMessengerProfile(['persistent_menu'], options).then(res => res[0] ? res[0].persistent_menu : null);this.setPersistentMenu = (menuItems, _ref = {}) => {var _ref$composer_input_d = _ref.composer_input_disabled;let composerInputDisabled = _ref$composer_input_d === undefined ? false : _ref$composer_input_d,options = _objectWithoutProperties(_ref, ['composer_input_disabled']); // menuItems is in type PersistentMenu
if (menuItems.some(item => item.locale === 'default')) {return this.setMessengerProfile({ persistent_menu: menuItems }, options);} // menuItems is in type Array<MenuItem>
return this.setMessengerProfile({ persistent_menu: [{ locale: 'default', composer_input_disabled: composerInputDisabled, call_to_actions: menuItems }] }, options);};this.deletePersistentMenu = (options = {}) => this.deleteMessengerProfile(['persistent_menu'], options);this.getGreeting = (options = {}) => this.getMessengerProfile(['greeting'], options).then(res => res[0] ? res[0].greeting : null);this.setGreeting = (greeting, options = {}) => {if (typeof greeting === 'string') {return this.setMessengerProfile({ greeting: [{ locale: 'default', text: greeting }] }, options);}return this.setMessengerProfile({ greeting }, options);};this.deleteGreeting = (options = {}) => this.deleteMessengerProfile(['greeting'], options);this.getWhitelistedDomains = (options = {}) => this.getMessengerProfile(['whitelisted_domains'], options).then(res => res[0] ? res[0].whitelisted_domains : null);this.setWhitelistedDomains = (domains, options = {}) => this.setMessengerProfile({ whitelisted_domains: domains }, options);this.deleteWhitelistedDomains = (options = {}) => this.deleteMessengerProfile(['whitelisted_domains'], options);this.getAccountLinkingURL = (options = {}) => this.getMessengerProfile(['account_linking_url'], options).then(res => res[0] ? res[0] : null);this.setAccountLinkingURL = (url, options = {}) => this.setMessengerProfile({ account_linking_url: url }, options);this.deleteAccountLinkingURL = (options = {}) => this.deleteMessengerProfile(['account_linking_url'], options);this.getPaymentSettings = (options = {}) => this.getMessengerProfile(['payment_settings'], options).then(res => res[0] ? res[0] : null);this.setPaymentPrivacyPolicyURL = (url, options = {}) => this.setMessengerProfile({ payment_settings: { privacy_url: url } }, options);this.setPaymentPublicKey = (key, options = {}) => this.setMessengerProfile({ payment_settings: { public_key: key } }, options);this.setPaymentTestUsers = (users, options = {}) => this.setMessengerProfile({ payment_settings: { test_users: users } }, options);this.deletePaymentSettings = (options = {}) => this.deleteMessengerProfile(['payment_settings'], options);this.getTargetAudience = (options = {}) => this.getMessengerProfile(['target_audience'], options).then(res => res[0] ? res[0] : null);this.setTargetAudience = (type, whitelist = [], blacklist = [], options = {}) => this.setMessengerProfile({ target_audience: { audience_type: type, countries: { whitelist, blacklist } } }, options);this.deleteTargetAudience = (options = {}) => this.deleteMessengerProfile(['target_audience'], options);this.getHomeURL = (options = {}) => this.getMessengerProfile(['home_url'], options).then(res => res[0] ? res[0] : null);this.setHomeURL = (url, { webview_share_button, in_test }, options = {}) => this.setMessengerProfile({ home_url: { url, webview_height_ratio: 'tall', in_test, webview_share_button } }, options);this.deleteHomeURL = (options = {}) => this.deleteMessengerProfile(['home_url'], options);this.getMessageTags = ({ access_token: customAccessToken } = {}) => this._axios.get(`/page_message_tags?access_token=${customAccessToken || this._accessToken}`).then(res => res.data.data, handleError);this.sendRawBody = body => {const customAccessToken = body.access_token;return this._axios.post(`/me/messages?access_token=${customAccessToken || this._accessToken}`, body).then(res => res.data, handleError);};this.sendMessage = (idOrRecipient, message, options = {}) => {const recipient = typeof idOrRecipient === 'string' ? { id: idOrRecipient } : idOrRecipient;let messageType = 'UPDATE';if (options.messaging_type) {messageType = options.messaging_type;} else if (options.tag) {messageType = 'MESSAGE_TAG';}return this.sendRawBody(_extends({ messaging_type: messageType, recipient, message: _Messenger2.default.createMessage(message, options) }, (0, _lodash2.default)(options, 'quick_replies')));};this.sendMessageFormData = (recipient, formdata, options = {}) => {const recipientObject = typeof recipient === 'string' ? { id: recipient } : recipient;let messageType = 'UPDATE';if (options.messaging_type) {messageType = options.messaging_type;} else if (options.tag) {messageType = 'MESSAGE_TAG';}formdata.append('messaging_type', messageType);formdata.append('recipient', JSON.stringify(recipientObject));return this._axios.post(`/me/messages?access_token=${options.access_token || this._accessToken}`, formdata, { headers: formdata.getHeaders() }).then(res => res.data, handleError);};this.sendAttachment = (recipient, attachment, options) => this.sendMessage(recipient, _Messenger2.default.createAttachment(attachment), options);this.sendText = (recipient, text, options) => this.sendMessage(recipient, _Messenger2.default.createText(text), options);this.sendAudio = (recipient, audio, options) => {const message = _Messenger2.default.createAudio(audio, options);if (message && (0, _isPlainObject2.default)(message)) {return this.sendMessage(recipient, message, options);} // $FlowFixMe
return this.sendMessageFormData(recipient, message, options);};this.sendImage = (recipient, image, options) => {const message = _Messenger2.default.createImage(image, options);if (message && (0, _isPlainObject2.default)(message)) {return this.sendMessage(recipient, message, options);} // $FlowFixMe
return this.sendMessageFormData(recipient, message, options);};this.sendVideo = (recipient, video, options) => {const message = _Messenger2.default.createVideo(video, options);if (message && (0, _isPlainObject2.default)(message)) {return this.sendMessage(recipient, message, options);} // $FlowFixMe
return this.sendMessageFormData(recipient, message, options);};this.sendFile = (recipient, file, options) => {const message = _Messenger2.default.createFile(file, options);if (message && (0, _isPlainObject2.default)(message)) {return this.sendMessage(recipient, message, options);} // $FlowFixMe
return this.sendMessageFormData(recipient, message, options);};this.sendTemplate = (recipient, payload, options) => this.sendMessage(recipient, _Messenger2.default.createTemplate(payload), options);this.sendButtonTemplate = (recipient, text, buttons, options) => this.sendMessage(recipient, _Messenger2.default.createButtonTemplate(text, buttons), options);this.sendGenericTemplate = (recipient, elements, _ref2 = {}) => {var _ref2$image_aspect_ra = _ref2.image_aspect_ratio;let image_aspect_ratio = _ref2$image_aspect_ra === undefined ? 'horizontal' : _ref2$image_aspect_ra,options = _objectWithoutProperties(_ref2, ['image_aspect_ratio']);return this.sendMessage(recipient, _Messenger2.default.createGenericTemplate(elements, { image_aspect_ratio }), options);};this.sendListTemplate = (recipient, elements, buttons, _ref3 = {}) => {var _ref3$top_element_sty = _ref3.top_element_style;let top_element_style = _ref3$top_element_sty === undefined ? 'large' : _ref3$top_element_sty,options = _objectWithoutProperties(_ref3, ['top_element_style']);return this.sendMessage(recipient, _Messenger2.default.createListTemplate(elements, buttons, { top_element_style }), options);};this.sendOpenGraphTemplate = (recipient, elements, options) => this.sendMessage(recipient, _Messenger2.default.createOpenGraphTemplate(elements), options);this.sendReceiptTemplate = (recipient, attrs, options) => this.sendMessage(recipient, _Messenger2.default.createReceiptTemplate(attrs), options);this.sendMediaTemplate = (recipient, elements, options) => this.sendMessage(recipient, _Messenger2.default.createMediaTemplate(elements), options);this.sendAirlineBoardingPassTemplate = (recipient, attrs, options) => this.sendMessage(recipient, _Messenger2.default.createAirlineBoardingPassTemplate(attrs), options);this.sendAirlineCheckinTemplate = (recipient, attrs, options) => this.sendMessage(recipient, _Messenger2.default.createAirlineCheckinTemplate(attrs), options);this.sendAirlineItineraryTemplate = (recipient, attrs, options) => this.sendMessage(recipient, _Messenger2.default.createAirlineItineraryTemplate(attrs), options);this.sendAirlineFlightUpdateTemplate = (recipient, attrs, options) => this.sendMessage(recipient, _Messenger2.default.createAirlineFlightUpdateTemplate(attrs), options);this.sendQuickReplies = (recipient, textOrAttachment, quickReplies, options) => {(0, _warning2.default)(false, '`sendQuickReplies` is deprecated. Use send message methods with `options.quick_replies` instead.');validateQuickReplies(quickReplies);return this.sendMessage(recipient, _extends({}, textOrAttachment, { quick_replies: quickReplies }), options);};this.sendSenderAction = (idOrRecipient, action, { access_token: customAccessToken } = {}) => {const recipient = typeof idOrRecipient === 'string' ? { id: idOrRecipient } : idOrRecipient;return this.sendRawBody({ recipient, sender_action: action, access_token: customAccessToken });};this.markSeen = (recipient, options = {}) => this.sendSenderAction(recipient, 'mark_seen', options);this.typingOn = (recipient, options = {}) => this.sendSenderAction(recipient, 'typing_on', options);this.typingOff = (recipient, options = {}) => this.sendSenderAction(recipient, 'typing_off', options);this.sendBatch = (batch, { access_token: customAccessToken } = {}) => {(0, _invariant2.default)(batch.length <= 50, 'limit the number of requests which can be in a batch to 50');const bodyEncodedbatch = batch.map(item => {if (item.body) {return _extends({}, item, { body: Object.keys(item.body).map(key => {// $FlowFixMe item.body should not possible as undefined.
const val = item.body[key];return `${encodeURIComponent(key)}=${encodeURIComponent(typeof val === 'object' ? JSON.stringify(val) : val)}`;}).join('&') });}return item;});return _axios2.default.post('https://graph.facebook.com/', { access_token: customAccessToken || this._accessToken, batch: bodyEncodedbatch }).then(res => res.data);};this.createMessageCreative = (messages = [], { access_token: customAccessToken } = {}) => this._axios.post(`/me/message_creatives?access_token=${customAccessToken || this._accessToken}`, { messages }).then(res => res.data, handleError);this.sendBroadcastMessage = (messageCreativeId, options = {}) => this._axios.post(`/me/broadcast_messages?access_token=${options.access_token || this._accessToken}`, _extends({ message_creative_id: messageCreativeId }, options)).then(res => res.data, handleError);this.sendSponsoredMessage = (adAccountId, message) => this._axios.post(`/act_${adAccountId}/sponsored_message_ads?access_token=${this._accessToken}`, message).then(res => res.data, handleError);this.createLabel = (name, { access_token: customAccessToken } = {}) => this._axios.post(`/me/custom_labels?access_token=${customAccessToken || this._accessToken}`, { name }).then(res => res.data, handleError);this.associateLabel = (userId, labelId, { access_token: customAccessToken } = {}) => this._axios.post(`/${labelId}/label?access_token=${customAccessToken || this._accessToken}`, { user: userId }).then(res => res.data, handleError);this.dissociateLabel = (userId, labelId, { access_token: customAccessToken } = {}) => this._axios.delete(`/${labelId}/label?access_token=${customAccessToken || this._accessToken}`, { data: { user: userId } }).then(res => res.data, handleError);this.getAssociatedLabels = (userId, { access_token: customAccessToken } = {}) => this._axios.get(`/${userId}/custom_labels?access_token=${customAccessToken || this._accessToken}`).then(res => res.data, handleError);this.getLabelDetails = (labelId, options = {}) => {const fields = options.fields ? options.fields.join(',') : 'name';return this._axios.get(`/${labelId}?fields=${fields}&access_token=${options.access_token || this._accessToken}`).then(res => res.data, handleError);};this.getLabelList = (options = {}) => {const fields = options.fields ? options.fields.join(',') : 'name';return this._axios.get(`/me/custom_labels?fields=${fields}&access_token=${options.access_token || this._accessToken}`).then(res => res.data, handleError);};this.deleteLabel = (labelId, { access_token: customAccessToken } = {}) => this._axios.delete(`/${labelId}?access_token=${customAccessToken || this._accessToken}`).then(res => res.data, handleError);this.startReachEstimation = (customLabelId, { access_token: customAccessToken } = {}) => this._axios.post(`/broadcast_reach_estimations?access_token=${customAccessToken || this._accessToken}`, { custom_label_id: customLabelId }).then(res => res.data, handleError);this.getReachEstimate = (reachEstimationId, { access_token: customAccessToken } = {}) => this._axios.post(`/${reachEstimationId}?access_token=${customAccessToken || this._accessToken}`).then(res => res.data, handleError);this.getBroadcastMessagesSent = (broadcastId, { access_token: customAccessToken } = {}) => this._axios.post(`/${broadcastId}/insights/messages_sent?access_token=${customAccessToken || this._accessToken}`).then(res => res.data.data, handleError);this.uploadAttachment = (type, attachment, options = {}) => {const args = [];const isReusable = options.is_reusable || false;if (typeof attachment === 'string') {args.push({ message: { attachment: { type, payload: { url: attachment, is_reusable: isReusable } } } });} else {const form = new _formData2.default();form.append('message', JSON.stringify({ attachment: { type, payload: { is_reusable: isReusable } } }));form.append('filedata', attachment, (0, _lodash2.default)(options, ['is_reusable']));args.push(form, { headers: form.getHeaders() });}return this._axios.post(`/me/message_attachments?access_token=${options.access_token || this._accessToken}`, ...args).then(res => res.data, handleError);};this.uploadAudio = (attachment, options) => this.uploadAttachment('audio', attachment, options);this.uploadImage = (attachment, options) => this.uploadAttachment('image', attachment, options);this.uploadVideo = (attachment, options) => this.uploadAttachment('video', attachment, options);this.uploadFile = (attachment, options) => this.uploadAttachment('file', attachment, options);this.generateMessengerCode = (options = {}) => this._axios.post(`/me/messenger_codes?access_token=${options.access_token || this._accessToken}`, _extends({ type: 'standard' }, options)).then(res => res.data, handleError);this.passThreadControl = (recipientId, targetAppId, metadata, { access_token: customAccessToken } = {}) => this._axios.post(`/me/pass_thread_control?access_token=${customAccessToken || this._accessToken}`, { recipient: { id: recipientId }, target_app_id: targetAppId, metadata }).then(res => res.data, handleError);this.passThreadControlToPageInbox = (recipientId, metadata, options = {}) => this.passThreadControl(recipientId, 263902037430900, metadata, options);this.takeThreadControl = (recipientId, metadata, { access_token: customAccessToken } = {}) => this._axios.post(`/me/take_thread_control?access_token=${customAccessToken || this._accessToken}`, { recipient: { id: recipientId }, metadata }).then(res => res.data, handleError);this.getSecondaryReceivers = ({ access_token: customAccessToken } = {}) => this._axios.get(`/me/secondary_receivers?fields=id,name&access_token=${customAccessToken || this._accessToken}`).then(res => res.data.data, handleError);this.getInsights = (metrics, options = {}) => this._axios.get(`/me/insights/?${_querystring2.default.stringify(_extends({ metric: metrics.join(','), access_token: options.access_token || this._accessToken }, options))}`).then(res => res.data.data, handleError);this.getDailyUniqueActiveThreadCounts = (options = {}) => this.getInsights(['page_messages_active_threads_unique'], options);this.getBlockedConversations = (options = {}) => this.getInsights(['page_messages_blocked_conversations_unique'], options);this.getReportedConversations = (options = {}) => this.getInsights(['page_messages_reported_conversations_unique'], options);this.getReportedConversationsByReportType = (options = {}) => this.getInsights(['page_messages_blocked_conversations_unique'], options);this.getDailyUniqueConversationCounts = () => {(0, _warning2.default)(false, 'page_messages_feedback_by_action_unique is deprecated as of November 7, 2017.\nThis metric will be removed in Graph API v2.12.');return this.getInsights(['page_messages_feedback_by_action_unique']);};this.setNLPConfigs = (config = {}, { access_token: customAccessToken } = {}) => this._axios.post(`/me/nlp_configs?${_querystring2.default.stringify(config)}`, { access_token: customAccessToken || this._accessToken }).then(res => res.data, handleError);this.enableNLP = (options = {}) => this.setNLPConfigs({ nlp_enabled: true }, options);this.disableNLP = (options = {}) => this.setNLPConfigs({ nlp_enabled: false }, options);this.logCustomEvents = ({ app_id, appId, page_id, pageId, page_scoped_user_id, userId, events, access_token: customAccessToken }) => {// FIXME: remove in v0.7
(0, _warning2.default)(!appId, '`appId` is deprecated. Use `app_id` instead.');(0, _warning2.default)(!pageId, '`pageId` is deprecated. Use `page_id` instead.');(0, _warning2.default)(!userId, '`userId` is deprecated. Use `page_scoped_user_id` instead.'); /* eslint-disable no-param-reassign */app_id = app_id || appId;page_id = page_id || pageId;page_scoped_user_id = page_scoped_user_id || userId; /* eslint-enable no-param-reassign */return this._axios.post(`/${app_id}/activities?access_token=${customAccessToken || this._accessToken}`, { event: 'CUSTOM_APP_EVENTS', custom_events: JSON.stringify(events), advertiser_tracking_enabled: 0, application_tracking_enabled: 0, extinfo: JSON.stringify(['mb1']), page_id, page_scoped_user_id }).then(res => res.data, handleError);};this.getUserField = ({ field, user_id, app_secret, app, page, access_token: customAccessToken }) => {const accessToken = customAccessToken || this._accessToken; // $appsecret_proof= hash_hmac('sha256', $access_token, $app_secret);
const appsecretProof = _crypto2.default.createHmac('sha256', app_secret).update(accessToken).digest('hex');const appQueryString = app ? `&app=${app}` : '';const pageQueryString = page ? `&page=${page}` : '';return this._axios.get(`/${user_id}/${field}?access_token=${accessToken}&appsecret_proof=${appsecretProof}${appQueryString}${pageQueryString}`).then(res => res.data, handleError);};this.getIdsForApps = ({ user_id, app_secret, app, page, access_token }) => this.getUserField({ field: 'ids_for_apps', user_id, app_secret, app, page, access_token });this.getIdsForPages = ({ user_id, app_secret, app, page, access_token }) =>
this.getUserField({
field: 'ids_for_pages',
user_id,
app_secret,
app,
page,
access_token });};
}}exports.default = MessengerClient;
{
"name": "messaging-api-messenger",
"description": "Messaging API client for Messenger",
"version": "0.7.0-alpha.2",
"version": "0.7.0-beta.1",
"engines": {

@@ -22,3 +22,3 @@ "node": ">=6"

"axios": "^0.17.0",
"axios-error": "^0.7.0-alpha.2",
"axios-error": "^0.7.0-beta.1",
"form-data": "^2.3.1",

@@ -25,0 +25,0 @@ "invariant": "^2.2.2",

@@ -1,6 +0,7 @@

import { Messenger, MessengerClient } from '../';
import { Messenger, MessengerBatch, MessengerClient } from '../';
it('should export api correctly', () => {
expect(Messenger).toBeDefined();
expect(MessengerBatch).toBeDefined();
expect(MessengerClient).toBeDefined();
});

@@ -117,1 +117,905 @@ import MessengerBatch from '../MessengerBatch';

});
describe('createAttachment', () => {
it('should create send attachment request', () => {
expect(
MessengerBatch.createAttachment(RECIPIENT_ID, {
type: 'image',
payload: {
url: 'https://example.com/pic.png',
},
})
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'image',
payload: {
url: 'https://example.com/pic.png',
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createAudio', () => {
const request = {
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'audio',
payload: {
url: 'https://example.com/audio.mp3',
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
};
it('should create send audio request with url', () => {
expect(
MessengerBatch.createAudio(RECIPIENT_ID, 'https://example.com/audio.mp3')
).toEqual(request);
});
it('should create send audio request with payload', () => {
expect(
MessengerBatch.createAudio(RECIPIENT_ID, {
url: 'https://example.com/audio.mp3',
})
).toEqual(request);
});
});
describe('createImage', () => {
const request = {
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'image',
payload: {
url: 'https://example.com/pic.png',
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
};
it('should create send image request with url', () => {
expect(
MessengerBatch.createImage(RECIPIENT_ID, 'https://example.com/pic.png')
).toEqual(request);
});
it('should create send image request with payload', () => {
expect(
MessengerBatch.createImage(RECIPIENT_ID, {
url: 'https://example.com/pic.png',
})
).toEqual(request);
});
});
describe('createVideo', () => {
const request = {
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'video',
payload: {
url: 'https://example.com/video.mp4',
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
};
it('should create send video request with url', () => {
expect(
MessengerBatch.createVideo(RECIPIENT_ID, 'https://example.com/video.mp4')
).toEqual(request);
});
it('should create send video request with payload', () => {
expect(
MessengerBatch.createVideo(RECIPIENT_ID, {
url: 'https://example.com/video.mp4',
})
).toEqual(request);
});
});
describe('createFile', () => {
const request = {
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'file',
payload: {
url: 'https://example.com/file.pdf',
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
};
it('should create send file request with url', () => {
expect(
MessengerBatch.createFile(RECIPIENT_ID, 'https://example.com/file.pdf')
).toEqual(request);
});
it('should create send file request with payload', () => {
expect(
MessengerBatch.createFile(RECIPIENT_ID, {
url: 'https://example.com/file.pdf',
})
).toEqual(request);
});
});
describe('createTemplate', () => {
it('should create send template request', () => {
expect(
MessengerBatch.createTemplate(RECIPIENT_ID, {
template_type: 'button',
text: 'title',
buttons: [
{
type: 'postback',
title: 'Start Chatting',
payload: 'USER_DEFINED_PAYLOAD',
},
],
})
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'button',
text: 'title',
buttons: [
{
type: 'postback',
title: 'Start Chatting',
payload: 'USER_DEFINED_PAYLOAD',
},
],
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createButtonTemplate', () => {
it('should create send button template request', () => {
expect(
MessengerBatch.createButtonTemplate(RECIPIENT_ID, 'title', [
{
type: 'postback',
title: 'Start Chatting',
payload: 'USER_DEFINED_PAYLOAD',
},
])
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'button',
text: 'title',
buttons: [
{
type: 'postback',
title: 'Start Chatting',
payload: 'USER_DEFINED_PAYLOAD',
},
],
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createGenericTemplate', () => {
const elements = [
{
title: "Welcome to Peter's Hats",
image_url: 'https://petersfancybrownhats.com/company_image.png',
subtitle: "We've got the right hat for everyone.",
default_action: {
type: 'web_url',
url: 'https://peterssendreceiveapp.ngrok.io/view?item=103',
messenger_extensions: true,
webview_height_ratio: 'tall',
fallback_url: 'https://peterssendreceiveapp.ngrok.io/',
},
buttons: [
{
type: 'postback',
title: 'Start Chatting',
payload: 'DEVELOPER_DEFINED_PAYLOAD',
},
],
},
];
it('should create send generic template request', () => {
expect(
MessengerBatch.createGenericTemplate(RECIPIENT_ID, elements)
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements,
image_aspect_ratio: 'horizontal',
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createListTemplate', () => {
const elements = [
{
title: 'Classic T-Shirt Collection',
image_url: 'https://peterssendreceiveapp.ngrok.io/img/collection.png',
subtitle: 'See all our colors',
default_action: {
type: 'web_url',
url: 'https://peterssendreceiveapp.ngrok.io/shop_collection',
messenger_extensions: true,
webview_height_ratio: 'tall',
fallback_url: 'https://peterssendreceiveapp.ngrok.io/',
},
buttons: [
{
title: 'View',
type: 'web_url',
url: 'https://peterssendreceiveapp.ngrok.io/collection',
messenger_extensions: true,
webview_height_ratio: 'tall',
fallback_url: 'https://peterssendreceiveapp.ngrok.io/',
},
],
},
];
const buttons = [
{
type: 'postback',
title: 'Start Chatting',
payload: 'USER_DEFINED_PAYLOAD',
},
];
it('should create send list template request', () => {
expect(
MessengerBatch.createListTemplate(RECIPIENT_ID, elements, buttons, {
top_element_style: 'compact',
})
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'list',
elements,
buttons,
top_element_style: 'compact',
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createOpenGraphTemplate', () => {
const elements = [
{
url: 'https://open.spotify.com/track/7GhIk7Il098yCjg4BQjzvb',
buttons: [
{
type: 'web_url',
url: 'https://en.wikipedia.org/wiki/Rickrolling',
title: 'View More',
},
],
},
];
it('should create send open graph template request', () => {
expect(
MessengerBatch.createOpenGraphTemplate(RECIPIENT_ID, elements)
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'open_graph',
elements,
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createReceiptTemplate', () => {
const receipt = {
recipient_name: 'Stephane Crozatier',
order_number: '12345678902',
currency: 'USD',
payment_method: 'Visa 2345',
order_url: 'http://petersapparel.parseapp.com/order?order_id=123456',
timestamp: '1428444852',
elements: [
{
title: 'Classic White T-Shirt',
subtitle: '100% Soft and Luxurious Cotton',
quantity: 2,
price: 50,
currency: 'USD',
image_url: 'http://petersapparel.parseapp.com/img/whiteshirt.png',
},
{
title: 'Classic Gray T-Shirt',
subtitle: '100% Soft and Luxurious Cotton',
quantity: 1,
price: 25,
currency: 'USD',
image_url: 'http://petersapparel.parseapp.com/img/grayshirt.png',
},
],
address: {
street_1: '1 Hacker Way',
street_2: '',
city: 'Menlo Park',
postal_code: '94025',
state: 'CA',
country: 'US',
},
summary: {
subtotal: 75.0,
shipping_cost: 4.95,
total_tax: 6.19,
total_cost: 56.14,
},
adjustments: [
{
name: 'New Customer Discount',
amount: 20,
},
{
name: '$10 Off Coupon',
amount: 10,
},
],
};
it('should create send receipt template request', () => {
expect(MessengerBatch.createReceiptTemplate(RECIPIENT_ID, receipt)).toEqual(
{
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'receipt',
...receipt,
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
}
);
});
});
describe('createMediaTemplate', () => {
const elements = [
{
media_type: 'image',
attachment_id: '1854626884821032',
buttons: [
{
type: 'web_url',
url: '<WEB_URL>',
title: 'View Website',
},
],
},
];
it('should create send media template request', () => {
expect(MessengerBatch.createMediaTemplate(RECIPIENT_ID, elements)).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'media',
elements,
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createAirlineBoardingPassTemplate', () => {
const attrs = {
intro_message: 'You are checked in.',
locale: 'en_US',
boarding_pass: [
{
passenger_name: 'SMITH/NICOLAS',
pnr_number: 'CG4X7U',
travel_class: 'business',
seat: '74J',
auxiliary_fields: [
{
label: 'Terminal',
value: 'T1',
},
{
label: 'Departure',
value: '30OCT 19:05',
},
],
secondary_fields: [
{
label: 'Boarding',
value: '18:30',
},
{
label: 'Gate',
value: 'D57',
},
{
label: 'Seat',
value: '74J',
},
{
label: 'Sec.Nr.',
value: '003',
},
],
logo_image_url: 'https://www.example.com/en/logo.png',
header_image_url: 'https://www.example.com/en/fb/header.png',
qr_code: 'M1SMITH/NICOLAS CG4X7U nawouehgawgnapwi3jfa0wfh',
above_bar_code_image_url: 'https://www.example.com/en/PLAT.png',
flight_info: {
flight_number: 'KL0642',
departure_airport: {
airport_code: 'JFK',
city: 'New York',
terminal: 'T1',
gate: 'D57',
},
arrival_airport: {
airport_code: 'AMS',
city: 'Amsterdam',
},
flight_schedule: {
departure_time: '2016-01-02T19:05',
arrival_time: '2016-01-05T17:30',
},
},
},
{
passenger_name: 'JONES/FARBOUND',
pnr_number: 'CG4X7U',
travel_class: 'business',
seat: '74K',
auxiliary_fields: [
{
label: 'Terminal',
value: 'T1',
},
{
label: 'Departure',
value: '30OCT 19:05',
},
],
secondary_fields: [
{
label: 'Boarding',
value: '18:30',
},
{
label: 'Gate',
value: 'D57',
},
{
label: 'Seat',
value: '74K',
},
{
label: 'Sec.Nr.',
value: '004',
},
],
logo_image_url: 'https://www.example.com/en/logo.png',
header_image_url: 'https://www.example.com/en/fb/header.png',
qr_code: 'M1JONES/FARBOUND CG4X7U nawouehgawgnapwi3jfa0wfh',
above_bar_code_image_url: 'https://www.example.com/en/PLAT.png',
flight_info: {
flight_number: 'KL0642',
departure_airport: {
airport_code: 'JFK',
city: 'New York',
terminal: 'T1',
gate: 'D57',
},
arrival_airport: {
airport_code: 'AMS',
city: 'Amsterdam',
},
flight_schedule: {
departure_time: '2016-01-02T19:05',
arrival_time: '2016-01-05T17:30',
},
},
},
],
};
it('should create send airline boarding pass template request', () => {
expect(
MessengerBatch.createAirlineBoardingPassTemplate(RECIPIENT_ID, attrs)
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'airline_boardingpass',
...attrs,
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createAirlineCheckinTemplate', () => {
const attrs = {
intro_message: 'Check-in is available now.',
locale: 'en_US',
pnr_number: 'ABCDEF',
flight_info: [
{
flight_number: 'f001',
departure_airport: {
airport_code: 'SFO',
city: 'San Francisco',
terminal: 'T4',
gate: 'G8',
},
arrival_airport: {
airport_code: 'SEA',
city: 'Seattle',
terminal: 'T4',
gate: 'G8',
},
flight_schedule: {
boarding_time: '2016-01-05T15:05',
departure_time: '2016-01-05T15:45',
arrival_time: '2016-01-05T17:30',
},
},
],
checkin_url: 'https://www.airline.com/check-in',
};
it('should create send airline checkin template request', () => {
expect(
MessengerBatch.createAirlineCheckinTemplate(RECIPIENT_ID, attrs)
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'airline_checkin',
...attrs,
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createAirlineItineraryTemplate', () => {
const attrs = {
intro_message: "Here's your flight itinerary.",
locale: 'en_US',
pnr_number: 'ABCDEF',
passenger_info: [
{
name: 'Farbound Smith Jr',
ticket_number: '0741234567890',
passenger_id: 'p001',
},
{
name: 'Nick Jones',
ticket_number: '0741234567891',
passenger_id: 'p002',
},
],
flight_info: [
{
connection_id: 'c001',
segment_id: 's001',
flight_number: 'KL9123',
aircraft_type: 'Boeing 737',
departure_airport: {
airport_code: 'SFO',
city: 'San Francisco',
terminal: 'T4',
gate: 'G8',
},
arrival_airport: {
airport_code: 'SLC',
city: 'Salt Lake City',
terminal: 'T4',
gate: 'G8',
},
flight_schedule: {
departure_time: '2016-01-02T19:45',
arrival_time: '2016-01-02T21:20',
},
travel_class: 'business',
},
{
connection_id: 'c002',
segment_id: 's002',
flight_number: 'KL321',
aircraft_type: 'Boeing 747-200',
travel_class: 'business',
departure_airport: {
airport_code: 'SLC',
city: 'Salt Lake City',
terminal: 'T1',
gate: 'G33',
},
arrival_airport: {
airport_code: 'AMS',
city: 'Amsterdam',
terminal: 'T1',
gate: 'G33',
},
flight_schedule: {
departure_time: '2016-01-02T22:45',
arrival_time: '2016-01-03T17:20',
},
},
],
passenger_segment_info: [
{
segment_id: 's001',
passenger_id: 'p001',
seat: '12A',
seat_type: 'Business',
},
{
segment_id: 's001',
passenger_id: 'p002',
seat: '12B',
seat_type: 'Business',
},
{
segment_id: 's002',
passenger_id: 'p001',
seat: '73A',
seat_type: 'World Business',
product_info: [
{
title: 'Lounge',
value: 'Complimentary lounge access',
},
{
title: 'Baggage',
value: '1 extra bag 50lbs',
},
],
},
{
segment_id: 's002',
passenger_id: 'p002',
seat: '73B',
seat_type: 'World Business',
product_info: [
{
title: 'Lounge',
value: 'Complimentary lounge access',
},
{
title: 'Baggage',
value: '1 extra bag 50lbs',
},
],
},
],
price_info: [
{
title: 'Fuel surcharge',
amount: '1597',
currency: 'USD',
},
],
base_price: '12206',
tax: '200',
total_price: '14003',
currency: 'USD',
};
it('should create send airline itinerary template request', () => {
expect(
MessengerBatch.createAirlineItineraryTemplate(RECIPIENT_ID, attrs)
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'airline_itinerary',
...attrs,
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
describe('createAirlineFlightUpdateTemplate', () => {
const attrs = {
intro_message: 'Your flight is delayed',
update_type: 'delay',
locale: 'en_US',
pnr_number: 'CF23G2',
update_flight_info: {
flight_number: 'KL123',
departure_airport: {
airport_code: 'SFO',
city: 'San Francisco',
terminal: 'T4',
gate: 'G8',
},
arrival_airport: {
airport_code: 'AMS',
city: 'Amsterdam',
terminal: 'T4',
gate: 'G8',
},
flight_schedule: {
boarding_time: '2015-12-26T10:30',
departure_time: '2015-12-26T11:30',
arrival_time: '2015-12-27T07:30',
},
},
};
it('should create send airline flight update template request', () => {
expect(
MessengerBatch.createAirlineFlightUpdateTemplate(RECIPIENT_ID, attrs)
).toEqual({
method: 'POST',
relative_url: 'me/messages',
body: {
messaging_type: 'UPDATE',
message: {
attachment: {
type: 'template',
payload: {
template_type: 'airline_update',
...attrs,
},
},
},
recipient: {
id: RECIPIENT_ID,
},
},
});
});
});
/* @flow */
/* eslint-disable camelcase */
import Messenger from './Messenger';
import type {

@@ -8,3 +10,15 @@ UserID,

Message,
Attachment,
FileData,
AttachmentPayload,
BatchItem,
TemplateButton,
TemplateElement,
OpenGraphElement,
ReceiptAttributes,
MediaElement,
AirlineBoardingPassAttributes,
AirlineCheckinAttributes,
AirlineItineraryAttributes,
AirlineFlightUpdateAttributes,
} from './MessengerTypes';

@@ -22,3 +36,3 @@

idOrRecipient: UserID | Recipient,
message: Message,
msg: Message,
options?: SendOption = {}

@@ -38,6 +52,7 @@ ): BatchItem {

}
return createRequest({
messaging_type: messageType,
recipient,
message,
message: Messenger.createMessage(msg, options),
...options,

@@ -52,5 +67,214 @@ });

): BatchItem {
return createMessage(recipient, { text }, options);
return createMessage(recipient, Messenger.createText(text, options), options);
}
function createAttachment(
recipient: UserID | Recipient,
attachment: Attachment,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createAttachment(attachment, options),
options
);
}
function createAudio(
recipient: UserID | Recipient,
audio: string | FileData | AttachmentPayload,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createAudio(audio, options),
options
);
}
function createImage(
recipient: UserID | Recipient,
image: string | FileData | AttachmentPayload,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createImage(image, options),
options
);
}
function createVideo(
recipient: UserID | Recipient,
video: string | FileData | AttachmentPayload,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createVideo(video, options),
options
);
}
function createFile(
recipient: UserID | Recipient,
file: string | FileData | AttachmentPayload,
options?: SendOption
): BatchItem {
return createMessage(recipient, Messenger.createFile(file, options), options);
}
function createTemplate(
recipient: UserID | Recipient,
payload: AttachmentPayload,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createTemplate(payload, options),
options
);
}
function createButtonTemplate(
recipient: UserID | Recipient,
text: string,
buttons: Array<TemplateButton>,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createButtonTemplate(text, buttons, options),
options
);
}
function createGenericTemplate(
recipient: UserID | Recipient,
elements: Array<TemplateElement>,
{
// $FlowFixMe
image_aspect_ratio = 'horizontal',
...options
}: {
image_aspect_ratio: 'horizontal' | 'square',
...SendOption,
} = {}
): BatchItem {
return createMessage(
recipient,
Messenger.createGenericTemplate(elements, {
...options,
image_aspect_ratio,
}),
options
);
}
function createListTemplate(
recipient: UserID | Recipient,
elements: Array<TemplateElement>,
buttons: Array<TemplateButton>,
{
// $FlowFixMe
top_element_style = 'large',
...options
}: {
top_element_style: 'large' | 'compact',
...SendOption,
} = {}
): BatchItem {
return createMessage(
recipient,
Messenger.createListTemplate(elements, buttons, {
...options,
top_element_style,
}),
options
);
}
function createOpenGraphTemplate(
recipient: UserID | Recipient,
elements: Array<OpenGraphElement>,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createOpenGraphTemplate(elements, options),
options
);
}
function createReceiptTemplate(
recipient: UserID | Recipient,
attrs: ReceiptAttributes,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createReceiptTemplate(attrs, options),
options
);
}
function createMediaTemplate(
recipient: UserID | Recipient,
elements: Array<MediaElement>,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createMediaTemplate(elements, options),
options
);
}
function createAirlineBoardingPassTemplate(
recipient: UserID | Recipient,
attrs: AirlineBoardingPassAttributes,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createAirlineBoardingPassTemplate(attrs, options),
options
);
}
function createAirlineCheckinTemplate(
recipient: UserID | Recipient,
attrs: AirlineCheckinAttributes,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createAirlineCheckinTemplate(attrs, options),
options
);
}
function createAirlineItineraryTemplate(
recipient: UserID | Recipient,
attrs: AirlineItineraryAttributes,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createAirlineItineraryTemplate(attrs, options),
options
);
}
function createAirlineFlightUpdateTemplate(
recipient: UserID | Recipient,
attrs: AirlineFlightUpdateAttributes,
options?: SendOption
): BatchItem {
return createMessage(
recipient,
Messenger.createAirlineFlightUpdateTemplate(attrs, options),
options
);
}
const MessengerBatch = {

@@ -60,4 +284,20 @@ createRequest,

createText,
createAttachment,
createAudio,
createImage,
createVideo,
createFile,
createTemplate,
createButtonTemplate,
createGenericTemplate,
createListTemplate,
createOpenGraphTemplate,
createReceiptTemplate,
createMediaTemplate,
createAirlineBoardingPassTemplate,
createAirlineCheckinTemplate,
createAirlineItineraryTemplate,
createAirlineFlightUpdateTemplate,
};
export default MessengerBatch;

@@ -13,3 +13,2 @@ /* @flow */

import isPlainObject from 'is-plain-object';
import warning from 'warning';

@@ -22,3 +21,2 @@ import Messenger from './Messenger';

Attachment,
TextOrAttachment,
Message,

@@ -31,3 +29,2 @@ SendOption,

TemplateElement,
QuickReply,
SenderAction,

@@ -73,26 +70,2 @@ User,

function validateQuickReplies(quickReplies: Array<QuickReply>): void {
// quick_replies is limited to 11
invariant(
Array.isArray(quickReplies) && quickReplies.length <= 11,
'quick_replies is an array and limited to 11'
);
quickReplies.forEach(quickReply => {
if (quickReply.content_type === 'text') {
// title has a 20 character limit, after that it gets truncated
invariant(
(quickReply.title: any).trim().length <= 20,
'title of quick reply has a 20 character limit, after that it gets truncated'
);
// payload has a 1000 character limit
invariant(
(quickReply.payload: any).length <= 1000,
'payload of quick reply has a 1000 character limit'
);
}
});
}
function handleError(err) {

@@ -104,7 +77,15 @@ const { error } = err.response.data;

type ClientConfig = {
accessToken: string,
version?: string,
origin?: string,
};
export default class MessengerClient {
static connect = (
accessToken: string,
static connect(
accessTokenOrConfig: string | ClientConfig,
version?: string = '2.11'
): MessengerClient => new MessengerClient(accessToken, version);
): MessengerClient {
return new MessengerClient(accessTokenOrConfig, version);
}

@@ -115,8 +96,28 @@ _accessToken: string;

constructor(accessToken: string, version?: string = '2.11') {
this._accessToken = accessToken;
invariant(typeof version === 'string', 'Type of `version` must be string.');
this._version = extractVersion(version);
constructor(
accessTokenOrConfig: string | ClientConfig,
version?: string = '2.11'
) {
let origin;
if (accessTokenOrConfig && typeof accessTokenOrConfig === 'object') {
const config = accessTokenOrConfig;
this._accessToken = config.accessToken;
invariant(
!config.version || typeof config.version === 'string',
'Type of `version` must be string.'
);
this._version = extractVersion(config.version || '2.11');
origin = config.origin;
} else {
this._accessToken = accessTokenOrConfig;
invariant(
typeof version === 'string',
'Type of `version` must be string.'
);
this._version = extractVersion(version);
}
this._axios = axios.create({
baseURL: `https://graph.facebook.com/v${this._version}/`,
baseURL: `${origin || 'https://graph.facebook.com'}/v${this._version}/`,
headers: { 'Content-Type': 'application/json' },

@@ -144,8 +145,9 @@ });

*/
getPageInfo = ({
getPageInfo({
access_token: customAccessToken,
}: { access_token?: string } = {}): Promise<PageInfo> =>
this._axios
}: { access_token?: string } = {}): Promise<PageInfo> {
return this._axios
.get(`/me?access_token=${customAccessToken || this._accessToken}`)
.then(res => res.data, handleError);
}

@@ -157,3 +159,3 @@ /**

*/
createSubscription = ({
createSubscription({
app_id: appId,

@@ -181,4 +183,4 @@ object = 'page',

access_token: string,
}): Promise<{ success: boolean }> =>
this._axios
}): Promise<{ success: boolean }> {
return this._axios
.post(`/${appId}/subscriptions?access_token=${appAccessToken}`, {

@@ -192,2 +194,3 @@ object,

.then(res => res.data, handleError);
}

@@ -200,9 +203,10 @@ /**

*/
getUserProfile = (
getUserProfile(
userId: string,
{ access_token: customAccessToken }: { access_token?: string } = {}
): Promise<User> =>
this._axios
): Promise<User> {
return this._axios
.get(`/${userId}?access_token=${customAccessToken || this._accessToken}`)
.then(res => res.data, handleError);
}

@@ -214,7 +218,7 @@ /**

*/
getMessengerProfile = (
getMessengerProfile(
fields: Array<string>,
{ access_token: customAccessToken }: { access_token?: string } = {}
): Promise<MessengerProfileResponse> =>
this._axios
): Promise<MessengerProfileResponse> {
return this._axios
.get(

@@ -226,8 +230,9 @@ `/me/messenger_profile?fields=${fields.join(

.then(res => res.data.data, handleError);
}
setMessengerProfile = (
setMessengerProfile(
profile: MessengerProfile,
{ access_token: customAccessToken }: { access_token?: string } = {}
): Promise<MutationSuccessResponse> =>
this._axios
): Promise<MutationSuccessResponse> {
return this._axios
.post(

@@ -239,8 +244,9 @@ `/me/messenger_profile?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}
deleteMessengerProfile = (
deleteMessengerProfile(
fields: Array<string>,
{ access_token: customAccessToken }: { access_token?: string } = {}
): Promise<MutationSuccessResponse> =>
this._axios
): Promise<MutationSuccessResponse> {
return this._axios
.delete(

@@ -256,2 +262,3 @@ `/me/messenger_profile?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}

@@ -263,14 +270,15 @@ /**

*/
getGetStarted = (
getGetStarted(
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['get_started'], options).then(
): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['get_started'], options).then(
res => (res[0] ? res[0].get_started : null)
);
}
setGetStarted = (
setGetStarted(
payload: string,
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -283,7 +291,7 @@ get_started: {

);
}
deleteGetStarted = (
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['get_started'], options);
deleteGetStarted(options?: Object = {}): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['get_started'], options);
}

@@ -295,10 +303,11 @@ /**

*/
getPersistentMenu = (
getPersistentMenu(
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['persistent_menu'], options).then(
): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['persistent_menu'], options).then(
res => (res[0] ? res[0].persistent_menu : null)
);
}
setPersistentMenu = (
setPersistentMenu(
menuItems: Array<MenuItem> | PersistentMenu,

@@ -312,3 +321,3 @@ {

} = {}
): Promise<MutationSuccessResponse> => {
): Promise<MutationSuccessResponse> {
// menuItems is in type PersistentMenu

@@ -337,8 +346,9 @@ if (menuItems.some((item: Object) => item.locale === 'default')) {

);
};
}
deletePersistentMenu = (
deletePersistentMenu(
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['persistent_menu'], options);
): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['persistent_menu'], options);
}

@@ -350,13 +360,12 @@ /**

*/
getGreeting = (
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['greeting'], options).then(
getGreeting(options?: Object = {}): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['greeting'], options).then(
res => (res[0] ? res[0].greeting : null)
);
}
setGreeting = (
setGreeting(
greeting: string | Array<GreetingConfig>,
options?: Object = {}
): Promise<MutationSuccessResponse> => {
): Promise<MutationSuccessResponse> {
if (typeof greeting === 'string') {

@@ -382,6 +391,7 @@ return this.setMessengerProfile(

);
};
}
deleteGreeting = (options?: Object = {}): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['greeting'], options);
deleteGreeting(options?: Object = {}): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['greeting'], options);
}

@@ -393,14 +403,15 @@ /**

*/
getWhitelistedDomains = (
getWhitelistedDomains(
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['whitelisted_domains'], options).then(
): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['whitelisted_domains'], options).then(
res => (res[0] ? res[0].whitelisted_domains : null)
);
}
setWhitelistedDomains = (
setWhitelistedDomains(
domains: Array<string>,
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -411,7 +422,9 @@ whitelisted_domains: domains,

);
}
deleteWhitelistedDomains = (
deleteWhitelistedDomains(
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['whitelisted_domains'], options);
): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['whitelisted_domains'], options);
}

@@ -423,14 +436,15 @@ /**

*/
getAccountLinkingURL = (
getAccountLinkingURL(
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['account_linking_url'], options).then(
): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['account_linking_url'], options).then(
res => (res[0] ? res[0] : null)
);
}
setAccountLinkingURL = (
setAccountLinkingURL(
url: string,
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -441,7 +455,9 @@ account_linking_url: url,

);
}
deleteAccountLinkingURL = (
deleteAccountLinkingURL(
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['account_linking_url'], options);
): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['account_linking_url'], options);
}

@@ -453,14 +469,15 @@ /**

*/
getPaymentSettings = (
getPaymentSettings(
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['payment_settings'], options).then(
): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['payment_settings'], options).then(
res => (res[0] ? res[0] : null)
);
}
setPaymentPrivacyPolicyURL = (
setPaymentPrivacyPolicyURL(
url: string,
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -473,8 +490,9 @@ payment_settings: {

);
}
setPaymentPublicKey = (
setPaymentPublicKey(
key: string,
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -487,8 +505,9 @@ payment_settings: {

);
}
setPaymentTestUsers = (
setPaymentTestUsers(
users: Array<string>,
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -501,7 +520,9 @@ payment_settings: {

);
}
deletePaymentSettings = (
deletePaymentSettings(
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['payment_settings'], options);
): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['payment_settings'], options);
}

@@ -513,10 +534,11 @@ /**

*/
getTargetAudience = (
getTargetAudience(
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['target_audience'], options).then(
): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['target_audience'], options).then(
res => (res[0] ? res[0] : null)
);
}
setTargetAudience = (
setTargetAudience(
type: AudienceType,

@@ -526,4 +548,4 @@ whitelist: ?Array<string> = [],

options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -540,7 +562,9 @@ target_audience: {

);
}
deleteTargetAudience = (
deleteTargetAudience(
options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['target_audience'], options);
): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['target_audience'], options);
}

@@ -552,10 +576,9 @@ /**

*/
getHomeURL = (
options?: Object = {}
): Promise<MessengerProfileResponse | null> =>
this.getMessengerProfile(['home_url'], options).then(
getHomeURL(options?: Object = {}): Promise<MessengerProfileResponse | null> {
return this.getMessengerProfile(['home_url'], options).then(
res => (res[0] ? res[0] : null)
);
}
setHomeURL = (
setHomeURL(
url: string,

@@ -570,4 +593,4 @@ {

options?: Object = {}
): Promise<MutationSuccessResponse> =>
this.setMessengerProfile(
): Promise<MutationSuccessResponse> {
return this.setMessengerProfile(
{

@@ -583,5 +606,7 @@ home_url: {

);
}
deleteHomeURL = (options?: Object = {}): Promise<MutationSuccessResponse> =>
this.deleteMessengerProfile(['home_url'], options);
deleteHomeURL(options?: Object = {}): Promise<MutationSuccessResponse> {
return this.deleteMessengerProfile(['home_url'], options);
}

@@ -593,6 +618,6 @@ /**

*/
getMessageTags = ({
getMessageTags({
access_token: customAccessToken,
}: { access_token?: string } = {}): Promise<MessageTagResponse> =>
this._axios
}: { access_token?: string } = {}): Promise<MessageTagResponse> {
return this._axios
.get(

@@ -603,2 +628,3 @@ `/page_message_tags?access_token=${customAccessToken ||

.then(res => res.data.data, handleError);
}

@@ -611,3 +637,3 @@ /**

// TODO: body flowtype
sendRawBody = (body: Object): Promise<SendMessageSucessResponse> => {
sendRawBody(body: Object): Promise<SendMessageSucessResponse> {
const { access_token: customAccessToken } = body;

@@ -621,9 +647,9 @@

.then(res => res.data, handleError);
};
}
sendMessage = (
sendMessage(
idOrRecipient: UserID | Recipient,
message: Message,
options?: SendOption = {}
): Promise<SendMessageSucessResponse> => {
): Promise<SendMessageSucessResponse> {
const recipient =

@@ -650,9 +676,9 @@ typeof idOrRecipient === 'string'

});
};
}
sendMessageFormData = (
sendMessageFormData(
recipient: UserID | Recipient,
formdata: FormData,
options?: SendOption = {}
) => {
) {
const recipientObject =

@@ -685,3 +711,3 @@ typeof recipient === 'string'

.then(res => res.data, handleError);
};
}

@@ -693,25 +719,31 @@ /**

*/
sendAttachment = (
sendAttachment(
recipient: UserID | Recipient,
attachment: Attachment,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createAttachment(attachment),
Messenger.createAttachment(attachment, options),
options
);
}
sendText = (
sendText(
recipient: UserID | Recipient,
text: string,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(recipient, Messenger.createText(text), options);
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createText(text, options),
options
);
}
sendAudio = (
sendAudio(
recipient: UserID | Recipient,
audio: string | FileData | AttachmentPayload,
options?: SendOption
): Promise<SendMessageSucessResponse> => {
): Promise<SendMessageSucessResponse> {
const message = Messenger.createAudio(audio, options);

@@ -725,9 +757,9 @@

return this.sendMessageFormData(recipient, message, options);
};
}
sendImage = (
sendImage(
recipient: UserID | Recipient,
image: string | FileData | AttachmentPayload,
options?: SendOption
): Promise<SendMessageSucessResponse> => {
): Promise<SendMessageSucessResponse> {
const message = Messenger.createImage(image, options);

@@ -741,9 +773,9 @@

return this.sendMessageFormData(recipient, message, options);
};
}
sendVideo = (
sendVideo(
recipient: UserID | Recipient,
video: string | FileData | AttachmentPayload,
options?: SendOption
): Promise<SendMessageSucessResponse> => {
): Promise<SendMessageSucessResponse> {
const message = Messenger.createVideo(video, options);

@@ -757,9 +789,9 @@

return this.sendMessageFormData(recipient, message, options);
};
}
sendFile = (
sendFile(
recipient: UserID | Recipient,
file: string | FileData | AttachmentPayload,
options?: SendOption
): Promise<SendMessageSucessResponse> => {
): Promise<SendMessageSucessResponse> {
const message = Messenger.createFile(file, options);

@@ -773,3 +805,3 @@

return this.sendMessageFormData(recipient, message, options);
};
}

@@ -781,11 +813,16 @@ /**

*/
sendTemplate = (
sendTemplate(
recipient: UserID | Recipient,
payload: AttachmentPayload,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(recipient, Messenger.createTemplate(payload), options);
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createTemplate(payload, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/button
sendButtonTemplate = (
sendButtonTemplate(
recipient: UserID | Recipient,

@@ -795,11 +832,12 @@ text: string,

options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createButtonTemplate(text, buttons),
Messenger.createButtonTemplate(text, buttons, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/generic
sendGenericTemplate = (
sendGenericTemplate(
recipient: UserID | Recipient,

@@ -815,6 +853,7 @@ elements: Array<TemplateElement>,

} = {}
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createGenericTemplate(elements, {
...options,
image_aspect_ratio,

@@ -824,5 +863,6 @@ }),

);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/list
sendListTemplate = (
sendListTemplate(
recipient: UserID | Recipient,

@@ -839,6 +879,7 @@ elements: Array<TemplateElement>,

} = {}
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createListTemplate(elements, buttons, {
...options,
top_element_style,

@@ -848,113 +889,94 @@ }),

);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/open-graph
sendOpenGraphTemplate = (
sendOpenGraphTemplate(
recipient: UserID | Recipient,
elements: Array<OpenGraphElement>,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createOpenGraphTemplate(elements),
Messenger.createOpenGraphTemplate(elements, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/receipt
sendReceiptTemplate = (
sendReceiptTemplate(
recipient: UserID | Recipient,
attrs: ReceiptAttributes,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createReceiptTemplate(attrs),
Messenger.createReceiptTemplate(attrs, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/media
sendMediaTemplate = (
sendMediaTemplate(
recipient: UserID | Recipient,
elements: Array<MediaElement>,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createMediaTemplate(elements),
Messenger.createMediaTemplate(elements, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#boarding_pass
sendAirlineBoardingPassTemplate = (
sendAirlineBoardingPassTemplate(
recipient: UserID | Recipient,
attrs: AirlineBoardingPassAttributes,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createAirlineBoardingPassTemplate(attrs),
Messenger.createAirlineBoardingPassTemplate(attrs, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#check_in
sendAirlineCheckinTemplate = (
sendAirlineCheckinTemplate(
recipient: UserID | Recipient,
attrs: AirlineCheckinAttributes,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createAirlineCheckinTemplate(attrs),
Messenger.createAirlineCheckinTemplate(attrs, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#itinerary
sendAirlineItineraryTemplate = (
sendAirlineItineraryTemplate(
recipient: UserID | Recipient,
attrs: AirlineItineraryAttributes,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
Messenger.createAirlineItineraryTemplate(attrs),
Messenger.createAirlineItineraryTemplate(attrs, options),
options
);
}
// https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline#update
sendAirlineFlightUpdateTemplate = (
sendAirlineFlightUpdateTemplate(
recipient: UserID | Recipient,
attrs: AirlineFlightUpdateAttributes,
options?: SendOption
): Promise<SendMessageSucessResponse> =>
this.sendMessage(
recipient,
Messenger.createAirlineFlightUpdateTemplate(attrs),
options
);
/**
* Quick Replies
*
* https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies
*/
sendQuickReplies = (
recipient: UserID | Recipient,
textOrAttachment: TextOrAttachment,
quickReplies: Array<QuickReply>,
options?: SendOption
): Promise<SendMessageSucessResponse> => {
warning(
false,
'`sendQuickReplies` is deprecated. Use send message methods with `options.quick_replies` instead.'
);
validateQuickReplies(quickReplies);
): Promise<SendMessageSucessResponse> {
return this.sendMessage(
recipient,
{
...textOrAttachment,
quick_replies: quickReplies,
},
Messenger.createAirlineFlightUpdateTemplate(attrs, options),
options
);
};
}

@@ -966,7 +988,7 @@ /**

*/
sendSenderAction = (
sendSenderAction(
idOrRecipient: UserID | Recipient,
action: SenderAction,
{ access_token: customAccessToken }: { access_token?: string } = {}
): Promise<SendSenderActionResponse> => {
): Promise<SendSenderActionResponse> {
const recipient =

@@ -983,21 +1005,24 @@ typeof idOrRecipient === 'string'

});
};
}
markSeen = (
markSeen(
recipient: UserID | Recipient,
options?: Object = {}
): Promise<SendSenderActionResponse> =>
this.sendSenderAction(recipient, 'mark_seen', options);
): Promise<SendSenderActionResponse> {
return this.sendSenderAction(recipient, 'mark_seen', options);
}
typingOn = (
typingOn(
recipient: UserID | Recipient,
options?: Object = {}
): Promise<SendSenderActionResponse> =>
this.sendSenderAction(recipient, 'typing_on', options);
): Promise<SendSenderActionResponse> {
return this.sendSenderAction(recipient, 'typing_on', options);
}
typingOff = (
typingOff(
recipient: UserID | Recipient,
options?: Object = {}
): Promise<SendSenderActionResponse> =>
this.sendSenderAction(recipient, 'typing_off', options);
): Promise<SendSenderActionResponse> {
return this.sendSenderAction(recipient, 'typing_off', options);
}

@@ -1009,6 +1034,6 @@ /**

*/
sendBatch = (
sendBatch(
batch: Array<BatchItem>,
{ access_token: customAccessToken }: { access_token?: string } = {}
): Promise<Array<SendMessageSucessResponse>> => {
): Promise<Array<SendMessageSucessResponse>> {
invariant(

@@ -1036,9 +1061,9 @@ batch.length <= 50,

});
return axios
.post('https://graph.facebook.com/', {
return this._axios
.post('/', {
access_token: customAccessToken || this._accessToken,
batch: bodyEncodedbatch,
})
.then(res => res.data);
};
.then(res => res.data, handleError);
}

@@ -1056,7 +1081,7 @@ /**

*/
createMessageCreative = (
createMessageCreative(
messages: Array<Object> = [],
{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
) {
return this._axios
.post(

@@ -1070,2 +1095,3 @@ `/me/message_creatives?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}

@@ -1077,4 +1103,4 @@ /**

*/
sendBroadcastMessage = (messageCreativeId: number, options?: Object = {}) =>
this._axios
sendBroadcastMessage(messageCreativeId: number, options?: Object = {}) {
return this._axios
.post(

@@ -1089,2 +1115,3 @@ `/me/broadcast_messages?access_token=${options.access_token ||

.then(res => res.data, handleError);
}

@@ -1096,4 +1123,4 @@ /**

*/
sendSponsoredMessage = (adAccountId: string, message: Object) =>
this._axios
sendSponsoredMessage(adAccountId: string, message: Object) {
return this._axios
.post(

@@ -1106,2 +1133,3 @@ `/act_${adAccountId}/sponsored_message_ads?access_token=${

.then(res => res.data, handleError);
}

@@ -1119,7 +1147,7 @@ /**

*/
createLabel = (
createLabel(
name: string,
{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
) {
return this._axios
.post(

@@ -1133,2 +1161,3 @@ `/me/custom_labels?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}

@@ -1140,8 +1169,8 @@ /**

*/
associateLabel = (
associateLabel(
userId: UserID,
labelId: number,
{ access_token: customAccessToken }: { access_token: ?string } = {}
) =>
this._axios
) {
return this._axios
.post(

@@ -1155,2 +1184,3 @@ `/${labelId}/label?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}

@@ -1162,8 +1192,8 @@ /**

*/
dissociateLabel = (
dissociateLabel(
userId: UserID,
labelId: number,
{ access_token: customAccessToken }: { access_token: ?string } = {}
) =>
this._axios
) {
return this._axios
.delete(

@@ -1177,2 +1207,3 @@ `/${labelId}/label?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}

@@ -1184,7 +1215,7 @@ /**

*/
getAssociatedLabels = (
getAssociatedLabels(
userId: UserID,
{ access_token: customAccessToken }: { access_token: ?string } = {}
) =>
this._axios
) {
return this._axios
.get(

@@ -1195,2 +1226,3 @@ `/${userId}/custom_labels?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}

@@ -1202,3 +1234,3 @@ /**

*/
getLabelDetails = (labelId: number, options?: Object = {}) => {
getLabelDetails(labelId: number, options?: Object = {}) {
const fields = options.fields ? options.fields.join(',') : 'name';

@@ -1211,3 +1243,3 @@ return this._axios

.then(res => res.data, handleError);
};
}

@@ -1219,3 +1251,3 @@ /**

*/
getLabelList = (options?: Object = {}) => {
getLabelList(options?: Object = {}) {
const fields = options.fields ? options.fields.join(',') : 'name';

@@ -1228,3 +1260,3 @@ return this._axios

.then(res => res.data, handleError);
};
}

@@ -1236,7 +1268,7 @@ /**

*/
deleteLabel = (
deleteLabel(
labelId: number,
{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
) {
return this._axios
.delete(

@@ -1246,2 +1278,3 @@ `/${labelId}?access_token=${customAccessToken || this._accessToken}`

.then(res => res.data, handleError);
}

@@ -1253,9 +1286,9 @@ /**

*/
startReachEstimation = (
startReachEstimation(
customLabelId: number,
{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
) {
return this._axios
.post(
`/broadcast_reach_estimations?access_token=${customAccessToken ||
`/me/broadcast_reach_estimations?access_token=${customAccessToken ||
this._accessToken}`,

@@ -1267,2 +1300,3 @@ {

.then(res => res.data, handleError);
}

@@ -1274,8 +1308,8 @@ /**

*/
getReachEstimate = (
getReachEstimate(
reachEstimationId: number,
{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
.post(
) {
return this._axios
.get(
`/${reachEstimationId}?access_token=${customAccessToken ||

@@ -1285,2 +1319,3 @@ this._accessToken}`

.then(res => res.data, handleError);
}

@@ -1293,7 +1328,7 @@ /**

*/
getBroadcastMessagesSent = (
getBroadcastMessagesSent(
broadcastId: number,
{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
) {
return this._axios
.post(

@@ -1304,2 +1339,3 @@ `/${broadcastId}/insights/messages_sent?access_token=${customAccessToken ||

.then(res => res.data.data, handleError);
}

@@ -1311,7 +1347,7 @@ /**

*/
uploadAttachment = (
uploadAttachment(
type: 'audio' | 'image' | 'video' | 'file',
attachment: string | FileData,
options?: UploadOption = {}
) => {
) {
const args = [];

@@ -1362,12 +1398,16 @@

.then(res => res.data, handleError);
};
}
uploadAudio = (attachment: string | FileData, options?: UploadOption) =>
this.uploadAttachment('audio', attachment, options);
uploadImage = (attachment: string | FileData, options?: UploadOption) =>
this.uploadAttachment('image', attachment, options);
uploadVideo = (attachment: string | FileData, options?: UploadOption) =>
this.uploadAttachment('video', attachment, options);
uploadFile = (attachment: string | FileData, options?: UploadOption) =>
this.uploadAttachment('file', attachment, options);
uploadAudio(attachment: string | FileData, options?: UploadOption) {
return this.uploadAttachment('audio', attachment, options);
}
uploadImage(attachment: string | FileData, options?: UploadOption) {
return this.uploadAttachment('image', attachment, options);
}
uploadVideo(attachment: string | FileData, options?: UploadOption) {
return this.uploadAttachment('video', attachment, options);
}
uploadFile(attachment: string | FileData, options?: UploadOption) {
return this.uploadAttachment('file', attachment, options);
}

@@ -1379,4 +1419,4 @@ /**

*/
generateMessengerCode = (options: Object = {}) =>
this._axios
generateMessengerCode(options: Object = {}) {
return this._axios
.post(

@@ -1391,2 +1431,3 @@ `/me/messenger_codes?access_token=${options.access_token ||

.then(res => res.data, handleError);
}

@@ -1404,3 +1445,3 @@ /**

*/
passThreadControl = (
passThreadControl(
recipientId: string,

@@ -1410,4 +1451,4 @@ targetAppId: number,

{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
) {
return this._axios
.post(

@@ -1423,8 +1464,16 @@ `/me/pass_thread_control?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}
passThreadControlToPageInbox = (
passThreadControlToPageInbox(
recipientId: string,
metadata?: string,
options?: Object = {}
) => this.passThreadControl(recipientId, 263902037430900, metadata, options);
) {
return this.passThreadControl(
recipientId,
263902037430900,
metadata,
options
);
}

@@ -1436,8 +1485,8 @@ /**

*/
takeThreadControl = (
takeThreadControl(
recipientId: string,
metadata?: string,
{ access_token: customAccessToken }: { access_token: ?string } = {}
) =>
this._axios
) {
return this._axios
.post(

@@ -1452,4 +1501,27 @@ `/me/take_thread_control?access_token=${customAccessToken ||

.then(res => res.data, handleError);
}
/**
* Request Thread Control
*
* https://developers.facebook.com/docs/messenger-platform/handover-protocol/request-thread-control/
*/
requestThreadControl(
recipientId: string,
metadata?: string,
{ access_token: customAccessToken }: { access_token: ?string } = {}
) {
return this._axios
.post(
`/me/request_thread_control?access_token=${customAccessToken ||
this._accessToken}`,
{
recipient: { id: recipientId },
metadata,
}
)
.then(res => res.data, handleError);
}
/**
* Secondary Receivers List

@@ -1459,6 +1531,6 @@ *

*/
getSecondaryReceivers = ({
getSecondaryReceivers({
access_token: customAccessToken,
}: { access_token: ?string } = {}) =>
this._axios
}: { access_token: ?string } = {}) {
return this._axios
.get(

@@ -1469,2 +1541,3 @@ `/me/secondary_receivers?fields=id,name&access_token=${customAccessToken ||

.then(res => res.data.data, handleError);
}

@@ -1476,7 +1549,4 @@ /**

*/
getInsights = (
metrics: Array<InsightMetric>,
options?: InsightOptions = {}
) =>
this._axios
getInsights(metrics: Array<InsightMetric>, options?: InsightOptions = {}) {
return this._axios
.get(

@@ -1490,23 +1560,46 @@ `/me/insights/?${querystring.stringify({

.then(res => res.data.data, handleError);
}
getDailyUniqueActiveThreadCounts = (options?: Object = {}) =>
this.getInsights(['page_messages_active_threads_unique'], options);
getActiveThreads(options?: Object = {}) {
return this.getInsights(
['page_messages_active_threads_unique'],
options
).then(result => result[0]);
}
getBlockedConversations = (options?: Object = {}) =>
this.getInsights(['page_messages_blocked_conversations_unique'], options);
getBlockedConversations(options?: Object = {}) {
return this.getInsights(
['page_messages_blocked_conversations_unique'],
options
).then(result => result[0]);
}
getReportedConversations = (options?: Object = {}) =>
this.getInsights(['page_messages_reported_conversations_unique'], options);
getReportedConversations(options?: Object = {}) {
return this.getInsights(
['page_messages_reported_conversations_unique'],
options
).then(result => result[0]);
}
getReportedConversationsByReportType = (options?: Object = {}) =>
this.getInsights(['page_messages_blocked_conversations_unique'], options);
getReportedConversationsByReportType(options?: Object = {}) {
return this.getInsights(
['page_messages_reported_conversations_by_report_type_unique'],
options
).then(result => result[0]);
}
getDailyUniqueConversationCounts = () => {
warning(
false,
'page_messages_feedback_by_action_unique is deprecated as of November 7, 2017.\nThis metric will be removed in Graph API v2.12.'
);
return this.getInsights(['page_messages_feedback_by_action_unique']);
};
getOpenConversations(options?: Object = {}) {
return this.getInsights(
['page_messages_open_conversations_unique'],
options
).then(result => result[0]);
}
getNewConversations(options?: Object = {}) {
return this.getInsights(
['page_messages_new_conversations_unique'],
options
).then(result => result[0]);
}
/**

@@ -1517,7 +1610,7 @@ * Built-in NLP API

*/
setNLPConfigs = (
setNLPConfigs(
config: MessengerNLPConfig = {},
{ access_token: customAccessToken }: { access_token?: string } = {}
) =>
this._axios
) {
return this._axios
.post(`/me/nlp_configs?${querystring.stringify(config)}`, {

@@ -1527,8 +1620,12 @@ access_token: customAccessToken || this._accessToken,

.then(res => res.data, handleError);
}
enableNLP = (options?: Object = {}) =>
this.setNLPConfigs({ nlp_enabled: true }, options);
disableNLP = (options?: Object = {}) =>
this.setNLPConfigs({ nlp_enabled: false }, options);
enableNLP(options?: Object = {}) {
return this.setNLPConfigs({ nlp_enabled: true }, options);
}
disableNLP(options?: Object = {}) {
return this.setNLPConfigs({ nlp_enabled: false }, options);
}
/**

@@ -1539,35 +1636,15 @@ * Logging Custom Events

*/
logCustomEvents = ({
logCustomEvents({
app_id,
appId,
page_id,
pageId,
page_scoped_user_id,
userId,
events,
access_token: customAccessToken,
}: {
app_id?: number,
appId?: number,
page_id?: number,
pageId?: number,
page_scoped_user_id?: UserID,
userId?: UserID,
app_id: number,
page_id: number,
page_scoped_user_id: UserID,
events: Array<Object>,
access_token?: string,
}) => {
// FIXME: remove in v0.7
warning(!appId, '`appId` is deprecated. Use `app_id` instead.');
warning(!pageId, '`pageId` is deprecated. Use `page_id` instead.');
warning(
!userId,
'`userId` is deprecated. Use `page_scoped_user_id` instead.'
);
/* eslint-disable no-param-reassign */
app_id = ((app_id || appId: any): number);
page_id = ((page_id || pageId: any): number);
page_scoped_user_id = ((page_scoped_user_id || userId: any): string);
/* eslint-enable no-param-reassign */
}) {
return this._axios

@@ -1588,3 +1665,3 @@ .post(

.then(res => res.data, handleError);
};
}

@@ -1594,3 +1671,3 @@ /**

*/
getUserField = ({
getUserField({
field,

@@ -1609,3 +1686,3 @@ user_id,

access_token?: string,
}) => {
}) {
const accessToken = customAccessToken || this._accessToken;

@@ -1627,3 +1704,3 @@

.then(res => res.data, handleError);
};
}

@@ -1633,3 +1710,3 @@ /**

*/
getIdsForApps = ({
getIdsForApps({
user_id,

@@ -1646,4 +1723,4 @@ app_secret,

access_token?: string,
}) =>
this.getUserField({
}) {
return this.getUserField({
field: 'ids_for_apps',

@@ -1656,2 +1733,3 @@ user_id,

});
}

@@ -1661,3 +1739,3 @@ /**

*/
getIdsForPages = ({
getIdsForPages({
user_id,

@@ -1674,4 +1752,4 @@ app_secret,

access_token?: string,
}) =>
this.getUserField({
}) {
return this.getUserField({
field: 'ids_for_pages',

@@ -1684,2 +1762,3 @@ user_id,

});
}
}

@@ -29,10 +29,2 @@ /* @flow */

export type TextOrAttachment =
| {
text: string,
}
| {
attachment: Attachment,
};
export type QuickReply = {

@@ -77,3 +69,4 @@ content_type: 'text' | 'location',

| 'page_messages_reported_conversations_by_report_type_unique'
| 'page_messages_feedback_by_action_unique';
| 'page_messages_open_conversations_unique'
| 'page_messages_new_conversations_unique';

@@ -83,2 +76,3 @@ export type InsightOptions = {

until?: number,
access_token?: string,
};

@@ -95,2 +89,3 @@

filename?: string,
is_reusable?: boolean,
access_token?: string,

@@ -97,0 +92,0 @@ };

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc