事前準備
- AWSのアカウント登録
- LINE Developersの登録
- pip等でrequestsライブラリをインストールしておく※pipの場合
pip install requests
##今回やること
LINEBOTにメッセージを送って、送られてきたメッセージをDynamoDBに保存したいです
###使用する技術
- Python3.6
- Lambda
- DynamoDB
- LINEmessagingAPI
####LINE Developers
新規プロパイダ作成をする→新規チャンネル作成。
チャンネル基本設定にあるアクセストークンを発行しコピーしておく。
#####Lambda
lambdaのコンソール画面を開き、関数の新規作成
※ランタイムにPython3.6を選択してください
実行ロールにIAMでDynamoDBFullAccess
をふっておきましょう。
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のファイルと一緒にデプロイします。
※圧縮する時は.pyファイルと同じ階層にファイルが置かれてないといけないらしいです
pipでインストールした場合はpip show
コマンドでどこにファイルが置かれているか分かります。
###API Gateway
次に左側にあるトリガーの追加を押してステージ等はdefaultのままで追加。
API Gatewayをクリックするとエンドポイントが表示されるのでこれをコピー
Webhook URLの部分に貼りつけて更新
こんな感じで作ってますが、もっといいやり方があるなら教えて欲しいです。
ちゃんと書きこまれてますね!!