1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Tweepy(v4.8.0)でユーザのプロフィール欄の取得方法がわからなかったのでTwitterAPIを直接叩いて取得する

Posted at

はじめに

ほぼ備忘録的なものですが、他に困ってる方がいるかもしれないので、一応残しておきます。

当方の手元の環境のtweepyのバージョンは4.8.0です。

!pip list | grep tweepy
# tweepy                     4.8.0

私のTwitterのプロフィール欄「自然言語処理を主に...」って文章を取ることを目指します。

スクリーンショット 2022-09-24 23.06.39.png

tweepyget_userを使ってuser idを取得する

TwitterAPIを叩くときにユーザIDがいるのですが、ユーザIDはtweepyget_userを使って取得します。
get_userの引数に必要なusernameはTwitterアカウントの@以降の文字列を指定します。

import tweepy

# 認証に必要なキーとトークン
# 環境変数として設定してます。
BEARER_TOKEN = os.getenv('TW_BEARER_TOKEN')
API_KEY = os.getenv('TW_API_KEY')
API_SECRET = os.getenv('TW_API_SECRET')
ACCESS_TOKEN = os.getenv('TW_ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.getenv('TW_ACCESS_TOKEN_SECRET')

client = tweepy.Client(bearer_token=BEARER_TOKEN,
                       consumer_key=API_KEY,
                       consumer_secret=API_SECRET,
                       access_token=ACCESS_TOKEN,
                       access_token_secret=ACCESS_TOKEN_SECRET
                      )

user_result = client.get_user(username='m_k_696')
user_result.data
# <User id=947117893757448197 name=m__k username=m_k_696>

私のユーザIDは947117893757448197であることがわかりました。

このget_userにも引数としてuser_fieldsが指定できるのですが、こちらでdescriptionを指定してもプロフィール欄が取得できないんですよねぇ。どっかが間違ってるのだろうか。。。

user_result = client.get_user(username='m_k_696', user_fields='description')
user_result
# Response(data=<User id=947117893757448197 name=m__k username=m_k_696>, includes={}, errors=[], meta={})
# ↑ プロフィール欄の情報が取得できてない

TwitterAPIを直接叩いてプロフィール欄を取得する

せっかくなのでpythonからTwitterAPIを叩こうと思います。subprocessを使って以下のようにTwitterAPIを実行すれば簡単にプロフィール欄を取得できました。

import subprocess

user_result = subprocess.run([
    'curl',
    f'https://api.twitter.com/2/users?ids=947117893757448197&user.fields=description',
    '-H',
    f'Authorization: Bearer {BEARER_TOKEN}'
], capture_output=True, text=True).stdout
user_result = eval(user_result)
user_result
# {'data': [{'name': 'm__k',
#  'description': '自然言語処理を主に勉強しており、Qiitaに実装重視で初学者にもわかりやすくをモットーに記事を投稿しています。Twitterでも読んだ論文や実装における細かなTipsとかをつぶやいたりしています。',
#  'id': '947117893757448197',
#  'username': 'm_k_696'}]}

無事にプロフィール欄の情報が取れました。

おわり

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?