68
68

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS Lambda + API GatewayでLINE BOT APIを叩いてみた

Last updated at Posted at 2016-04-07

LINE BOT API公開記念
AWS Lambdaでオウム返しBOTを作成

アカウント設定はhttps://developers.line.me から適当にやってください。

BOTを作成するとLINE_CHANNEL_ID, LINE_CHANNEL_SECRET, LINE_CHANNEL_MIDを取得できます

  • まずはAWSのマネジメントコンソールに入り[Create a Lambda function]をクリック
  • Node.jsのfunctionを選ぶ
  • Code欄を以下のコードに変更
var https = require('https');

exports.handler = function(event, context) {
    console.log('Received event:', JSON.stringify(event, null, 2));
    var msg = event.result[0];
    var data = JSON.stringify({
      to: [msg.content.from.toString()],
      toChannel: 1383378250,
      eventType: "138311608800106203",
      content: msg.content
    });
    var url ='https://trialbot-api.line.me/v1/events';
    var opts = {
        host: 'trialbot-api.line.me',
        path: '/v1/events',
        headers: {
            "Content-type": "application/json; charset=UTF-8",
            "X-Line-ChannelID": "LINE_CHANNEL_ID",
            "X-Line-ChannelSecret": "LINE_CHANNEL_SECRET",
            "X-Line-Trusted-User-With-ACL": "LINE_CHANNEL_MID"
        },
        method: 'POST'
    }
    var req = https.request(opts, function(res){
        res.on('data', function(chunk){
            console.log(chunk.toString())
        }).on('error', function(e){
            console.log('ERROR: '+ e.stack);
        })
    })
    req.write(data)
    req.end();
};
  • LINE_CHANNEL_ID, LINE_CHANNEL_SECRET, LINE_CHANNEL_MIDは適当に変更してください
  • 次にAPI endpointsに移動し、[Add API endpoint]をクリック
  • API Gatewayを選択し、もろもろ設定し、Methodは「POST」に設定
  • 追加後API endpoint URLをコピーしLINE developersのBasic InformationのCallback URLにペースト
  • 作成したBOTにメッセージを送るとLambdaのCloud watchのログに
{
    "statusCode": "427",
    "statusMessage": "Your ip address [xxx.xxx.xxx.xxx] is not allowed to access this API."
}
  • とip addressが書かれるのでこれをLINE developersのServer IP Whitelistに追加
  • 少し経つと設定されオウム返しBOTの完成

追記 2016/4/28
Whitelistを空にするとどこからでもアクセス可能となりました。
サーバーを指定したくない場合はWhitelistの設定を消してください。

つぎはBot Frameworkかな・・・

68
68
12

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
68
68

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?