はじめに
ホームページをクロールしてただツイートしたかっただけなのにハマったのでまとめた。
状況
ネットで検索すれば多数みつかる、以下のようなtweepyを使用したプログラムを実行するとエラーメッセージが出てツイートできない
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("ツイート文")
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 V2とTwitter API V1.1の両方が利用できるようなので問題はないかもしれない。
Twitter API V2に対応したプログラム
tweepy.API()ではなくtweepy.Client()を使用する。(tweepy V4.0.0以上が必要)
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 writeかRead and write and Direct messageである必要がある。(初期値はRead)
Developer PortalでAccess TokenとAccess Token Secretを生成する前にapp permissionsをRead(初期値)からRead and writeかRead and write and Direct messageに変更しておく。
App permissionsをRead(初期値)のままAccess TokenとAccess Token Secretを生成してしまった場合は、App permissionsを変更してからAccess TokenとAccess Token Secretを再生成すればよい。
参考
Twitter Deverloper Portal
tweepy ドキュメント
tweepy Twitter API v2 リファレンス
tweepy Twitter API v2 サンプルプログラム(Create Tweet)