Get only image tweets on twitter

Introduction

I often read childcare comics on Twitter, It's annoying when tweets other than manga are also displayed on the timeline, so Only manga (= image) tweets are acquired using the Twitter API.

Processing flow

  1. Get the users you are following (Twitter API)
  2. Get the timeline of each user (Twitter API)
  3. Judge the presence or absence of an image from the content of the tweet
  4. Like & retweet the one with the image (Twitter API)

By doing this, if you display your timeline, you can view only the tweets of the image at once.

Implementation

Twitter API authentication

API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET were obtained by referring to the following site. Detailed explanation from the example sentence of the 2020 version Twitter API usage application to the acquisition of the API key

python


twitter = OAuth1Session(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

1. Get the users you are following

First, get the username (screen name to be exact) of the user you are following. The endpoint uses https://api.twitter.com/1.1/friends/list.json. Up to 200 people seem to be API limits. Specify your own screen_name for the argument screen_name. (You can also get it with another person's screen name)

get_follow_screen_name


def get_follow_screen_name(screen_name):
    #Prepare an empty list
    follow_list = []

    #Authentication
    twitter = OAuth1Session(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    #Acquisition endpoint
    url = "https://api.twitter.com/1.1/friends/list.json"
    #Parameters
    params = {"screen_name": screen_name, "count": 200}

    #request
    res = twitter.get(url, params=params)

    if res.status_code == 200:
        result_json = json.loads(res.text)
        #Add followers to list
        for i in range(0, len(result_json["users"]), 1):
            follow_list.append(result_json["users"][i]["screen_name"])
        #Returns a list
        return follow_list
    else:
        return None

2. Get the timeline for each user

Use the screen_name of each user obtained in 1 to get the timeline and return it in JSON format. I want the latest tweets this time, so I set count = 1.

get_user_timeline


def get_user_timeline(screen_name):
    #Authentication process
    twitter = OAuth1Session(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    #Timeline acquisition endpoint
    url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
    #Parameters
    params = {
        "count": 1,
        "screen_name": screen_name,
        "include_entities": True,
        "exclude_replies": False,
        "include_rts": False,
    }

    #Get the timeline list from the response
    res = twitter.get(url, params=params)

    if res.status_code == 200:
        return json.loads(res.text)
    else:
        return None

3. Judge the presence or absence of an image from the content of the tweet

First, make the JSON file saved in 2 into the following class.

python


class Tweet:
    def __init__(self, json_file):
        self.created_at = json_file[0]["created_at"]
        self.tweet_id = json_file[0]["id"]
        self.text = json_file[0]["text"]
        self.user_name = json_file[0]["user"]["name"]
        self.user_screen_name = json_file[0]["user"]["screen_name"]
        self.user_mention = json_file[0]["entities"]["user_mentions"]
        self.image_urls_list = []

        #If there is an attachment
        if "extended_entities" in json_file[0]:
            self.media_number = len(json_file[0]["extended_entities"]["media"])
            self.content_type = json_file[0]["extended_entities"]["media"][0]["type"]

            for i in range(0, self.media_number, 1):
                self.image_urls_list.append(
                    json_file[0]["extended_entities"]["media"][i]["media_url"]
                )

        else:
            self.media_number = 0
            self.content_type = ""

Look at self.media_number = len (json_file [0] ["extended_entities"] ["media"]) Distinguish if an image has been posted.

is_content_type


def is_content_type(obj_tweet, expect_type):
    if obj_tweet.content_type == expect_type:
        return True
    else:
        return False

4. Like & retweet those with images

If the image has been posted, hit the API as shown below to like and retweet. All you have to do is specify the Tweet ID.

push_favorite


def push_favorite(tweet_id):
    #Authentication
    twitter = OAuth1Session(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

    #request
    url = "https://api.twitter.com/1.1/favorites/create.json"
    params = {"id": tweet_id}
    req = twitter.post(url, params=params)
    req_json = json.loads(req.text)

    if req.status_code == 200:
        return True
    #If you have already liked
    elif req.status_code == 403 and req_json["errors"][0]["code"] == 139:
        return True
    else:
        return False

retweet


def retweet(tweetId):
    twitter = OAuth1Session(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    url = "https://api.twitter.com/1.1/statuses/retweet/%d.json" % tweetId
    res = twitter.post(url)
    res_json = json.loads(res.text)

    if res.status_code == 200:
        return True
    #Already retweeted
    elif res.status_code == 403 and res_json["errors"][0]["code"] == 327:
        return True
    else:
        return False

Recommended Posts

Get only image tweets on twitter
Get delay information on Twitter and tweet
Get Twitter bookmarks on CentOS using Selenium
Program to get favorite images on Twitter
Get images from specific users on Twitter
twitter on python3
Get Twitter Trends
Get Twitter userData
Get a lot of Twitter tweets at once
Save tweets containing specific keywords in CSV on Twitter
Get Tweets with Tweepy
Get twitter tweets, followers, followers, likes, with urllib and beautifulSoup
I get "too early to create image" on tkinter
I analyzed tweets about the new coronavirus posted on Twitter
A barren Twitter posting client that saves only your tweets
Get Twitter timeline with python
Twitter posts on Python 3 etc.
Get image features with OpenCV
Search twitter tweets with python
Create a word cloud with only positive / negative words on Twitter
I analyzed the tweets about the new coronavirus posted on Twitter Part 2
I checked the image of Science University on Twitter with Word2Vec.