6
6

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.

LINEから送信したテキストをDynamoDBに保存

Last updated at Posted at 2019-09-19

事前準備

##今回やること
LINEBOTにメッセージを送って、送られてきたメッセージをDynamoDBに保存したいです

###使用する技術

  • Python3.6
  • Lambda
  • DynamoDB
  • LINEmessagingAPI

####LINE Developers
新規プロパイダ作成をする→新規チャンネル作成。
チャンネル基本設定にあるアクセストークンを発行しコピーしておく。
スクリーンショット 2019-09-18 13.46.12.png

#####Lambda
lambdaのコンソール画面を開き、関数の新規作成
スクリーンショット 2019-09-18 13.49.17.png
※ランタイムにPython3.6を選択してください
実行ロールにIAMでDynamoDBFullAccessをふっておきましょう。

Lambda_Function.py
import requests
import json
import boto3
import datetime

HEADER = {
    'Content-type':'application/json',
    'Authorization':'Bearer '+'先ほどコピーしたアクセストークン'
}


def lambda_handler(event, context):

    body = json.loads(event['body'])

    for event in body['events']:

        userId = event['source']['userId']  #userID取得
        message = datetime.datetime.now()  #時刻
        dynamoDB = boto3.resource("dynamodb")
        table = dynamoDB.Table("自分で作ったテーブル名")  # DynamoDBのテーブル名

        payload = {'replyToken': event['replyToken'], 'messages': []}

        #text形式で来た時の処理
        if event['message']['type'] == 'text':
            
            # DynamoDBへのPut処理実行
            table.put_item(
                Item={
                    "userId": str(userId),  # Partition Keyのデータ
                    "time": str(message),   #Sort Key
                    "message": str(event['message']['text'])  #Text内容
                })
            #END
            
            #送信したメッセージを送り返す処理
            payload['messages'].append({
                'type': 'text',
                'text': event['message']['text']
            })

    #スタンプを返す(標準スタンプだけ)
        elif event['message']['type'] == 'sticker':
            payload['messages'].append({
                'type':'sticker',
                'stickerId': event['message']['stickerId'],
                'packageId':event['message']['packageId']
            })
            
        if len(payload['messages']) > 0:
            response = requests.post(
                'https://api.line.me/v2/bot/message/reply',
                headers=HEADER,
                data=json.dumps(payload))

Lambdaでライブラリを使いたい時は使いたいライブラリファイルとまとめてzip圧縮してデプロイします。なので、インストールしたrequestsのファイルと一緒にデプロイします。
スクリーンショット 2019-09-19 12.16.05.png
※圧縮する時は.pyファイルと同じ階層にファイルが置かれてないといけないらしいです

pipでインストールした場合はpip show コマンドでどこにファイルが置かれているか分かります。

###API Gateway
次に左側にあるトリガーの追加を押してステージ等はdefaultのままで追加。
スクリーンショット 2019-09-19 10.40.47.png

API Gatewayをクリックするとエンドポイントが表示されるのでこれをコピー
スクリーンショット 2019-09-19 10.41.38.png

LINE Developersの管理画面に戻って
スクリーンショット 2019-09-19 12.28.53.png

Webhook URLの部分に貼りつけて更新

####DynamoDB
スクリーンショット 2019-09-19 12.31.16.png

こんな感じで作ってますが、もっといいやり方があるなら教えて欲しいです。

###実演
IMG_0601.PNG
こんな感じでちゃんと返ってこれば大丈夫です!!
スクリーンショット 2019-09-19 14.02.34.png

ちゃんと書きこまれてますね!!

6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?