I tried follow management with Twitter API and Python (easy)

Introduction

Have you ever wondered if your account is missing follow-ups or if you don't follow back? This time, I implemented a program that can display all accounts in one follow (I wonder?) State with Twitter API and Python! (There may be many apps that can be followed and managed, but please watch with warm eyes because it is a practice of Python lol)

output

It is like this

Getting the id and name of the user you are following...
Processd:  100.00 %
Done


Getting follower id and name...
Processd:  100.00 %
Done


Checking one follow...
Batch display of users who do not follow back

5    sample1
Name: name, dtype: object
Batch display of users who have followed but have not followed back

0    sample2
Name: name, dtype: object
Done

--The output is the same as the DataFrame of pandas. If you want to save csv, please modify the code by yourself.

What to use

--Twitter API: How to apply for use is introduced in various articles, so please refer to that. (** It is very important that you need to get a total of 4 types of API Key and Accesee Token. **) --tweepy: You can download it with pip install tweepy --Python3 series

code

Click here!
import tweepy
import pandas as pd
import time

def authorize():
    Consumer_key = 'My API Key'
    Consumer_secret = 'My API Secret Key'
    Access_token = 'My Access Token'
    Access_secret = 'Your Access Secret Token'
    authorization = [Consumer_key, Consumer_secret, Access_token, Access_secret]
    return authorization


def get_myaccount_data(authorization):
    auth = tweepy.OAuthHandler(authorization[0], authorization[1])
    auth.set_access_token(authorization[2], authorization[3])
    api = tweepy.API(auth, wait_on_rate_limit=True)
    return api


def get_friends_id(api):
    print("Getting the id and name of the user you are following...")
    df_friends = pd.DataFrame(columns=["id","name"])
    process_id = len(api.friends_ids())
    for i, user_id in enumerate(api.friends_ids()[:6]):
        if (i+1) % 5 == 0:
            print("Processd: ", round(((i+1)/process_id)*100,2),"%")
        time.sleep(1) #It may not be necessary. Uncomment if there are many people
        user = api.get_user(user_id)
        user_info = [user.id_str, user.name]
        df_friends.loc[i,"id"] = user_info[0]
        df_friends.loc[i,"name"] = user_info[1]
    print("Done")
    print("\n")
    df_friends.to_csv("./friends_ids.csv", index=False, encoding='utf-8-sig')
    return df_friends


def get_followers_id(api):
    print("Getting follower id and name...")
    df_followers = pd.DataFrame(columns=["id","name"])
    process_id = len(api.followers_ids())
    for i, user_id in enumerate(api.followers_ids()[:6]):
        if (i+1) % 5 == 0:
            print("Processd: ", round(((i+1)/process_id)*100,2),"%")
        time.sleep(1) #It may not be necessary. Uncomment if there are many people
        user = api.get_user(user_id)
        user_info = [user.id_str, user.name]
        df_followers.loc[i,"id"] = user_info[0]
        df_followers.loc[i,"name"] = user_info[1]
    print("Done")
    print("\n")
    df_followers.to_csv("./followers_ids.csv", index=False, encoding='utf-8-sig')
    return df_followers


def check_onesided_follow(df_friends, df_followers):
    print("Checking one follow...")
    #Check one follow by converting to set and giving the set difference
    friends = set(df_friends["id"])
    followers = set(df_followers["id"])
    # 1.Batch display of users who do not follow back
    diff1 = friends.difference(followers)
    diff1_list = list(diff1)
    print("Batch display of users who do not follow back\n")
    print(df_friends['name'][df_friends['id'].isin(diff1_list)])
    # 2.Batch display of users who have followed but have not followed back
    diff2 = followers.difference(friends)
    diff2_list = list(diff2)
    print("Batch display of users who have followed but have not followed back\n")
    print(df_followers['name'][df_followers['id'].isin(diff2_list)])
    print("Done")
    print("\n")

def main():
    #Consumer key and access token setting for using Twitter API
    authorization = authorize()
    #Get your account information with API
    api = get_myaccount_data(authorization)
    #friend(The account I followed)Get id and name of
    df_friends = get_friends_id(api)
    #Get follower id and name all at once
    df_followers = get_followers_id(api)
    #Follow one(I followed but did not follow back or followed me but I did not follow)of
    #Batch display of user names with print statement
    check_onesided_follow(df_friends, df_followers)
    
if __name__ == "__main__":
    main()

Impressions

It's easy if you use the API ~

The contents are almost the same, but it is also listed on GitHub, so please check it if you like. https://github.com/kkkodai/check-onesided-follwer-in-twitter

Recommended Posts

I tried follow management with Twitter API and Python (easy)
I tried to automate internal operations with Docker, Python and Twitter API + bonus
I tried Jacobian and partial differential with python
I tried function synthesis and curry with python
I tried scraping with Python
Use Twitter API with Python
I tried gRPC with Python
I tried scraping with python
Automatic follow on Twitter with python and selenium! (RPA)
Crawling with Python and Twitter API 1-Simple search function
I tried hitting the API with echonest's python client
Easy to use Nifty Cloud API with botocore and python
I tried web scraping with python.
I tried connecting Raspberry Pi and conect + with Web API
[Python] I tried to visualize the follow relationship of Twitter
I played with PyQt5 and Python3
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried running prolog with python 3.8.2.
Easy modeling with Blender and Python
I tried SMTP communication with Python
Crawling with Python and Twitter API 2-Implementation of user search function
I tried to make a periodical process with Selenium and Python
I tried to easily detect facial landmarks with python and dlib
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
Collecting information from Twitter with Python (Twitter API)
Python installation and package management with pip
I tried scraping Yahoo News with Python
I tried sending an email with python.
I tried non-photorealistic rendering with Python + opencv
I tried using UnityCloudBuild API from Python
I tried a functional language with Python
I tried recursion with Python ② (Fibonacci sequence)
I installed and used Numba with Python3.5
Easy web scraping with Python and Ruby
#I tried something like Vlookup with Python # 2
I tried to delete bad tweets regularly with AWS Lambda + Twitter API
[AWS] [GCP] I tried to make cloud services easy to use with Python
I tried to get the authentication code of Qiita API with Python.
I tried to get the movie information of TMDb API with Python
[Zaif] I tried to make it easy to trade virtual currencies with Python
I tried hitting Mastodon API with Ruby (Faraday) / Python (Pycurl) / PHP (Curl)
I tried updating Google Calendar with CSV appointments using Python and Google APIs
I tried "smoothing" the image with Python + OpenCV
I tried hundreds of millions of SQLite with python
[Python] I introduced Word2Vec and played with it.
I tried web scraping using python and selenium
I tried "differentiating" the image with Python + OpenCV
I tried "License OCR" with Google Vision API
I made a Twitter fujoshi blocker with Python ①
I tried L-Chika with Raspberry Pi 4 (Python edition)
I tried playing with PartiQL and MongoDB connected
I tried to get CloudWatch data with Python
I tried using mecab with python2.7, ruby2.3, php7
I tried super easy linear separation with Chainer
I tried to output LLVM IR with Python
I tried "binarizing" the image with Python + OpenCV
I tried running faiss with python, Go, Rust
I tried to automate sushi making with python
I tried playing mahjong with Python (single mahjong edition)
I tried "Receipt OCR" with Google Vision API
Get Gmail subject and body with Python and Gmail API