I thought it would be convenient if I could post regularly on Twitter using AWS Lambda, so I summarized it.
I used Docker to use non-standard libraries with lambada. To use docker with lambda, it is convenient to use lambci / docker-lambda. This article was helpful. [Reproduction of local development environment with AWS Lambda x Python](https://qiita.com/i35_267/items/15b981acae8cf7c763ae#-docker-lambda%E3%82%92%E8%A7%A6%E3%81% A3% E3% 81% A6% E3% 81% BF% E3% 82% 8B)
Dockerfile
FROM lambci/lambda:build-python3.8
ENV AWS_DEFAULT_REGION ap-northeast-1
ADD . .
CMD pip3 install -r requirements.txt -t /var/task && \
zip -9 deploy_package.zip lambda_function.py && \
zip -r9 deploy_package.zip *
I'm not sure about the options for zip -9
.
requirements.txt
twitter
You can easily tweet using the library here sixohsix / twitter. Articles that I used as a reference ・ Post to twitter easily with Python3
lambda_funcyion.py
import twitter
def lambda_handler(event, context):
auth = twitter.OAuth(
token="token",
token_secret="Token secret",
consumer_key="Key",
consumer_secret="secret"
)
context = 'I did my best today too!'
t = twitter.Twitter(auth=auth)
t.statuses.update(status=context)
It is troublesome to give it to lambda one by one and check it, so check it locally.
$ docker run -v "$PWD":/var/task lambci/lambda:python3.8 lambda_function.lambda_handler [event]
You should be posting with this.
First, put it in a zip file.
$ docker build -t mylambda .
$ docker run -v "$PWD":/var/task mylambda
Next, create a lambda function from the AWS console.
Upload zip file
Register environment variables
It's OK if you can register the time of regular execution!
reference -Be careful about the time difference when using cron expressions in Amazon CloudWatch Events ・ Official document rule schedule formula
・ I want to incorporate it into other flows.
Recommended Posts