案件でTweepyでユーザーのブックマークツイートを取得する機能を作成したのですが、思ったより手間取ったのでやり方をメモしておきます。
前準備
これは自分もやってみるまで知らなかったのですが、TwitterのAPI経由でブックマークしたツイート情報を取得する際はapi鍵とアクセストークン以外にもoauth認証に使用するoauth2.0のクライアントIDとクライアントSecretが必要になります。
まずTwitter開発者用ポータルサイトのプロジェクト内のsettingにある「User authentication settings」をクリックしてリダイレクト用URLを設定する必要があります。(リダイレクト用URLはoauth認証を自作WEBアプリに組み込む、みたいなケース出ない限り適当なURLで大丈夫です。)
AppPermissionは「read and write and direct messeage」
type of appは「webapp bot」に設定してください

URLを設定したら「Keys and tokens」から「OAuth 2.0 Client ID and Client Secret」の項目でClient ID and Client Secretを生成して保存してください。またpermissionを変更した場合は上の4つのアクセスキーと認証トークンも再発行してください(そうしないとpermission設定の変更が反映されません)
関連記事:TweepyとTwitter API V2を使って大量のツイート情報をスクレイピングする

Tweepyでユーザーのブックマークツイートを取得する
前準備が終わったので実際にTweepyでブックマークツイートを取得したいと思います。
tweepyはバージョンで関数の書き方が変わるので、この記事ではtweepy==4.10.0を使用しています。
$ pip install tweepy==4.10.0
関連記事:Tweepyで 「API object has no attribute search」のエラー出る原因と解決法
まずは認証部分、各種トークンは自分のものに置き換えてください
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 = 'xxxx'
consumer_secret = 'xxxx'
access_token_secret = 'xxxx'
access_token = 'xxxx'
# oauth認証
oauth2_user_handler = tweepy.OAuth2UserHandler(
client_id='xxxx',
redirect_uri="https://tkstock.site/",
scope=["bookmark.read", "bookmark.write",
"tweet.read","users.read"],
# Client Secret is only necessary if using a confidential client
client_secret='xxxx'
)
ここで肝心なのは以下のコードでブックマークをOauth認証で読み取る際の権限を指定してあげる必要があります。ここでこの4つを指定しないと認証後にブックマークをclient.get_bookmarksで取得しようとして403 forbiddenになってしまうので注意してください
scope=[“bookmark.read”, “bookmark.write”,
“tweet.read”,”users.read”],
ちなみにスコープのリストについては、Tweepyの公式ドキュメントとTwitter の OAuth 2.0 Authorization Code Flow with PKCE ドキュメントの Scopes セクションを参照してください。
参考:https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code
参考:https://docs.tweepy.org/en/stable/authentication.html
# 次に認証 URL を取得します。
print(oauth2_user_handler.get_authorization_url())
#これを使用して、ユーザーにアプリを認証させることができます。完了すると、定したコールバック / リダイレクト URI / URL にリダイレクトされますので、その認証応答URLをINPUT文で渡してください。
すると戻り値の変数access_tokenの中のAPIレスポンスのdictの中にアクセストークンが格納されているので、それを再度input文の入力欄に張り付けてプログラムを実行してください。
ちなみにINPUT文を使っているのはoauth認証によるトークン認証を使っているのでそのままURLを叩くと「CSRF 検証に失敗したため、リクエストは中断されました」的なCSRF エラーが起こるためです。多分頑張ればinputを使わなくてもいい気がしますが、自分的にはこれで目的な達成したのでそれ以上は調べていません。
# Clientその後、初期化時にアクセス トークンを渡すことができます。
verifier = input("Enter whole callback URL: ")
access_token = oauth2_user_handler.fetch_token(verifier)
print("The returned access token is ", access_token)
accessCopy = input("Copy paste the access token here \n >")
client = tweepy.Client(accessCopy)
response = client.get_bookmarks(
expansions="author_id,attachments.media_keys",
tweet_fields="created_at,public_metrics,attachments",
user_fields="username,name,profile_image_url",
media_fields="public_metrics,url,height,width,alt_text")
# print(response)
tweets = response.data
users = {}
for user in response.includes['users']:
users[user.id] = f"{user.name} (@{user.username}) [{user.profile_image_url}]"
# process media attachment
media = {}
if 'media' in response.includes:
for item in response.includes['media']:
media[item.media_key] = f"{item.url} - {item.height}x{item.width} - Alt: {item.alt_text}"
tweets = response.data
# The expanded tweet offers a lot more data
for tweet in tweets:
print('-' * 50)
print(f"{tweet.id} ({tweet.created_at}) - {users[tweet.author_id]}:\n {tweet.text} \n")
metric = tweet.public_metrics
print(f"retweets: {metric['retweet_count']} | likes: {metric['like_count']}")
if tweet.attachments is not None:
for media_key in tweet.attachments['media_keys']:
print(f"Media attachment: #{media[media_key]}")
これでブックマークしたツイートのテキストと画像がある場合は画像のURLが取得できます。
保存したいは空のリストか何かを作って、appendしていけばよいと思います。
参照:https://docs.tweepy.org/en/stable/client.html#users
参照:https://stackoverflow.com/questions/73027084/tweepy-error-with-bookmarks-typeerror-unhashable-type-oauth2token
参照:https://improveandrepeat.com/2022/07/python-friday-131-working-with-bookmarks-in-tweepy/
コメント