[PYTHON] I want to save the photos sent by LINE to S3

What to use

When processing images using AWS Lambda etc. or when using it as a resource of AWS.rekognition I hope it helps. This time, I will skip the settings of LINE Developper.

If you do a similar search, many people are using the SDK, but this time I would like to avoid using it.

Technology used

program

Part of the main function

lambda_function.py


import requests
import os
import json
import boto3
from io import BytesIO
#Header generation
HEADER = {
    'Content-type':
    'application/json',
    'Authorization':
    'Bearer ' +'Channel access token'
}
#main
def lambda_handler(event, context):
    #Json Load
    body = json.loads(event['body'])
    for event in body['events']:
        payload = {'replyToken': event['replyToken'], 'messages': []}
        #When ImageMessage arrives
        if event['message']['type'] == 'image':
#HEADER and messages(pyload)With post
     if len(payload['messages']) > 0:
            response = requests.post(
            'https://api.line.me/v2/bot/message/reply',
            headers=HEADER,
            data=json.dumps(payload))

I want to save the image when ImageMessage arrives, so

lambda_function.py


#When ImageMessage arrives
if event['message']['type'] == 'image':

I would like to write the process in this IF statement.

lambda_function.py


MessageId = event['message']['id']  #Message ID
ImageFile = requests.get('https://api-data.line.me/v2/bot/message/
'+ MessageId +'/content',headers=HEADER) #Get Image content

Image_bin = BytesIO(ImageFile.content)
Image = Image_bin.getvalue()  #Image acquisition

Get content ← has more details, so please read it if you are interested.

lambda_function.py


S3 = boto3.client('s3') 
FileName = MessageId + '.jpeg'  #Message ID+File name jpeg
#put process to s3
S3.put_object(Bucket='Bucket name',
             Body=Image, #Photo
             Key=FileName)  #file name

Finally

I think it's okay if you write the processing up to this point, send an image from LINE, and save it in S3. If you feel uncomfortable that the image is saved and remains every time during processing, write the following code I will solve it.

lambda_function.py


S3.delete_object(Bucket="Bucket name", Key=FileName)  #Delete transmitted image

Recommended Posts

I want to save the photos sent by LINE to S3
I want to know the weather with LINE bot feat.Heroku + Python
I want to make the second line the column name in pandas
I want to pin Spyder to the taskbar
I want to output to the console coolly
I want to handle the rhyme part1
I want to handle the rhyme part3
I want to display the progress bar
I want to handle the rhyme part2
I want to handle the rhyme part5
I want to handle the rhyme part4
I want to change the color by clicking the scatter point in matplotlib
I tried to save the data with discord
I want to handle the rhyme part7 (BOW)
I want to manage systemd by time zone! !!
I want to sell Mercari by scraping python
I want to customize the appearance of zabbix
I want to use the activation function Mish
I want to display the progress in Python!
The file edited with vim was readonly but I want to save it
I want to get the file name, line number, and function name in Python 3.4
I want to read CSV line by line while converting the field type (while displaying the progress bar) and process it.
I want to see the file name from DataLoader
Upload the image downloaded by requests directly to S3
I want to grep the execution result of strace
I want to scroll the Django shift table, but ...
Save the graph drawn by pyqtgraph to an image
I want to inherit to the back with python dataclass
I want to fully understand the basics of Bokeh
I want to write in Python! (3) Utilize the mock
I want to handle the rhyme part6 (organize once)
I want to automate ssh using the expect command!
I want to publish the product at the lowest cost
I want to use the R dataset in python
I tried to notify the honeypot report on LINE
I want to handle the rhyme part8 (finished once)
I want to increase the security of ssh connections
I want to add my own structure to the structure created by Python's C extension module!
[Memorandum] ① Get and save tweets ~ I want to identify the news tweets that are spread ~
I want to use the latest gcc without sudo privileges! !!
I want to initialize if the value is empty (python)
I want to automate ssh using the expect command! part2
I tried to notify the train delay information with LINE Notify
maya Python I want to fix the baked animation again.
I want to move selenium for the time being [for mac]
I want to use only the normalization process of SudachiPy
I want to get the operation information of yahoo route
I want to change the Japanese flag to the Palau flag with Numpy
I want to solve Sudoku (Sudoku)
I want to calculate the allowable downtime from the operating rate
I want to color black-and-white photos of memories with GAN
[Python] I want to use the -h option with argparse
I want to find the intersection of a Bezier curve and a straight line (Bezier Clipping method)
[Go] I want to separate endpoints by Read / Write to DB
[Python] I asked LINE BOT to answer the weather forecast.
I want to judge the authenticity of the elements of numpy array
I want to send a message from Python to LINE Bot
I want to know the features of Python and pip
I want to make the Dictionary type in the List unique
I want to map the EDINET code and securities number
[Selenium] I want to display the browser by hitting the driver on the host OS from WSL