Make ordinary tweets fleet-like with AWS Lambda and Python

What is a fleet?

Fleet provides the ability to take advantage of Twitter and communicate on Twitter in an unprecedented way. The content shared on Fleet disappears after 24 hours, so you can share your thoughts and feelings of depression. You can share your temporary personal thoughts with your followers without any reaction from other general users. Fleet creators can click on their Fleet and tap the read text at the bottom to see who viewed their Fleet, including accounts that keep tweets private.

--It disappears after 24 hours ――In other words, you only have to delete it once every 24 hours.

Fleet drawbacks

--There is no comment function and you will be notified by DM --Even if you send an emoji, you will be notified by DM ――I still want Fav, RT, and reply functions, just like regular tweets.

How to fleet tweets?

--Clarify "tweets to leave" and "tweets to disappear" --Conditions for tweets to be left --There is a Fav --There is RT --There is a reply --Conditions for erasing tweets --Everything except the tweets you leave --According to the above conditions, fire Lambda once every 24 hours and delete the tweet

Prerequisites

--Twitter API key issued ――I will do my best because English composition will come out as much as I can if I google --Created an AWS account --Keep AWS CLI available

Build

Folder structure

DeleteNoRtFavReplyTweets
|   lambda.yml
|   README.md
|
\---code
        DeleteNoRtFavReplyTweets.py

Cloudformation

AAWSTemplateFormatVersion: '2010-09-09'
# Twitter API Key
Parameters:
  ConsumerKey:
    Type: String
    NoEcho: true
  ConsumerSecret:
    Type: String
    NoEcho: true
  AccessKey:
    Type: String
    NoEcho: true
  AccessSecret:
    Type: String
    NoEcho: true
Resources:
# Lambda
  Lambda:
    Type: 'AWS::Lambda::Function'
    Properties:
      Code: code
      Environment: 
        Variables:
          ConsumerKeyVar: !Ref ConsumerKey
          ConsumerSecretVar: !Ref ConsumerSecret
          AccessKeyVar: !Ref AccessKey
          AccessSecretVar: !Ref AccessSecret
      Description: NoRtFavReplyTweetDelete
      FunctionName: NoRtFavReplyTweetDelete
      Handler: noRtFavTweetDelete.lambda_handler
      MemorySize: 128
      Role: !Sub 
        - arn:aws:iam::${AWS::AccountId}:role/${Domain}
        -  { Domain: !Ref LambdaRole }
      Runtime: python3.8
      Timeout: 180
  # CloudWatchEvents Rule
  Rule:
    Type: 'AWS::Events::Rule'
    Properties:
      Description: NoRtFavReplyTweetDeleteRule
      Name: NoRtFavReplyTweetDeleteRule
      ScheduleExpression: 'cron(0 17 * * ? *)' #2 o'clock at night
      State: ENABLED
      Targets:
        - Arn: !GetAtt Lambda.Arn
          Id: lambda
  # Lambda IAM Role
  LambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: deleteTweetRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
  # CloudWatchEvents Lambda excute enable
  LambdaEvent:
    Type: 'AWS::Lambda::Permission'
    Properties:
      Action: 'lambda:InvokeFunction'
      FunctionName: !Ref Lambda
      Principal: 'events.amazonaws.com'
      SourceArn: !GetAtt Rule.Arn

Python

import tweepy
import os

# API Key
consumer_key = os.environ['ConsumerKeyVar']
consumer_secret = os.environ['ConsumerSecretVar']
access_key = os.environ['AccessKeyVar']
access_secret = os.environ['AccessSecretVar']

# Tweepy Auth
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth, wait_on_rate_limit = True)

noFavRtTweet = []
mentionTweet = []
noDeleteTweet = []

def lambda_handler(event, context):
    # No Favorite No RT Tweet
    print("==========No Favorite No RT Tweet==========")
    for tweet in tweepy.Cursor(api.user_timeline,exclude_replies = True).items():
        if tweet.favorite_count == 0 and tweet.retweet_count == 0: #Change according to the number of Favs
            print(tweet.id,tweet.created_at,tweet.text.replace('\n',''))
            noFavRtTweet.append(tweet.id)

    # Reply Tweet
    print("==========Reply Tweet==========")
    for mentions in tweepy.Cursor(api.mentions_timeline).items():
        print(mentions.id,mentions.created_at,mentions.text.replace('\n',''))
        mentionTweet.append(mentions.in_reply_to_status_id)

    print("==========No Favorite No RT Reply Tweet==========")
    # No Favorite No RT Reply Tweet
    for tweet in noFavRtTweet:
        for reptw in mentionTweet:
            if tweet == reptw:
                print(api.get_status(tweet).id,api.get_status(tweet).created_at,api.get_status(tweet).text.replace('\n',''))
                noDeleteTweet.append(tweet)

    # Extraction Delete Tweet
    print("==========Extraction Delete tweet==========")
    perfectList = set(noFavRtTweet) ^ set(noDeleteTweet)
    print(list(perfectList))

    # Delete Tweet
    print("==========delete tweet==========")
    for deltw in perfectList:
        print(api.get_status(deltw).id,api.get_status(deltw).created_at,api.get_status(deltw).text)
        api.destroy_status(deltw)

