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.6.3 to 0.6.4

lib/MessengerBatch.js

2

lib/index.js
'use strict';
var _Messenger = require('./Messenger');var _Messenger2 = _interopRequireDefault(_Messenger);
var _MessengerBatch = require('./MessengerBatch');var _MessengerBatch2 = _interopRequireDefault(_MessengerBatch);
var _MessengerClient = require('./MessengerClient');var _MessengerClient2 = _interopRequireDefault(_MessengerClient);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}

@@ -8,2 +9,3 @@

Messenger: _Messenger2.default,
MessengerBatch: _MessengerBatch2.default,
MessengerClient: _MessengerClient2.default };

59

lib/Messenger.js

@@ -1,52 +0,29 @@

'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;};
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _warning = require('warning');var _warning2 = _interopRequireDefault(_warning);
var _MessengerBatch = require('./MessengerBatch');var _MessengerBatch2 = _interopRequireDefault(_MessengerBatch);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
function createRequest(...args) {
(0, _warning2.default)(
false,
'`Messenger.createRequest` will breaking and become part of message creation API in v0.7. For batch usage, use `MessengerBatch.createRequest` instead.');
return _MessengerBatch2.default.createRequest(...args);
}
function createMessage(...args) {
(0, _warning2.default)(
false,
'`Messenger.createMessage` will breaking and become part of message creation API in v0.7. For batch usage, use `MessengerBatch.createMessage` instead.');
function createRequest(body) {
return {
method: 'POST',
relative_url: 'me/messages',
body };
return _MessengerBatch2.default.createMessage(...args);
}
function createMessage(
idOrRecipient,
message,
options = {})
{
const recipient =
typeof idOrRecipient === 'string' ?
{
id: idOrRecipient } :
function createText(...args) {
(0, _warning2.default)(
false,
'`Messenger.createText` will breaking and become part of message creation API in v0.7. For batch usage, use `MessengerBatch.createText` instead.');
idOrRecipient;
let messageType = 'UPDATE';
if (options.messaging_type) {
messageType = options.messaging_type;
} else if (options.tag) {
messageType = 'MESSAGE_TAG';
}
return createRequest(_extends({
messaging_type: messageType,
recipient,
message },
options));
return _MessengerBatch2.default.createText(...args);
}
function createText(
recipient,
text,
options)
{
return createMessage(recipient, { text }, options);
}
const Messenger = {

@@ -53,0 +30,0 @@ createRequest,

'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 _querystring = require('querystring');var _querystring2 = _interopRequireDefault(_querystring);
var _crypto = require('crypto');var _crypto2 = _interopRequireDefault(_crypto);

@@ -11,3 +13,3 @@ var _axios = require('axios');var _axios2 = _interopRequireDefault(_axios);

var _isPlainObject = require('is-plain-object');var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _warning = require('warning');var _warning2 = _interopRequireDefault(_warning);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;}
var _warning = require('warning');var _warning2 = _interopRequireDefault(_warning);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 */

@@ -144,6 +146,5 @@

/**
* Get User Profile
* Create Subscription
*
* 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
* https://developers.facebook.com/docs/graph-api/reference/app/subscriptions
*/

@@ -158,7 +159,2 @@

/**
* Messenger Profile
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api
*/

@@ -194,2 +190,8 @@

/**
* 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
*/

@@ -203,8 +205,6 @@

/**
* Get Started Button
* Messenger Profile
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/get-started-button
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api
*/

@@ -236,7 +236,2 @@

/**
* Persistent Menu
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/persistent-menu
*/

@@ -257,2 +252,7 @@

/**
* Get Started Button
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/get-started-button
*/

@@ -283,2 +283,7 @@

/**
* Persistent Menu
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/persistent-menu
*/

@@ -288,7 +293,2 @@

/**
* Greeting Text
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/greeting
*/

@@ -330,6 +330,10 @@

/**
* Whitelisted Domains
* Greeting Text
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/domain-whitelisting
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/greeting
*/

@@ -359,6 +363,19 @@

/**
* Account Linking URL
* Whitelisted Domains
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/account-linking-url
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/domain-whitelisting
*/

@@ -389,5 +406,5 @@

/**
* Payment Settings
* Account Linking URL
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/payment-settings
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/account-linking-url
*/

@@ -417,2 +434,7 @@

/**
* Payment Settings
*
* https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/payment-settings
*/

@@ -446,7 +468,30 @@

/**
* 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
*/

@@ -484,6 +529,6 @@

/**
* 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
*/

@@ -523,6 +568,6 @@

/**
* 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
*/

@@ -539,6 +584,6 @@

/**
* 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

@@ -1487,3 +1532,117 @@

* https://developers.facebook.com/docs/app-events/bots-for-messenger#logging-custom-events
*/}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.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
*/
/**
* 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
*/
/**
* 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: customAccessToken }) => this._axios.post(`/${appId}/subscriptions?access_token=${customAccessToken || this._accessToken}`, { 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>

@@ -1497,21 +1656,13 @@ 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';}const quickReplies = options.quick_replies,otherOptions = _objectWithoutProperties(options, ['quick_replies']);if (quickReplies) {validateQuickReplies(quickReplies);message.quick_replies = quickReplies; // eslint-disable-line no-param-reassign

return this.sendAttachmentFormData(recipient, attachment, file, options);};this.sendTemplate = (recipient, payload, options) => this.sendAttachment(recipient, { type: 'template', payload }, options);this.sendButtonTemplate = (recipient, text, buttons, options) => this.sendTemplate(recipient, { template_type: 'button', text, buttons }, options);this.sendGenericTemplate = (recipient, elements, options = {}) => this.sendTemplate(recipient, { template_type: 'generic', elements, image_aspect_ratio: options.image_aspect_ratio || 'horizontal' }, (0, _lodash2.default)(options, ['image_aspect_ratio']));this.sendListTemplate = (recipient, elements, buttons, options = {}) => this.sendTemplate(recipient, { template_type: 'list', elements, buttons, top_element_style: options.top_element_style || 'large' }, (0, _lodash2.default)(options, ['top_element_style']));this.sendOpenGraphTemplate = (recipient, elements, options) => this.sendTemplate(recipient, { template_type: 'open_graph', elements }, options);this.sendReceiptTemplate = (recipient, attrs, options) => this.sendTemplate(recipient, _extends({ template_type: 'receipt' }, attrs), options);this.sendMediaTemplate = (recipient, elements, options) => this.sendTemplate(recipient, { template_type: 'media', elements }, options);this.sendAirlineBoardingPassTemplate = (recipient, attrs, options) => this.sendTemplate(recipient, _extends({ template_type: 'airline_boardingpass' }, attrs), options);this.sendAirlineCheckinTemplate = (recipient, attrs, options) => this.sendTemplate(recipient, _extends({ template_type: 'airline_checkin' }, attrs), options);this.sendAirlineItineraryTemplate = (recipient, attrs, options) => this.sendTemplate(recipient, _extends({ template_type: 'airline_itinerary' }, attrs), options);this.sendAirlineFlightUpdateTemplate = (recipient, attrs, options) => this.sendTemplate(recipient, _extends({ template_type: 'airline_update' }, 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 = ({ appId, pageId, userId, events, access_token: customAccessToken }) =>
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._axios.
post(
`/${appId}/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: pageId,
page_scoped_user_id: userId }).
then(res => res.data, handleError);};
this.getUserField({
field: 'ids_for_pages',
user_id,
app_secret,
app,
page,
access_token });};
{
"name": "messaging-api-messenger",
"description": "Messaging API client for Messenger",
"version": "0.6.3",
"version": "0.6.4",
"engines": {

@@ -6,0 +6,0 @@ "node": ">=6"

/* @flow */
import Messenger from './Messenger';
import MessengerBatch from './MessengerBatch';
import MessengerClient from './MessengerClient';

@@ -8,3 +9,4 @@

Messenger,
MessengerBatch,
MessengerClient,
};

