2021年の11月にTwitterAPIの仕様変更が実施されてV2が標準になったのをきっかけにTwitterAPIのラッパーライブラリのTweepyもV2用にバージョンアップが行われました。
それにより関数の名前や引数などがV1.1の書き方と変わっているケースが多く、ネットの情報もV1.1とV2.0のものが混在していて自分もググっていて混乱するので、Tweepy(TwitterAPI v2)でツイート検索やユーザー情報を取得するサンプルコードを纏めてみました。TwitterAPI v2の使い方などで困っている人の助けになれば幸いです。
Contents
Tweepyのインストール
Tweepyはバージョンで関数名などが変わっているため、バージョンを統一します。本記事では4.10.0を使用しています。バージョンを指定してPIPでライブラリをインストールする場合は以下のコマンドを実行してください。
#Tweepyのインストール $ pip install tweepy==4.10.0
ライブラリの読み込みとAPIの設定
import tweepy
from datetime import datetime
from datetime import timedelta
import json
import requests
import traceback
import os
import pandas as pd
# ライブラリのバージョン確認 tweepyのバージョンは4.10.0です
print(f'tweepyのバージョンは{tweepy.__version__}です')
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'
bearer = 'xxx'
#APIインスタンスの作成
client = tweepy.Client(bearer)
api = tweepy.Client(None, consumer_key, consumer_secret, access_token, access_token_secret)
ツイート検索
# ツイート取得
import pprint
for tweet in tweepy.Paginator(client.search_recent_tweets, query='ワンピース lang:ja -is:retweet',
tweet_fields=['id','created_at','entities','public_metrics','attachments','text','author_id','lang',],
user_fields=['description','protected','name','username','public_metrics','profile_image_url'],
expansions='author_id',max_results=10).flatten(limit=1):
pprint.pprint(tweet.data)
tweet_id = tweet.data['id']
print(f'サンプルツイートID:{tweet_id}')
lang:ja は検索結果を日本語のツイートのみ絞る
-is:retweetはRTを除外すること指定しています。
他の検索条件のクエリについては以下参照
<実行結果>
{
'author_id': '196098708',
'created_at': '2022-09-17T12:48:26.000Z',
'entities': {'mentions': [{'end': 16, 'id': '241810950', 'start': 3, 'username': 'hirayama8emi'}]},
'id': '1571118883427483649',
'lang': 'ja',
'public_metrics': {'like_count': 0, 'quote_count': 0, 'reply_count': 0, 'retweet_count': 127},
'text': 'RT @hirayama8emi: まぁたんゆりりん夜の部!\n' '\n' 'まちこの想像力と、べーせんの神対応と、ゆいとんのきゅるんとした可愛いさ!見習いたい…!w\n' '恋バナで盛り上がったのとっても楽しかったなー!\n' '\n' '爆モテナイトという事でワンピースを着ました!メイクさんとゆいとんがTシャツ…'
}
中身は変わりますが、こんな感じの情報が取得できます。
今回は例なので1件だけを取得するようにしていますが、
max_resultsとLimitは数字を変えれば取得件数が増えます。
また「tweet_id」は下のコードでいいねやRTを行う際に使用します。
「author_id」はツイート主のアカウント内部IDを指します。
アカウント情報を取得する
いいね・RTのサンプルアカウントは私自身のアカウントを使います。
Twitterアカウント→ @python_mllover
user=api.get_user(username='python_mllover',
user_fields=['description','protected','name','username','public_metrics','profile_image_url']
,user_auth=True)
print(user)
<実行結果>
Response(data=<User id=965799286117027841 name=ミナピ(ピン) username=python_mllover>, includes={}, errors=[], meta={})
user_fieldsで指定しているプロフィール内容やフォロー数・フォロワー数などの情報が一見取得出来ているようには見えませんが、ちゃんと取得できています。user_fieldsの情報は以下のようにして抽出することができます
# アカウントのフォロー・フォロワー情報を取得する print(user.data.public_metrics)
<実行結果>
{‘followers_count’: 2582, ‘following_count’: 2505, ‘tweet_count’: 900, ‘listed_count’: 6}
参照:https://qiita.com/aki4003/items/5bc6b97ef496bd094edd
アカウントのフォロワー情報を取得する
#ユーザーのフォロワーを出力 followers_data = api.get_users_followers(id=965799286117027841,user_auth=True) followers_data
実行すると以下のようにフォロワーのアカウント情報を取得することができます。
<実行結果>
Response(data=[<User id=1571085711524401152 name=ななは username=IaeBGMnjLFKtbGY>, <User id=1567934684868354048 name=謙一朗☘ビジネス案内人/フリーランス username=qinylngbijines3>,…
アカウントのツイートを取得する
# 特定のユーザーのツイートを取得する api.get_users_tweets(965799286117027841, max_results=100,user_auth=True)
その他引数などは公式ドキュメント参照
アカウントのフォロー情報を取得する
#フォロー取得 follows_data = api.get_users_following(id=965799286117027841,user_auth=True) print(follows_data)
Response(data=[<User id=1571085711524401152 name=ななは username=IaeBGMnjLFKtbGY>, <User id=1567934684868354048 name=謙一朗☘ビジネス案内人/フリーランス username=qinylngbijines3>,…
ツイートを行う
# ツイート api.create_tweet(text="テストテスト")
特定のツイートにリプライを送る場合は引数の「in_reply_to_tweet_id」でツイートIDを指定します
# リプライを送る api.create_tweet( text=text, in_reply_to_tweet_id=tweet_id )
ツイートにいいねを付ける
# いいねを付ける api.like(tweet_id)
ツイートをリツイートする
# リツイートを行う api.retweet(tweet_id)
ユーザーをフォローする
# フォロー api.follow(target_user_id=965799286117027841)
<実行結果>
Response(data={‘following’: True, ‘pending_follow’: False}, includes={}, errors=[], meta={})
target_user_idは数値の内部IDを指定する必要があります。
‘pending_follow’は鍵垢をフォローした場合にTrueとなります。
ユーザーをフォロー解除(リムーブ)する
# フォロー解除 api.unfollow_user(target_user_id=965799286117027841)
ユーザーをブロックする
# Tweepy経由でユーザーをブロックする api.block(target_user_id=904318848622510080)
ユーザーをブロック解除する
# Tweepy経由でユーザーのブロック解除する api.unblock(target_user_id=904318848622510080)
ユーザーをミュートにする
# Tweepy経由でユーザーをミュートにする api.mute(target_user_id=904318848622510080)
ユーザーをミュートを解除する
# Tweepy経由でユーザーのミュートを解除する api.unmute(target_user_id=904318848622510080)

コメント