Tuesday, September 19, 2017

Facebook Bot for Multiple Facebook Pages

When you call the Facebook Send API, you can pass a page access token through the access_tokenparameter. You can specify which page to direct your message by modifying this access token. To know which page initiated the message, you can access the id field of the entry of the message post.
app.post('/webhook', (req, res) => {
    const data = req.body

    // Make sure this is a page subscription
   if (data.object === 'page') {
       // Iterate over each entry
       data.entry.forEach((pageEntry) => {
           // get the pageId
           const pageId = pageEntry.id
           ...
You would then need to maintain an object mapping page ids to the access token associated with each page id:
const accessTokens = {
    myPageId1: 'myPageAccessToken1',
    myPageId2: 'myPageAccessToken2',
}
Then when sending the response, just specify the corresponding page access_token
const callSendAPI = (pageId, messageData) =>
    rp({
        uri: 'https://graph.facebook.com/v2.8/me/messages',
        qs: { access_token: accessTokens[pageId] },
        method: 'POST',
        body: messageData,
        json: true,
     })

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Data Structures : Tree Traversals

(Week 2) Tree traversals are one of the most important algorithm in computer science because sometimes we don't have lin...