LoginSignup
52
32

More than 1 year has passed since last update.

tweepy + Twitter API V2でツイート

Last updated at Posted at 2021-12-07

はじめに

ホームページをクロールしてただツイートしたかっただけなのにハマったのでまとめた。

状況

ネットで検索すれば多数みつかる、以下のようなtweepyを使用したプログラムを実行するとエラーメッセージが出てツイートできない

sample_APIv1.1.py
import tweepy

# Twitter Deverloper Portalで取得
ck = 'あなたのAPI Key'
cs = 'あなたのAPI Key Secret'
at = 'あなたのAccess Token'
ats = 'あなたのAccess Token Secret'

auth = tweepy.OAuthHandler(ck, cs)
auth.set_access_token(at, ats)
api = tweepy.API(auth)

api.update_status("ツイート文")
errormessage.log
tweepy.errors.Forbidden: 403 Forbidden
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve

エラーメッセージの要点は以下2点

  • Essential(エッセンシャル)アクセスではTwiter API V2しか使用できない
  • このAPIを使用したい場合Elevated(エレベイティッド)アクセスを申請することが必要

ハマった原因

Twitter社は1か月ほど前(2021/11/15)に開発者向けプラットフォーム(開発者向けプログラム)を更新した。
自分は数日前に開発者登録したので無料かつ登録のみで使用できるEssentialレベルで登録したのだが、EssentialレベルはTwitter API V2しか使用できずtweepyを使ってツイートするには別のやり方が必要だった。(ネットで見つかるサンプルはTwitter API V1.1向けが多いようだ)
なお、Twitter API V2を申請済みの以前からの開発者は上位のElevatedレベルに自動的に移行されてTwitter API V2Twitter API V1.1の両方が利用できるようなので問題はないかもしれない。

Twitter API V2に対応したプログラム

tweepy.API()ではなくtweepy.Client()を使用する。(tweepy V4.0.0以上が必要)

sample_APIv2.py
import tweepy

# Twitter Deverloper Portalで取得
ck = 'あなたのAPI Key'
cs = 'あなたのAPI Key Secret'
at = 'あなたのAccess Token'
ats = 'あなたのAccess Token Secret'

client = tweepy.Client(consumer_key=ck, consumer_secret=cs, access_token=at, access_token_secret=ats)

#パラメータ名を省略したい場合
#client = tweepy.Client(None, ck, cs, at, ats)

client.create_tweet(text="ツイート文")

その他の注意

ツイートするためにはApp permissions(アプリケーションレベルのパーミッション)がRead and writeRead and write and Direct messageである必要がある。(初期値はRead)

Developer PortalAccess TokenAccess Token Secret生成する前にapp permissionsRead(初期値)からRead and writeRead and write and Direct message変更しておく
App permissionsRead(初期値)のままAccess TokenAccess Token Secret生成してしまった場合はApp permissionsを変更してからAccess TokenAccess Token Secret再生成すればよい

参考

Twitter Deverloper Portal
tweepy ドキュメント
tweepy Twitter API v2 リファレンス
tweepy Twitter API v2 サンプルプログラム(Create Tweet)

52
32
3

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
52
32