import request from 'request-promise';

const apiURL = 'https://graph.facebook.com/v2.7/';

pageSubscribe(pageAccessToken)

Subscribe your facebook app/bot to a facebook page's webhook updates. You need to call this for each page you want to receive messages from.

Parameters

const pageSubscribe = pageAccessToken => {
    const requestOptions = {
        uri: `${apiURL}me/subscribed_apps`,
        method: 'POST',
        qs: {
            access_token: pageAccessToken
        }
    };
    return new Promise(resolve =>
        request(requestOptions)
        .then(result => resolve(result))
        .catch(e => {
            console.error(e.message);
            return resolve(e.message);
        })
    );
};

sendTextMessage(message, pageAccessToken)

Send a text message with your Facebook Messenger app/bot.

Parameters

const sendTextMessage = (message, pageAccessToken) => {
    const { attachment, text } = message;
    const croppedText = text
        ? text.substring(0, 319) + (message.text.length > 320 ? '…' : '')
        : null;
    const requestOptions = {
        uri: `${apiURL}me/messages`,
        qs: {
            access_token: pageAccessToken
        },
        method: 'POST',
        body: {
            recipient: {
                id: message.userId
            },
            message: {
                text: croppedText,
                attachment
            }
        },
        json: true
    };
    return request(requestOptions);
};

senderActions(status, userId, pageAccessToken)

Set typing indicators or send read receipts to your Facebook Messenger app/bot.

Parameters

const senderActions = (status, userId, pageAccessToken) => {
    const requestOptions = {
        uri: `${apiURL}me/messages`,
        qs: {
            access_token: pageAccessToken
        },
        method: 'POST',
        body: {
            recipient: {
                id: userId
            },
            sender_action: status
        },
        json: true
    };
    return request(requestOptions);
};

quickRepliesText(text, attachment, pageAccessToken)

Send a quick replies message with your Facebook Messenger app/bot.

Parameters

const quickRepliesText = (text, attachment, userId, pageAccessToken) => {
    const requestOptions = {
        uri: `${apiURL}me/messages`,
        qs: {
            access_token: pageAccessToken
        },
        method: 'POST',
        body: {
            recipient: {
                id: userId
            },
            message: {
                text,
                quick_replies: attachment
            }
        },
        json: true
    };
    return request(requestOptions);
};

userInfo(userId, pageAccessToken)

Retrieves user information, first name, last name, profile pic, locale, time zone and gender, from Facebook's User Profile API

Parameters

const userInfo = (userId, pageAccessToken) => new Promise(resolve => request({
    uri: `${apiURL}${userId}`,
    qs: {
        fields: 'first_name,last_name,profile_pic,locale,timezone,gender',
        access_token: pageAccessToken
    }
}).then(body =>
    resolve(JSON.parse(body))
));

threadSettings(options, pageId, pageAccessToken)

Generic method for the various thread settings that can be set, such as Greeting Text, Get Start Button or Persistent Menu

A helper function to make graph api calls to thread_settings endpoint.

const threadSettings = ({ type, state, text, cta }, pageId, pageAccessToken) => {
    const requestOptions = {
        uri: `${apiURL}${pageId}/thread_settings`,
        qs: {
            access_token: pageAccessToken
        },
        method: 'POST',
        json: true
    };
    if (type === 'greeting') {
        return request({
            ...requestOptions,
            body: {
                setting_type: type,
                greeting: {
                    text
                }
            }
        });
    }
    return new Promise(resolve =>
        request({
            ...requestOptions,
            body: {
                thread_state: state,
                setting_type: type,
                call_to_actions: cta
            }
        })
        .then(response => {
            console.log('DEBUG: threadSettings response headers', response.headers);
            return resolve(response);
        })
        .catch(error => {
            console.log('DEBUG: threadSettings error headers', error.response.headers);
            return resolve(error.message);
        })
    );
};

setWelcomeMessage(message, pageId, pageAccessToken)

Change the Welcome Message for the messenger of a page. A helper function to make graph api calls to set new thread state message setting.

const setWelcomeMessage = (message, pageId, pageAccessToken) => threadSettings(
    {
        type: 'call_to_actions',
        state: 'new_thread',
        cta: [{
            payload: JSON.stringify({
                type: 'legacy-welcome',
                message
            })
        }]
    },
    pageId,
    pageAccessToken
);

export {
    pageSubscribe,
    sendTextMessage,
    userInfo,
    setWelcomeMessage,
    threadSettings,
    senderActions,
    quickRepliesText
};
h