4
0

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 3 years have passed since last update.

LINEbotに画像を送信すると、その画像をS3に保存

Last updated at Posted at 2021-10-01

前提

・Lineデベロッパーアカウント開設済み
・LinebotのwebhookにApiGatewayのpostエンドポイント設定済み
・LambdaとApiGatewayの紐づけ
・その他LINE発行のトークンを環境変数に設定やS3へのアクセス権限付与などLambda周り
詳しくは下記記事が参考になります。
https://qiita.com/w2or3w/items/1b80bfbae59fe19e2015

コード

Lambdaに下記コード記述・デプロイ
あなたのバケット名はS3のバケット名に変えてください

lambda_function.py
import os
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.models import (
    MessageEvent, TextSendMessage,
    ImageMessage
)
import boto3
import tempfile
LINE_CHANNEL_ACCESS_TOKEN   = os.environ['LINE_CHANNEL_ACCESS_TOKEN']
LINE_CHANNEL_SECRET         = os.environ['LINE_CHANNEL_SECRET']
LINE_BOT_API = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
LINE_HANDLER = WebhookHandler(LINE_CHANNEL_SECRET)

def lambda_handler(event, context):
    logger.info(event)
    signature = event["headers"]["x-line-signature"]
    body = event["body"]
    
    # 画像を受け取った時に呼ばれるイベント
    @LINE_HANDLER.add(MessageEvent, message=ImageMessage)
    def on_image(line_event):
        logger.info('image event')
        image = LINE_BOT_API.get_message_content(line_event.message.id)
        with tempfile.TemporaryFile() as tmp:
            for chunk in image.iter_content():
                tmp.write(chunk)
            tmp.seek(0)
            s3 = boto3.resource('s3')
            bucket = s3.Bucket('あなたのバケット名')
            try:
                bucket.put_object(
                    Body=tmp,
                    Key=f'{line_event.message.id}.png'
                )
                LINE_BOT_API.reply_message(
                    line_event.reply_token,
                    TextSendMessage(text='アップロードに成功しました')
                )
            except Exception as e:
                logger.error(e)
                LINE_BOT_API.reply_message(
                    line_event.reply_token,
                    TextSendMessage(text='アップロードに失敗しました')
                )
            
    LINE_HANDLER.handle(body, signature)
    return 0
4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?