Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Amazon Pinpoint - Custom Channel Lambda function (Node.js)
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
You can’t perform that action at this time.