Facebook Bot向けアプリをAWS Lambdaで実装する


# ここまでの準備

AWS API GatewayとAWS Lambdaで、HelloWorldを作成する
http://qiita.com/akira-sasaki/items/b9e8e8a0330818e3b71d

AWS API GatewayとAWS Lambdaで、Facebook Botを作成する
http://qiita.com/akira-sasaki/items/961cb7a1aa7386764863

# Facebookから送られてくるJSON

```json:Facebookから送られてくるJSON
{
  "object":"page",
  "entry":[
    {
      "id":PAGE_ID,
      "time":1457764198246,
      "messaging":[
        {
          "sender":{
            "id":USER_ID
          },
          "recipient":{
            "id":PAGE_ID
          },
          "timestamp":1457764197627,
          "message":{
            "mid":"mid.1457764197618:41d102a3e1ae206a38",
            "seq":73,
            "text":"hello, world!"
          }
        }
      ]
    }
  ]
}
```

| Field Name | Description | Type |
|:--|:--|:--|
| sender.id | Sender user id |Number |
| recipient.id | Recipient user id | Number |
| timestamp | Timestamp of message | Number |
| message | Message | Object |

# データ送信

```bash:Curl例
curl -X POST -H "Content-Type: application/json" -d '{
    "recipient":{
        "id":"USER_ID"
    }, 
    "message":{
        "text":"hello, world!"
    }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"
```

# ACCESS_TOKENを取得

![access_token.png](https://qiita-image-store.s3.amazonaws.com/0/63450/36cffc76-1683-4454-5a6f-230157107f32.png)

![access_token2.png](https://qiita-image-store.s3.amazonaws.com/0/63450/8776a762-89b2-2458-4c6c-9fd75dddcc0a.png)



# おうむ返しのBotを作る

```js:FacebookBotCallback.js
var http = require ('https');

var accessToken = "アクセストークン";
var sendingCount = 0;
var myContext;

exports.handler = function(event, context) {
    console.log('Received event:', JSON.stringify(event, null, 2));
    myContext = context;

    // パラメータチェック
    var entry = event.entry;
    if (!entry || entry.length === 0) {
        context.fail("invalid parameter");
        return;
    }

    // 各メッセージの処理
    for (var i = 0; i < entry.length; i++) {
        var messaging_events = entry[i].messaging;
        var timestamp = entry[i].time;
        for (var j = 0; j < messaging_events.length; j++) {
            var messaging = entry[i].messaging[j];
            var sender = messaging.sender.id;
            // メッセージ
            if (messaging.message && messaging.message.text) {
                var text = messaging.message.text;
                sendMessage(sender, {text: text});
            }
        }
    }
    // context.done();
};

// メッセージ送信
function sendMessage(sender, messageData) {
    var json_data = {
        recipient: {id: sender},
        message: messageData
    };
    var post_data = JSON.stringify(json_data);
    console.log("* sendMessage *" + post_data);

    var post_options = {
        host: 'graph.facebook.com',
        port: '443',
        path: '/v2.6/me/messages?access_token='+accessToken,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(post_data)
        }
    };

    var post_req = http.request(post_options, function(res) {
        res.setEncoding('utf8');
        // res.on('data', function (chunk) {
        //     console.log('Response: ' + chunk);
        // });
        res.on('end', function () {
            // console.log('End');
            sendingCount -= 1;
            if (sendingCount === 0) {
                myContext.done();
            }
        });
    });

    post_req.on('error', function (e) {
        console.error('HTTP error: ' + e.message);
        sendingCount -= 1;
        if (sendingCount === 0) {
            myContext.done();
        }
    });

    // post the data
    post_req.write(post_data);
    post_req.end();
}
```