Skip to content

Commit d103298

Browse files
committed
Twitter
1 parent eb95068 commit d103298

File tree

6 files changed

+204
-0
lines changed

6 files changed

+204
-0
lines changed

ThirdParty/Twitter/.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Pipfile*
2+
package/**
3+
package.zip
4+
requirements.txt

ThirdParty/Twitter/README.md

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# Twitter Bot
2+
3+
automatically tweet on a schedule
4+
5+
## Create Twitter Application
6+
7+
More info here <https://developer.twitter.com/en/docs/basics/apps/overview>.
8+
9+
Note the Consumer API keys and Access token & access token secret.
10+
11+
```sh
12+
CONSUMER_KEY=...
13+
CONSUMER_SECRET=...
14+
ACCESS_TOKEN=...
15+
ACCESS_TOKEN_SECRET=...
16+
```
17+
18+
## Create SSM Parameters
19+
20+
Use the keys from the previous step:
21+
22+
```sh
23+
aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/consumer_key", "Value": "'"$CONSUMER_KEY"'"}'
24+
25+
aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/consumer_secret", "Value": "'"$CONSUMER_SECRET"'"}'
26+
27+
aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/access_token", "Value": "'"$ACCESS_TOKEN"'"}'
28+
29+
aws ssm put-parameter --cli-input-json '{"Type": "SecureString", "KeyId": "alias/aws/ssm", "Name": "/TwitterBot/access_token_secret", "Value": "'"$ACCESS_TOKEN_SECRET"'"}'
30+
```
31+
32+
## Create an S3 bucket and upload the data file
33+
34+
```sh
35+
aws s3 mb s3://123456789012-twitterbot
36+
aws s3 cp data.txt s3://123456789012-twitterbot
37+
```
38+
39+
## Create IAM execution role for Lambda
40+
41+
Grant access to your S3 bucket:
42+
43+
```json
44+
{
45+
"Version": "2012-10-17",
46+
"Statement": [{
47+
"Effect": "Allow",
48+
"Action": [
49+
"s3:GetObject"
50+
],
51+
"Resource": "arn:aws:s3:::123456789012-twitterbot/*"
52+
}]
53+
}
54+
```
55+
56+
## Create deployment package
57+
58+
Create a new virtual environment using `pipenv` and install the required libraries:
59+
60+
```sh
61+
pipenv --python 3.7
62+
pipenv shell
63+
pipenv install tweepy
64+
mkdir package
65+
pipenv lock -r > requirements.txt
66+
pip install -r requirements.txt --no-deps -t package
67+
cd package
68+
zip -r9 ../package.zip .
69+
cd ..
70+
zip -g package.zip lambda_handler.py
71+
```
72+
73+
<!--
74+
## Update Lambda funcion
75+
76+
```sh
77+
aws lambda update-function-code --function-name TwitterBot --zip-file fileb://package.zip
78+
``` -->
79+
80+
## Create Lambda function
81+
82+
```sh
83+
aws lambda create-function \
84+
--function-name TwitterBot \
85+
--zip-file fileb://package.zip \
86+
--role arn:aws:iam::123456789012:role/LambdaTwitterBotRole \
87+
--handler lambda_function.lambda_handler \
88+
--runtime python3.7 \
89+
--environment Variables={BUCKET_NAME=123456789012-twitterbot}
90+
```
91+
92+
## Create CloudWatch Scheduled Rule
93+
94+
```sh
95+
aws events put-rule \
96+
--name TwitterBot \
97+
--schedule-expression 'rate(1 hour)'
98+
99+
aws lambda add-permission \
100+
--function-name TwitterBot \
101+
--statement-id TwitterBot \
102+
--action 'lambda:InvokeFunction' \
103+
--principal events.amazonaws.com \
104+
--source-arn arn:aws:events:us-east-1:123456789012:rule/TwitterBot
105+
106+
aws events put-targets --rule TwitterBot --targets file://targets.json
107+
```

ThirdParty/Twitter/data.txt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Once men turned their thinking over to machines in the hope that this would set them free. But that only permitted other men with machines to enslave them.
2+
Deep in the human unconscious is a pervasive need for a logical universe that makes sense. But the real universe is always one step beyond logic.
3+
The mystery of life isn't a problem to solve, but a reality to experience.
4+
What do you despise? By this are you truly known.
5+
There is no escape—we pay for the violence of our ancestors.
6+
Hope clouds observation.
7+
It is so shocking to find out how many people do not believe that they can learn, and how many more believe learning to be difficult.
8+
He who controls the spice controls the universe.
9+
Without change something sleeps inside us, and seldom awakens. The sleeper must awaken.
10+
The mind commands the body and it obeys. The mind orders itself and meets resistance.
11+
Whether a thought is spoken or not it is a real thing and it has power," Tuek said. "You might find the line between life and death among the Fremen to be too sharp and quick.
12+
Fear is the mind-killer.
13+
It is impossible to live in the past, difficult to live in the present and a waste to live in the future.
14+
Try looking into that place where you dare not look! You'll find me there, staring out at you!
15+
The people who can destroy a thing, they control it.
16+
Survival is the ability to swim in strange water.
17+
The Fremen were supreme in that quality the ancients called "spannungsbogen" -- which is the self-imposed delay between desire for a thing and the act of reaching out to grasp that thing.
18+
Arrakis teaches the attitude of the knife - chopping off what's incomplete and saying: 'Now, it's complete because it's ended here.'
19+
What has mood to do with it? You fight when the necessity arises—no matter the mood! Mood's a thing for cattle or making love or playing the baliset. It's not for fighting.
20+
Highly organized research is guaranteed to produce nothing new.
21+
Proper teaching is recognized with ease. You can know it without fail because it awakens within you that sensation which tells you this is something you have always known.
22+
The willow submits to the wind and prospers until one day it is many willows - a wall against the wind.
23+
"Give as few orders as possible," his father had told him once long ago. "Once you've given orders on a subject, you must always give orders on that subject."
24+
There should be a science of discontent. People need hard times to develop psychic muscles.
25+
Any road followed precisely to its end leads precisely nowhere. Climb the mountain just a little bit to test that it's a mountain. From the top of the mountain, you cannot see the mountain.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"Version": "2012-10-17",
3+
"Statement": [{
4+
"Effect": "Allow",
5+
"Action": [
6+
"s3:GetObject"
7+
],
8+
"Resource": "arn:aws:s3:::{bucket-name}/*"
9+
}]
10+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import os
2+
import random
3+
4+
import boto3
5+
from botocore.exceptions import ClientError
6+
import tweepy
7+
8+
BUCKET_NAME = os.environ['BUCKET_NAME']
9+
KEY = 'data.txt'
10+
11+
s3 = boto3.resource('s3')
12+
ssm = boto3.client('ssm')
13+
14+
15+
def get_parameter(param_name):
16+
response = ssm.get_parameter(Name=param_name, WithDecryption=True)
17+
credentials = response['Parameter']['Value']
18+
return credentials
19+
20+
21+
def get_tweet_text():
22+
filename = '/tmp/' + KEY
23+
try:
24+
s3.Bucket(BUCKET_NAME).download_file(KEY, filename)
25+
except ClientError as e:
26+
if e.response['Error']['Code'] == "404":
27+
print(f'The object {KEY} does not exist in bucket {BUCKET_NAME}.')
28+
else:
29+
raise
30+
31+
with open(filename) as f:
32+
lines = f.readlines()
33+
return random.choice(lines)
34+
35+
36+
def lambda_handler(event, context):
37+
38+
# Get SSM parameters
39+
CONSUMER_KEY = get_parameter('/TwitterBot/consumer_key')
40+
CONSUMER_SECRET = get_parameter('/TwitterBot/consumer_secret')
41+
ACCESS_TOKEN = get_parameter('/TwitterBot/access_token')
42+
ACCESS_TOKEN_SECRET = get_parameter('/TwitterBot/access_token_secret')
43+
44+
# Authenticate Tweepy
45+
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
46+
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
47+
api = tweepy.API(auth)
48+
49+
# Send tweet
50+
tweet = get_tweet_text()
51+
print(tweet)
52+
api.update_status(tweet)

ThirdParty/Twitter/targets.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[
2+
{
3+
"Id": "1",
4+
"Arn": "arn:aws:lambda:us-east-1:123456789012:function:TwitterBot"
5+
}
6+
]

0 commit comments

Comments
 (0)