I was making AWS Lambda that fetches a file from Amazon S3 and posts it to Slack as an attachment, but I struggled because AWS Lambda's Python environment did not include the requests module.
AWS Lambda Python environment
files.upload
API (use multipart / form-data for content type)Uploading files in Python https://qiita.com/5zm/items/92cde9e043813e02eb68 Or https://www.it-swarm-ja.tech/ja/python/python%E3%81%A7%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%81%A8-multipart-formdata%E3%82%92%E9%80%81%E4%BF%A1%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95%EF%BC%9F/1069592211/ As you can see in, it is standard to use requests. However, AWS Lambda's Python environment did not include the requests module.
--Use Lambda Layer with requests -** Use urllib.request instead of requests <-Adopt **
Even if you use urllib.request, you need to create multipart form data, so I referred to the following URL. https://necoyama3.hatenablog.com/entry/20150608/1434982490 The ʻencode_multipart_formdata` method described in this article converts the data part and the file part into the multipart form data format.
Using this, I did the following.
python
##Point 1:Define parameters excluding file parameter
data = {
'token': <your token>,
'channels': <your channels>,
'initial_comment': key + 'Post:eyes:',
'filename': key,
'filetype': 'webp'
}
url = "https://slack.com/api/files.upload"
content = open('/tmp/' + key, 'rb').read()
##Point 2:define the file parameter
file = {'file': {'filename': key, 'content': content}}
##Point 3:Convert data and file into one multipart form data
content_type, body = encode_multipart_formdata(data, file)
header = {'Content-Type': content_type}
request = urllib.request.Request(url, body, header)
response = urllib.request.urlopen(request)
The point is
data
variable excluding the file parameter of the Slack files.upload API.file
variable3 points. You can now post files to Slack with AWS Lambda without using requests.
Which is easier to make a Lambda Layer ...?
Recommended Posts