@@ -1,50 +0,27 @@

/* @flow */
import warning from 'warning';
import type {
UserID,
Recipient,
SendOption,
Message,
BatchItem,
} from './MessengerTypes';
import MessengerBatch from './MessengerBatch';
function createRequest(body: Object): BatchItem {
return {
method: 'POST',
relative_url: 'me/messages',
body,
};
function createRequest(...args) {
warning(
false,
'`Messenger.createRequest` will breaking and become part of message creation API in v0.7. For batch usage, use `MessengerBatch.createRequest` instead.'
);
return MessengerBatch.createRequest(...args);
}
function createMessage(
idOrRecipient: UserID | Recipient,
message: Message,
options?: SendOption = {}
): BatchItem {
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 createRequest({
messaging_type: messageType,
recipient,
message,
...options,
});
function createMessage(...args) {
warning(
false,
'`Messenger.createMessage` will breaking and become part of message creation API in v0.7. For batch usage, use `MessengerBatch.createMessage` instead.'
);
return MessengerBatch.createMessage(...args);
}
function createText(
recipient: UserID | Recipient,
text: string,
options?: SendOption
): BatchItem {
return createMessage(recipient, { text }, options);
function createText(...args) {
warning(
false,
'`Messenger.createText` will breaking and become part of message creation API in v0.7. For batch usage, use `MessengerBatch.createText` instead.'
);
return MessengerBatch.createText(...args);
}

@@ -51,0 +28,0 @@

/* @flow */
/* eslint-disable camelcase */
import querystring from 'querystring';
import crypto from 'crypto';

@@ -143,2 +145,45 @@ import axios from 'axios';

/**
* 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: customAccessToken,
}: {
app_id: string,
object?: 'user' | 'page' | 'permissions' | 'payments',
callback_url: string,
fields?: Array<string>,
include_values?: boolean,
verify_token: string,
access_token?: string,
}): Promise<{ success: boolean }> =>
this._axios
.post(
`/${appId}/subscriptions?access_token=${customAccessToken ||
this._accessToken}`,
{
object,
callback_url,
fields: fields.join(','),
include_values,
verify_token,
}
)
.then(res => res.data, handleError);
/**
* Get User Profile

@@ -1473,4 +1518,7 @@ *

logCustomEvents = ({
app_id,
appId,
page_id,
pageId,
page_scoped_user_id,
userId,

@@ -1480,11 +1528,28 @@ events,

}: {
appId: number,
pageId: number,
userId: UserID,
app_id?: number,
appId?: number,
page_id?: number,
pageId?: number,
page_scoped_user_id?: UserID,
userId?: UserID,
events: Array<Object>,
access_token?: string,
}) =>
this._axios
}) => {
// 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
.post(
`/${appId}/activities?access_token=${customAccessToken ||
`/${app_id}/activities?access_token=${customAccessToken ||
this._accessToken}`,

@@ -1497,7 +1562,94 @@ {

extinfo: JSON.stringify(['mb1']),
page_id: pageId,
page_scoped_user_id: userId,
page_id,
page_scoped_user_id,
}
)
.then(res => res.data, handleError);
};
/**
* https://developers.facebook.com/docs/messenger-platform/identity/id-matching#examples
*/
getUserField = ({
field,
user_id,
app_secret,
app,
page,
access_token: customAccessToken,
}: {
field: string,
user_id: string,
app_secret: string,
app?: string,
page?: string,
access_token?: string,
}) => {
const accessToken = customAccessToken || this._accessToken;
// $appsecret_proof= hash_hmac('sha256', $access_token, $app_secret);
const appsecretProof = crypto
.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);
};
/**
* 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,
}: {
user_id: string,
app_secret: string,
app?: string,
page?: string,
access_token?: string,
}) =>
this.getUserField({
field: 'ids_for_apps',
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
*/
getIdsForPages = ({
user_id,
app_secret,
app,
page,
access_token,
}: {
user_id: string,
app_secret: string,
app?: string,
page?: string,
access_token?: string,
}) =>
this.getUserField({
field: 'ids_for_pages',
user_id,
app_secret,
app,
page,
access_token,
});
}

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