5
4

More than 3 years have passed since last update.

LINEで送られてきた写真をS3に保存したい

Last updated at Posted at 2019-12-18

何に使うのか

AWSのLambdaなどを用いて画像加工する時やAWS.rekognitionのリソースとして使う時に
役に立てばと思います。
今回、LINE Developperの設定などは飛ばします。

類似の検索をするとSDKを使用している方が多いですが、今回は使わずにいきたいと思います。

使用技術

  • LINE Messaging API
  • Python 3.7
  • AWS S3
  • AWS Lambda

プログラム

メイン関数一部

lambda_function.py
import requests
import os
import json
import boto3
from io import BytesIO
#Headerの生成
HEADER = {
    'Content-type':
    'application/json',
    'Authorization':
    'Bearer ' +'チャンネルアクセストークン'
}
#main
def lambda_handler(event, context):
    #Json Load
    body = json.loads(event['body'])
    for event in body['events']:
        payload = {'replyToken': event['replyToken'], 'messages': []}
        # ImageMessageが来た時
        if event['message']['type'] == 'image':
#HEADERとmessages(pyload)を付加してpost
     if len(payload['messages']) > 0:
            response = requests.post(
            'https://api.line.me/v2/bot/message/reply',
            headers=HEADER,
            data=json.dumps(payload))

ImageMessageがきた時に画像を保存したいので、

lambda_function.py
# ImageMessageが来た時
if event['message']['type'] == 'image':

このIF文の中で処理を書いていきたいと思います。

lambda_function.py
MessageId = event['message']['id']  # メッセージID
ImageFile = requests.get('https://api-data.line.me/v2/bot/message/
'+ MessageId +'/content',headers=HEADER) #Imagecontent取得

Image_bin = BytesIO(ImageFile.content)
Image = Image_bin.getvalue()  # 画像取得

コンテンツを取得する←に詳しい事が書いてあるので気になる方は読んでみてください。

lambda_function.py
S3 = boto3.client('s3') 
FileName = MessageId + '.jpeg'  # メッセージID+jpegをファイル名
# s3へのput処理
S3.put_object(Bucket='バケット名',
             Body=Image, # 写真
             Key=FileName)  # ファイル名

最後に

ここまでの処理を書いてLINEから画像送信してS3に保存されてれば大丈夫だと思います。
処理していく中で画像が毎回保存されて残っているのが気持ち悪い人は下記のコードを書けば
解決します。

lambda_function.py
S3.delete_object(Bucket="バケット名", Key=FileName)  # 送信画像削除
5
4
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
4