Deploy to AWS

--Tweepy is an external module, so it is included.

pip install tweepy --target ./code

--Package and transfer to S3

aws cloudformation package --s3-bucket $YourBucketName `
--template-file lambda.yml `
--output-template-file lambda-packaged.yml

--Infrastructure construction and deployment --Here, specify the Twitter API KEY in the Lambda environment variable.

aws cloudformation deploy `
--template-file lambda-packaged.yml `
--stack-name $YourStackName `
--parameter-overrides AccessSecret=$YourAccessSecret `
ConsumerKey=$YourConsumerKey ` 
ConsumerSecret=$YourConsumerSecret ` 
AccessKey=$YourAccessKey `
--capabilities CAPABILITY_NAMED_IAM

--Check from the mannequin

Full version on GitHub

https://github.com/trysaildaisuki/DeleteNoReactionReply

truth

-This article is a by-product ――It is good to set countermeasures against Fabo explosion from the number of Favs of your tweets.

Recommended Posts

Make ordinary tweets fleet-like with AWS Lambda and Python
Dynamic HTML pages made with AWS Lambda and Python
Notify HipChat with AWS Lambda (Python)
Site monitoring and alert notification with AWS Lambda + Python + Slack
[AWS] Using ini files with Lambda [Python]
[AWS] Link Lambda and S3 with boto3
Make a scraping app with Python + Django + AWS and change jobs
Install pip in Serverless Framework and AWS Lambda with Python environment
Connect to s3 with AWS Lambda Python
Touch AWS with Serverless Framework and Python
Python + Selenium + Headless Chromium with aws lambda
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
Try to make foldl and foldr with Python: lambda. Also time measurement
Easy server monitoring with AWS Lambda (Python) and result notification in Slack
LINE BOT with Python + AWS Lambda + API Gateway
Serverless application with AWS SAM! (APIGATEWAY + Lambda (Python))
Amazon API Gateway and AWS Lambda Python version
[# 1] Make Minecraft with Python. ~ Preliminary research and design ~
Make Lambda Layers with Lambda
Collecting tweets with Python
Posting tweets with python
AWS CDK with Python
[# 2] Make Minecraft with Python. ~ Model drawing and player implementation ~
Let's make a simple game with Python 3 and iPhone
Solve simultaneous ordinary differential equations with Python and SymPy.
[AWS] Make friends with Lambda's JSON input (Python version)
Deploy Python3 function with Serverless Framework on AWS Lambda
Create a Layer for AWS Lambda Python with Docker
I want to AWS Lambda with Python on Mac!
Encryption and decryption with Python
Operate TwitterBot with Lambda, Python
Python and hardware-Using RS232C with Python-
[Python] Scraping in AWS Lambda
Make Puyo Puyo AI with Python
Make a fortune with Python
AWS Lambda with PyTorch [Lambda import]
python with pyenv and venv
Search twitter tweets with python
Works with Python and R
Associate Python Enum with a function and make it Callable
[Python] Make AWS resources mocked with Moto into pytest fixtures
Create API with Python, lambda, API Gateway quickly using AWS SAM
I tried to make GUI tic-tac-toe with Python and Tkinter
Easily build network infrastructure and EC2 with AWS CDK Python
Shining life with Python and OpenCV
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
Make Echolalia LINEbot with Python + heroku
Robot running with Arduino and python
AWS Lambda + Twilio Make Google Calendar reminders call with voice notifications
Neural network with OpenCV 3 and Python 3
Summary if using AWS Lambda (Python)
AM modulation and demodulation with python
Make apache log csv with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
[AWS] Create API with API Gateway + Lambda
Let's make a GUI with python.
Scraping with Python, Selenium and Chromedriver
[Machine learning] Try running Spark MLlib with Python and make recommendations
Text extraction with AWS Textract (Python3.6)
Scraping with Python and Beautiful Soup