Ccmmutty logo
Commutty IT
3 min read

Tweepy (Twitter API)の使い方

https://cdn.magicode.io/media/notebox/fe6e73f4-de0b-45ac-948b-7e148ea201d8.jpeg
Tweepyについて書いていこうと思います。 今回使用するAPIの系列はTwitter API v2のほうです。 未完成です

1.インストール

Windowsの場合
pip install tweepy
Linux/Macの場合
pip3 install tweepy

2.Clientの作成

client = tweepy.Client(
    consumer_key="API / Consumer Key here",
    consumer_secret="API / Consumer Secret here",
    access_token="Access Token here",
    access_token_secret="Access Token Secret here"
)

3.Tweetの取得

tweet=client.get_tweet("tweet_id here")
{
  "data": {
    "id": "1460323737035677698",
    "text": "Introducing a new era for the Twitter Developer Platform! nn📣The Twitter API v2 is now the primary API and full of new featuresn⏱Immediate access for most use cases, or apply to get more access for freen📖Removed certain restrictions in the Policynhttps://t.co/Hrm15bkBWJ https://t.co/YFfCDErHsg",
    "edit_history_tweet_ids": [
      "1460323737035677698"
    ]
  }
}
tweetはこのようになるのでツイートのテキストを取得したい場合は、
text=tweet.data.get('text')
で取得できます。
上記の例ではツイートのIDとテキストしか取得していませんが、いいねの数なども確認できます。 その場合は、
tweet=client.get_tweet("tweet_id here",tweet_fields="public_metrics,author_id")
のように書けます。
このとき、いいねの数は
count_fav=tweet.data.get("public_metrics").get("like_count")
で取得できます。
取得できるデータの種類についてはTwitter Devloper - Tweets lookupを参考にしてください。

4.Userの取得

user=client.get_user("user's id here")
で取得できます。
いわゆるユーザーIDで調べたい場合は、
user=client.get_user(username="username here")
と書けます。
リスポンスの例
{
  "data": {
    "id": "2244994945",
    "name": "Twitter Dev",
    "username": "TwitterDev"
  }
}
ツイートを取得した時と同じく、

Discussion

コメントにはログインが必要です。