PythonでツイッターAPI v2を使う

Last Updated: 2022/02/09 02:51:09

oauth を扱うライブラリはたくさんあるので好きなものを使えばよいが、私の場合は requests_oauthlibOAuth1Session を使っている。

マニュアルはこちら (opens new window)
ここにまとめている以外にもAPIはたくさんあるので、随時更新します。

# セッションオブジェクトの生成

基本的には OAuth1Session をインポートし、get メソッドか post メソッドを呼び出すだけでよい。

# requests_oauthlib をインストール

$ pip install requests_oauthlib
1

# Python の基本的なコード

from requests_oauthlib import OAuth1Session

# 1. Create Twitter Session
twitter = OAuth1Session(
    # Your own Keys
    'Consume Key', 
    'Cuosume Secret',
    "Access Token",
    "Access Secret Key"
)

# 2. Request Twitter API
res = twitter.get(...)

# 3. Do something with the response data
if res.status_code == 200:
    data = json.loads(res.text)
    print(pprint.pformat(data))
else:
    raise Exception("Status code(%d) : %s" % (res.status_code, res.text))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# ユーザー情報取得

# GET /2/users/:id

res = twitter.get("https://api.twitter.com/2/users/1301851771703160833", params={
    'expansions' : 'pinned_tweet_id', # pinned tweet is added in `includes.tweets`
    'tweet.fields' : 'attachments' ,  # `includes.tweets` only when `expansions=pinned_tweet_id` is requested.
                                        # attachements
                                        # author_id
                                        # context_annotations
                                        # conversation_id
                                        # created_at
                                        # entities
                                        # geo
                                        # id
                                        # in_reply_to_user_id
                                        # lang
                                        # non_public_metrics
                                        # public_metrics
                                        # organic_metrics
                                        # promoted_metrics
                                        # possibly_sensitive
                                        # referenced_tweets
                                        # reply_settings
                                        # source
                                        # text
                                        # withheld
    'user.fields' : 'description',  # user fields on `data`
                                        # created_at
                                        # description
                                        # entities
                                        # id
                                        # location
                                        # name
                                        # pinned_tweet_id
                                        # profile_image_url
                                        # protected
                                        # public_metrics
                                        # url
                                        # username
                                        # verified
                                        # withheld
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

# GET /2/users

res = twitter.get("https://api.twitter.com/2/users", params={
    # (Required) user ids
    "ids" : "1461537035320438785,1292439870586011649", 

    # same as `/2/users/:id`
    'expansions' : 'pinned_tweet_id', 
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6
7
8
9

# GET /2/users/by

res = twitter.get("https://api.twitter.com/2/users/by", params={
    # (Required) usernames
    "usernames" : "Yamam0t08202008", 

    # following parameters are the same as `/2/users/:id`
    'expansions' : 'pinned_tweet_id', 
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6
7
8
9

# GET /2/users/by/username/:username

res = twitter.get("https://api.twitter.com/2/users/by/username/Yamam0t08202008", params={
    # following parameters are the same as `/2/users/:id`
    'expansions' : 'pinned_tweet_id', 
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6

# ツイート情報取得

# GET /2/tweets/:id

res = twitter.get("https://api.twitter.com/2/tweets/1466948088728518659" , params={
    "expansions" : "attachments.poll_ids",  # Additional data 
                                                # attachments.poll_ids
                                                # attachments.media_keys
                                                # author_id
                                                # entities.mentions.username
                                                # geo.place_id
                                                # in_reply_to_user_id
                                                # referenced_tweets.id
                                                # referenced_tweets.id.author_id
    "media.fields" : "preview_image_url",   # Media fields
                                                # duration_ms
                                                # height
                                                # media_key
                                                # preview_image_url
                                                # type
                                                # url
                                                # width
                                                # public_metrics
                                                # non_public_metrics
                                                # organic_metrics
                                                # promoted_metrics
                                                # alt_text
    "place.fields" : "name",                # Place fields
                                                # contained_within
                                                # country
                                                # country_code
                                                # full_name
                                                # geo,
                                                # id
                                                # name
                                                # place_type
    "poll.fields" : "voting_status",        # Poll fields
                                                # duration_minutes
                                                # end_datetime
                                                # id,
                                                # options
                                                # voting_status
    
    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# GET /2/tweets

res = twitter.get("https://api.twitter.com/2/tweets", params={
    # (Required) tweet ids
    "ids" : "1466948088728518659", 
    
    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# ユーザータイムライン

# GET /2/users/:id/tweets

res = twitter.get("https://api.twitter.com/2/users/1461537035320438785/tweets", params={
    "end_time"         : "2021-12-07T10:18:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "start_time"       : "2010-11-06T00:00:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "exclude"          : "replies" ,             # retweets | replies
    "max_results"      : 10,                     # 5-100
    "pagination_token" : ".....",                # use `next_token` or `previous_token` in response
    "since_id"         : "1466948088728518659",  # tweet id
    "until_id"         : "1466948088728518659",  # tweet id

    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# GET /2/users/:id/mentions

res = twitter.get("https://api.twitter.com/2/users/1301851771703160833/mentions", params={
    "end_time"         : "2021-12-07T10:18:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "start_time"       : "2010-11-06T00:00:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "max_results"      : 10,                     # 5-100
    "pagination_token" : ".....",                # use `next_token` or `previous_token` in response
    "since_id"         : "1466948088728518659",  # tweet id
    "until_id"         : "1466948088728518659",  # tweet id

    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# ツイート検索

# GET /2/tweets/search/recent

res = twitter.get("https://api.twitter.com/2/tweets/search/recent", params={
    # (Required) search query
    # You can find how to build a query in `https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/build-a-query`
    'query': '#Python', 

    "end_time"         : "2021-12-07T01:44:00Z", # YYYY-MM-DDTHH:mm:ssZ (ISO 8601/RFC 3339).
    "start_time"       : "2021-12-01T00:00:00Z", # YYYY-MM-DDTHH:mm:ssZ (ISO 8601/RFC 3339).
    "max_results"      : 10,                     # 5-100
    "next_token"       : "b26v8....w8xc0vx",     # use `meta.next_token` in response
    "since_id"         : "1466948088728518659",  # tweet id
    "until_id"         : "1466948088728518659",  # tweet id

    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# リツイート

# GET /2/tweets/:id/retweeted_by

res = twitter.get("https://api.twitter.com/2/tweets/1292439870586011649/retweeted_by", json={
    'expansions' : 'pinned_tweet_id', # pinned tweet is added in `includes.tweets`

    "max_results"      : 10,          # 10-100
    "pagination_token" : ".....",     # use `next_token` or `previous_token` in response

    # following parameters are the same as `/2/tweets/:id`
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# POST /2/users/:id/retweets

res = twitter.post("https://api.twitter.com/2/users/1292439870586011649/retweets", json={
    "tweet_id" : "1466948088728518659", # tweet id to RT
})
1
2
3

# DELETE /2/users/:id/retweets/:source_tweet_id

res = twitter.delete("https://api.twitter.com/2/users/1292439870586011649/retweets/1466948088728518659")
# リクエストが成功した場合、戻り値の `data.retweeted` は `False` になります。
1
2

# いいね

# GET /2/tweets/:id/liking_users

res = twitter.get("https://api.twitter.com/2/users/1292439870586011649/liking_users", json={
    'expansions' : 'pinned_tweet_id', # pinned tweet is added in `includes.tweets`

    "max_results"      : 10,          # 10-100
    "pagination_token" : ".....",     # use `next_token` or `previous_token` in response

    # following parameters are the same as `/2/tweets/:id`
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# GET /2/users/:id/liked_tweets

res = twitter.get("https://api.twitter.com/2/users/1292439870586011649/liked_tweets", json={
    "max_results"      : 10,          # 10-100
    "pagination_token" : ".....",     # use `next_token` or `previous_token` in response

    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids",
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# POST /2/users/:id/likes

res = twitter.post("https://api.twitter.com/2/users/1292439870586011649/likes/", json={
    "tweet_id" : "1466948088728518659", # tweet id
})
1
2
3

# DELETE /2/users/:id/likes/:tweet_id

res = twitter.delete("https://api.twitter.com/2/users/1292439870586011649/likes/1466948088728518659")
# `data.liked` will be `False` in successful response.
1
2

Last Updated: 2022/02/09 02:51:09
Copyright © Web Ninja All Rights Reserved.