5
2

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.

Serverless FrameworkでLINE BOTへのメッセージをDynamoDBに保存するapiを作ってみる

Posted at

#経緯

  • ServerlessでChat Botを作る予定
  • 今年中に記事を投稿したい

#事前準備

  • Serverless Frameworkインストール
  • AWSアカウント取得
  • AWS CLIインストールと設定
  • LINEアカウント取得
  • Messaging APIを利用可能にする

#Serverless Frameworkのプロジェクト作成

$ mkdir test-api && cd test-api
$ serverless create --template aws-nodejs

#serverless.ymlの設定

serverless.yml
service: test-api

provider:
  name: aws
  runtime: nodejs4.3
  stage: dev
  region: ap-northeast-1
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:PutItem
      Resource: '*'

functions:
  put:
    handler: handler.put
    events:
     - http:
         path: put
         method: post

resources:
  Resources:
    messagesTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: messagesTable
        AttributeDefinitions:
          - AttributeName: replyToken
            AttributeType: S
          - AttributeName: time
            AttributeType: N
        KeySchema:
          - AttributeName: replyToken
            KeyType: HASH
          - AttributeName: time
            KeyType: RANGE
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1

#Lambdaファンクション作成

handler.js
'use strict';

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();
const table = 'messagesTable';

module.exports.put = (event, context, callback) => {
	var date = new Date();
	var time = date.getTime();
	var body = JSON.parse(event.body);

	body.events.forEach(function(data) {
		var replyToken = data.replyToken;
		var message = data.message.text;
		var params = {
			TableName: table,
			Item: {
				replyToken: replyToken,
				time: time,
				message: message
			}
		};

		dynamodb.put(params, function(err) {

			if (err) {
				console.log(err);
			}
		});
	});

	callback(null, {statusCode: 200, body: JSON.stringify({})});
};

#AWSへデプロイ

$ serverless deploy

成功したらエンドポイントが取得できるのでメモ

endpoints:
  POST - https://xxx.amazonaws.com/dev/put

#LINE側設定

  • Webhook送信:利用する
  • Webhook URL:メモしたエンドポイントを指定

#以上です
あとは、LINEからBOTアカウントを友だち追加してトークよりメッセージを送信することで
DynamoDBにメッセージが保存されます。

#片づけ

$ serverless remove
5
2
0

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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?