├── index.js └── README.md /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var https = require('https'); 4 | 5 | var PAGE_TOKEN = "GET_TOKEN_FROM_FACEBOOK_APP_SETUP"; 6 | 7 | var VERIFY_TOKEN = "my_token"; 8 | 9 | exports.handler = (event, context, callback) => { 10 | 11 | // process GET request 12 | 13 | if(event.params && event.params.querystring){ 14 | var queryParams = event.params.querystring; 15 | 16 | var rVerifyToken = queryParams['hub.verify_token'] 17 | 18 | if (rVerifyToken === VERIFY_TOKEN) { 19 | var challenge = queryParams['hub.challenge'] 20 | callback(null, parseInt(challenge)) 21 | }else{ 22 | callback(null, 'Error, wrong validation token'); 23 | } 24 | 25 | // process POST request 26 | } else { 27 | 28 | var messagingEvents = event.entry[0].messaging; 29 | for (var i = 0; i < messagingEvents.length; i++) { 30 | var messagingEvent = messagingEvents[i]; 31 | 32 | var sender = messagingEvent.sender.id; 33 | if (messagingEvent.message && messagingEvent.message.text) { 34 | var text = messagingEvent.message.text; 35 | console.log("Received a message: " + text); 36 | 37 | sendTextMessage(sender, "Text received, echo: " + text); 38 | 39 | callback(null, "Done") 40 | } 41 | } 42 | 43 | callback(null, event); 44 | } 45 | }; 46 | 47 | function sendDots(senderFbId) { 48 | var json = { 49 | recipient: {id: senderFbId}, 50 | sender_action: "typing_on" 51 | }; 52 | sendAll(json); 53 | } 54 | 55 | function sendTextMessage(senderFbId, text) { 56 | 57 | var json = { 58 | recipient: {id: senderFbId}, 59 | message: {text: text}, 60 | }; 61 | sendAll(json); 62 | 63 | } 64 | 65 | function sendMediaMessage(senderFbId, url, type) { 66 | 67 | var json = { 68 | recipient: {id: senderFbId}, 69 | message: { attachment:{ type: type, payload : { url: url }} } 70 | }; 71 | sendAll(json); 72 | 73 | } 74 | 75 | function sendTextAndMediaMessage(senderFbId, text, url, type) { 76 | var jsonArray = []; 77 | 78 | jsonArray.push({ 79 | recipient: {id: senderFbId}, 80 | message: {text: text}, 81 | }); 82 | 83 | jsonArray.push({ 84 | recipient: {id: senderFbId}, 85 | message: { attachment:{ type: type, payload : { url: url }} } 86 | }); 87 | 88 | sendAll(jsonArray); 89 | 90 | } 91 | 92 | function sendAll(jsonParameter) { 93 | var json; 94 | if (Array.isArray(jsonParameter)) 95 | { 96 | json = jsonParameter[0]; 97 | } 98 | else 99 | { 100 | json = jsonParameter; 101 | } 102 | 103 | var body = JSON.stringify(json); 104 | var path = '/v2.6/me/messages?access_token=' + PAGE_TOKEN; 105 | var options = { 106 | host: "graph.facebook.com", 107 | path: path, 108 | method: 'POST', 109 | headers: {'Content-Type': 'application/json'} 110 | }; 111 | var callback = function(response) { 112 | var str = '' 113 | response.on('data', function (chunk) { 114 | str += chunk; 115 | }); 116 | response.on('end', function () { 117 | if (Array.isArray(jsonParameter)) 118 | { 119 | if (jsonParameter.length > 1) 120 | { 121 | jsonParameter.shift(); 122 | sendAll(jsonParameter); 123 | } 124 | } 125 | }); 126 | } 127 | 128 | var req = https.request(options, callback); 129 | req.on('error', function(e) { 130 | console.log('problem with request: '+ e); 131 | }); 132 | 133 | req.write(body); 134 | req.end(); 135 | } 136 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Build a simple FB Messenger Bot with AWS Lambda 2 | 3 | This tutorial assumes that you have at least some experience with AWS. You don't need to be an expert (I'm certainly not) but this maybe shouldn't be the very first thing you do with AWS. 4 | 5 | ### Part 1 - Facebook Page and App 6 | 7 | Facebook [Messenger Bots](https://developers.facebook.com/docs/messenger-platform/) need to be tied to a Facebook Page so if you don't have an existing page you want to use or just want to create a test bot first on a new page you can create a new one [here](https://www.facebook.com/pages/create). (If you are creating a dummy page for a test bot then during the page setup process feel free to press "Skip" button whenever it is available.) 8 | 9 | Next you will need to create a new [Facebook app](https://developers.facebook.com/apps). Once you have created that app go to the "+ Add Product" area. Find Messenger click on the "Get Started". 10 | 11 | Scroll down to "Token Generation" and select the page you just created. Save that Page Access Token and keep this web page open because we will be coming back to it later to setup the webhooks. 12 | 13 | ### Part 2 - AWS Lambda 14 | 15 | We need to create an AWS Lambda function. Go to [AWS console](http://aws.amazon.com) then Lambda then Create a Lambda Function (or the "Get Started" button if you have never created a Lambda function before.) 16 | 17 | On the "Select a blueprint" page we can use either the Blank Function or hello-world blueprint, which is just a simple node.js function. 18 | 19 | Now we setup your Lambda function where the first step is to configure triggers: 20 | 21 | Click on the grey dotted line box that will present a pull down menu and select "API Gateway". 22 | 23 | API Gateway options: 24 | * API Name: Name of your API endpoint, leave as "LambdaMicroservice" 25 | * Deployment stage: the name of your deployment stage, leave as "prod" 26 | * Security: Change to "Open" 27 | 28 | Next — configure your function: 29 | 30 | * Name: a name of your function, for example "DemoBOT" 31 | * Description: leave as is or put in a description if you want 32 | * Runtime: make sure this is Node.js 4.3 33 | * Lambda function code: copy in the index.js code in this repo but set the PAGE_TOKEN equal to the Page Access Token you got from Facebook and also change the VERIFY_TOKEN to whatever you want 34 | * Handler: leave as is 35 | * Role: Choose and exiting role and select lambda_basic_execution 36 | * Memory(MIB): leave as is (128) 37 | * Timeout: to be safe I like to make this 1 minute, 0 seconds 38 | * VPC: No VPC 39 | 40 | Then click on Next button, review your settings on and click on Create function. 41 | 42 | Now we need to create API endpoints for this function. Your function will receive messages from Facebook Messenger via this API endpoint. Under the "Triggers" tab you should see your API Gateway. Copy the gateway URL (we will need it later) and then click on the "Deployment stage: prod" link. 43 | 44 | ### Part 3 - AWS API Gateway 45 | 46 | Click on your what you named your API Gateway. (If you left it as the default it should be LambdaMicroservice.) Under "Resources" you should see your Lambda function's name with an "ANY" under it. Make sure to add the GET and POST to that part of the endpoint and not someplace else. 47 | 48 | First, Facebook Messenger will need a GET API endpoint to verify your webhook. To add a GET method just click on Actions button, select the Create Method option, choose GET method, connect our Lambda function and save it. 49 | 50 | You should now see a "GET - Method Execution" page. Click on the "Integration Request" box and expand the "Body Mapping Templates" section. Add new mapping template with value "application/json", and in Generate template pull down menu choose the "Method Request" passthrough value and click on Save button. 51 | 52 | Next, we need to add POST method. Again click on Actions button, select the Create Method option, choose POST method, connect our Lambda function and save it. 53 | 54 | Lastly, we need to deploy our API gateway. To do that just click on Actions button and select the Deploy API option, then choose your Deployment stage and click Deploy API. 55 | 56 | ### Part 4 - Back to Facebook 57 | 58 | Time to go back to the Facebook App setup page. 59 | 60 | Now we need click on the "Setup Webhook" button and set the following fields: 61 | * Callback URL: you need to copy your API gateway URL from your Lambda function Triggers tab 62 | * Verify token: make sure you put in the value that is the same as what is in the index.js file for VERIFY_TOKEN 63 | * Subscription fields: You can pick what you want for your bot but messages, messaging_postbacks, messaging_optins, message_deliveries should cover what we need for this simple example 64 | 65 | Once your webhook is verified, scroll down and select the Facebook page to subscribe your webhook to the page events. 66 | 67 | That's it! Go to your facebook page, click on Message button and send something to it. If everything worked the bot should echo the text back to you. 68 | 69 | Right now only you can access the bot. If you want other people to be able to test it out before pushing it live you can add specific users as testers under the Roles section of the Facebook App setup page. 70 | 71 | The index.js file has some extra functions that should help you start to build out your bot more. 72 | --------------------------------------------------------------------------------