Creating a Twitter App

Length: 00:09:30

Lesson Summary:

In this lesson, we will learn how to create a Twitter app that automatically sends tweets on a schedule.

Create a Twitter Application

More info here:

Note the Consumer API keys and access token & access token secret.

You can set these as environment variables, should you wish to create the SSM parameters using the AWS CLI:


Create the SSM Parameters

Use the keys from the previous step:

aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/consumer_key", "Value": "'"$CONSUMER_KEY"'"}'

aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/consumer_secret", "Value": "'"$CONSUMER_SECRET"'"}'

aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/access_token", "Value": "'"$ACCESS_TOKEN"'"}'

aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/access_token_secret", "Value": "'"$ACCESS_TOKEN_SECRET"'"}'

Create an S3 Bucket and Upload the Data File

aws s3 mb s3://123456789012-twitterbot
aws s3 cp data.txt s3://123456789012-twitterbot

Create an IAM Execution Role for Lambda

  1. Grant access to your S3 bucket:

       "Version": "2012-10-17",
       "Statement": [{
           "Effect": "Allow",
           "Action": [
           "Resource": "arn:aws:s3:::123456789012-twitterbot/*"
           "Effect": "Allow",
           "Action": [
           "Resource": "arn:aws:ssm:us-east-2:123456789012:parameter/TwitterBot*"

Create a Deployment Package

  1. Create a new virtual environment using pipenv and install the required libraries:

     pipenv --python 3.7
     pipenv shell
     pipenv install tweepy
     mkdir package
     pipenv lock -r > requirements.txt
     pip install -r requirements.txt --no-deps -t package
     cd package
     zip -r9 ../ .
     cd ..
     zip -g
     rm -rf package/*

Create a Lambda Function

aws lambda create-function \
--function-name TwitterBot \
--zip-file fileb:// \
--role arn:aws:iam::123456789012:role/LambdaTwitterBotRole \
--handler lambda_function.lambda_handler \
--runtime python3.7 \
--environment Variables={BUCKET_NAME=123456789012-twitterbot}

Create a CloudWatch Scheduled Rule

aws events put-rule \
--name TwitterBot \
--schedule-expression 'rate(1 hour)'

aws lambda add-permission \
--function-name TwitterBot \
--statement-id TwitterBot \
--action 'lambda:InvokeFunction' \
--principal \
--source-arn arn:aws:events:us-east-1:123456789012:rule/TwitterBot

aws events put-targets --rule TwitterBot --targets file://targets.json

This lesson is only available to Linux Academy members.

Sign Up To View This Lesson
Or Log In

Looking For Team Training?

Learn More