Created
October 9, 2019 13:11
-
-
Save alexcasalboni/824dc8f91b30c6d7dc46818b271ce602 to your computer and use it in GitHub Desktop.
Amazon Pinpoint - Custom Channel Lambda function (Node.js)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require("https"); | |
/* FB configuration */ | |
const FB_ACCESS_TOKEN = "EAF...DZD"; | |
const FB_PSID = "facebookMessengerPsid"; | |
const FB_REQUEST = { | |
host: "graph.facebook.com", | |
path: "/v2.6/me/messages?access_token=" + FB_ACCESS_TOKEN, | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
}; | |
const isFBActive = (user) => | |
user && | |
user.UserAttributes && | |
user.UserAttributes[FB_PSID] | |
exports.handler = async (event, context) => { | |
const messagesToSend = []; | |
if (event.Message && event.Endpoints) { | |
for(const [id, endpoint] of Object.entries(event.Endpoints)) { | |
if (isFBActive(endpoint.User)) { | |
messagesToSend.push(deliver(event.Message, endpoint.User)); | |
} | |
} | |
} | |
await Promise.all(messagesToSend); | |
return { | |
body: "ok", | |
statusCode: 200, | |
}; | |
}; | |
const deliver = (message, user) => { | |
console.log("Sending message for user: ", user.UserId); | |
const requestBody = JSON.stringify({ | |
recipient: { | |
id: user.UserAttributes[FB_PSID][0], | |
}, | |
message: { | |
text: message["smsmessage"]["body"], | |
}, | |
}); | |
return new Promise((resolve, reject) => { | |
const req = https.request(FB_REQUEST, (response) => { | |
let responseBody = ''; | |
response.on('data', chunk => { | |
responseBody += chunk; | |
}); | |
response.on('end', () => { | |
resolve(responseBody); | |
}); | |
response.on('error', (error) => { | |
reject(error); | |
}); | |
response.resume(); | |
}); | |
req.write(requestBody); | |
req.end(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment