Skip to content

Instantly share code, notes, and snippets.

@lbrenman

lbrenman/fbwebhook.js

Last active Oct 31, 2017
Embed
What would you like to do?
Hello API Builder FB Chatbot
var Arrow = require('arrow');
var fbwebhook = Arrow.API.extend({
group: 'webhooks',
path: '/api/fbwebhook',
method: 'GET',
description: 'this is an api that shows how to handle requests from the FB chatbot',
parameters: {
'hub.mode': {
description: 'hub.mode',
optional: true
},
'hub.challenge': {
description: 'hub.challenge',
optional: true
},
'hub.verify_token': {
description: 'hub.verify_token',
optional: true
}
},
action: function(req, resp, next) {
console.log('fbwebhook - fbwebhook API called (GET)');
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === 'XXX') {
console.log("Validating webhook");
// resp.status(200).send(req.query['hub.challenge']);
resp.response.status(200);
resp.send(req.query['hub.challenge']);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
resp.response.status(403);
}
next();
}
});
module.exports = fbwebhook;
var Arrow = require('arrow');
var request = require('request');
function sendGenericMessage(recipientId, messageText) {
// To be expanded in later sections
}
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: 'EAAEtqD7zxecBAGngZBYRgetyohDU9ZBVfFyd1XzkFRzeZCnvy4ebNn41dUMNz0ZC5gbpOU8u23jMK0ZC7YDuFCF6I3VzYDG3fQTlSazH8ZBtvOHjeE0hA9dtZAFIqYDuwxdOflqZCfoJAT067bVOor12rDWjKGcte61RZB8jRM36cZAgZDZD' },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
// If we receive a text message, check to see if it matches a keyword
// and send back the example. Otherwise, just echo the text we received.
switch (messageText) {
case 'generic':
sendGenericMessage(senderID);
break;
default:
sendTextMessage(senderID, "The API Builder FB Chatbot detected that you wrote: "+messageText);
}
} else if (messageAttachments) {
sendTextMessage(senderID, "Message with attachment received");
}
}
var fbwebhookp = Arrow.API.extend({
group: 'webhooks',
path: '/api/fbwebhook',
method: 'POST',
description: 'this is an api that shows how to handle requests from the FB chatbot',
parameters: {
'object': {
description: 'object',
optional: true
},
'entry': {
description: 'entry',
optional: true
}
},
action: function(req, resp, next) {
console.log('fbwebhook - fbwebhook API called (POST)');
var data = req.body;
// Make sure this is a page subscription
if (data.object === 'page') {
// Iterate over each entry - there may be multiple if batched
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
// Iterate over each messaging event
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else {
console.log("Webhook received unknown event: ", event);
}
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know
// you've successfully received the callback. Otherwise, the request
// will time out and we will keep trying to resend.
resp.response.status(200);
next();
} else {
resp.response.status(200);
next();
}
}
});
module.exports = fbwebhookp;

Hello FB Chat Bot

Instructions:

  • Create a new API Builder Project

  • Disable Auth (set auth to none in default.js)

  • Run the Project (appc run)

  • Go to http://localhost:8080/console

  • Use ngrok so your API will be accessible by FB

  • Follow the FB Messenger Quick Start Guide here: https://developers.facebook.com/docs/messenger-platform/getting-started/quick-start

    • Create a new FB app here - DemoBot
    • Create a new FB Page here - Company, Organization or Institution, Engineering, DemoBot
    • My page ended up here
    • In the developer portal, go to the app page and add a product: messenger
  • Stop here since you will need API Builder APIs to enter in the Webhook section

  • Place fbwebhook.js and fbwebhookp.js in the /api folder

  • Run the Project (appc run)

  • Go to http://localhost:8080/console and show the two APIs (webhooks)

  • In the Webhooks section, click "Setup Webhooks"

  • Enter https://26bc6f28.ngrok.io/api/fbwebhook for the webhook URL

  • Enter a URL for a webhook, enter a Verify Token (XXX) and select messages and messaging_postbacks under Subscription Fields

    • See the API Builder console log for
    fbwebhook - fbwebhook API called (GET)
    Validating webhook
  • Since this worked properly, you should see a green check mark that the webhook is complete

  • Review the code for the fbwebhook GET and the validation and the token

  • In the Token Generation section, select your Page (created above)

  • Copy page token to clipboard

  • Paste the access token in the callSendAPI() method in the request options

  • Show how the code is mainly copy and pasted from the FB Messenger Quick Start Guide

  • Show how the response is just an echo of what was received

  • Restart the API Builder app

  • In the Webhooks section, you can subscribe the webhook for a specific page (Demobot) and click subscribe

  • Go to the FB Demobot home page (https://www.facebook.com/DemoBot-1437442156352884/)

  • In the lower right hand corner, bring up the chat window and search for Demobot and click on it

  • You should see a "Demobot is active now. Start a conversation"

  • Type "Hello Demobot"

  • Should see the response: "The API Builder Chatbot detected that you wrote: Hello Demobot"

  • See the console log for the following:

Received message for user 1896462583703774 and page 1437442156352884 at 1507323189868 with message:
{"mid":"mid.$cAAUbWLKh6iZlJLvibFe83aaLeYVd","seq":6143,"text":"Hi"}
Successfully sent generic message with id mid.$cAAUbWLKh6iZlJLvlUle83adD5LKX to recipient 1896462583703774

TADA!

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.