Skip to content

Instantly share code, notes, and snippets.

@emmaodia
Last active January 8, 2019 02:53
Show Gist options
  • Save emmaodia/28d5962a343344875e0d8ec15ed93474 to your computer and use it in GitHub Desktop.
Save emmaodia/28d5962a343344875e0d8ec15ed93474 to your computer and use it in GitHub Desktop.
Facebook Messenger Bot payload for basic text message replies from the Bot.
'use strict';
// Imports dependencies and set up http server
const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const
express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
app = express().use(bodyParser.json()); // creates express http server
// Sets server port and logs message on success
app.listen(process.env.PORT || 1337, () => console.log('webhook is listening'));
/// Accepts POST requests at /webhook endpoint
app.post('/webhook', (req, res) => {
// Parse the request body from the POST
let body = req.body;
// Check the webhook event is from a Page subscription
if (body.object === 'page') {
body.entry.forEach(function(entry) {
// Gets the body of the webhook event
let webhook_event = entry.messaging[0];
console.log(webhook_event);
// Get the sender PSID
let sender_psid = webhook_event.id;
console.log('Sender ID: ' + sender_psid);
// Check if the event is a message or postback and
// pass the event to the appropriate handler function
if (webhook_event.message) {
handleMessage(sender_psid, webhook_event.message);
} else if (webhook_event.postback) {
handlePostback(sender_psid, webhook_event.postback);
}
});
// Return a '200 OK' response to all events
res.status(200).send('EVENT_RECEIVED');
} else {
// Return a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
//Landing Page
app.get('/', (req, res, next) => {
res.status(200).json({
message: "ChatBot!"
})
});
// Adds support for GET requests to our webhook
app.get('/webhook', (req, res) => {
// Your verify token. Should be a random string.
let VERIFY_TOKEN = process.env.VERIFY_TOKEN;
// Parse the query params
let mode = req.query['hub.mode'];
let token = req.query['hub.verify_token'];
let challenge = req.query['hub.challenge'];
// Checks if a token and mode is in the query string of the request
if (mode && token) {
// Checks the mode and token sent is correct
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
// Responds with the challenge token from the request
console.log('WEBHOOK_VERIFIED');
res.status(200).send(challenge);
} else {
// Responds with '403 Forbidden' if verify tokens do not match
res.sendStatus(403);
}
}
// res.status(200).json({
// message: "successful GET requests"
// })
});
// Handles messages events
function handleMessage(sender_psid, received_message) {
let response;
// Check if the message contains text
if (received_message.text) {
// Create the payload for a basic text message
response = {
"text": `You sent the message: ${received_message.text}!`
}
}
// Sends the response message
callSendAPI(sender_psid, response);
}
// Handles messaging_postbacks events
function handlePostback(sender_psid, received_postback) {
}
// Sends response messages via the Send API
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"messaging_type": "RESPONSE",
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment