2
4

More than 1 year has passed since last update.

Twitter APIが You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, oauth) only. と言ってきた

Posted at

私が個人で運用しているTwitter botが気が付いたら以下のエラーメッセージで止まっていました。

You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, oauth) only. If you need access to this endpoint, you may need a different access level. You can learn more here: https://developer.twitter.com/en/portal/product

APIのv1.1ではなくv2を使えというメッセージです。

Twitter APIにアクセスしているライブラリがv2に対応しているかどうかの話になります。

いままではtwitterという名前のライブラリを使っていました。このライブラリのv2対応状況は以下に書いてあります。まだv2対応がalpha版という位置づけのようです。

tweepyというライブラリではv2に対応しているようです。

ということで、tweepyに置き換えることにしました。

twitterからtweepyに置き換え

requirements.txt 変更前

twitter

requirements.txt 変更後

tweepy

Pythonソースコード変更前(ツイート関連個所のみ)

import twitter

def tweet(message):
    auth = twitter.OAuth(
        consumer_key    = twitter_consumer_key,
        consumer_secret = twitter_consumer_secret,
        token           = twitter_token,
        token_secret    = twitter_token_secret,
    )
    client = twitter.Twitter(auth = auth)
    client.statuses.update(status = message)

Pythonソースコード変更後

import tweepy

 def tweet(message):
    client = tweepy.Client(
        consumer_key        = twitter_consumer_key,
        consumer_secret     = twitter_consumer_secret,
        access_token        = twitter_token,
        access_token_secret = twitter_token_secret,
    )
    client.create_tweet(text = message)

Twitter APIのエラーメッセージはこの変更だけで直りました。

おまけ

ひさしぶりにこのbotの自動ツイート部分をデプロイしたので、いろいろ変わっていました。

Serverless Frameworkのバージョン

bot開発当時Serverless Frameworkのバージョンが2だったのですが、いまは最新が3であり、私のローカル環境もいつのまにか3になっていたので、デプロイできなくなっていました。幸い serverless.yml でのバージョンの記載を変えるだけで動きました。

変更前

serverless.yml
frameworkVersion: '2'

変更後

serverless.yml
frameworkVersion: '3'

Pythonのバージョン

AWS LambdaのPythonランタイムがbot開発当時3.8だったのですが、いまは3.10が最新です。なので、今回ついでにPythonのバージョンも最新にしました。

変更前

serverless.yml
provider:
  name: aws
  runtime: python3.8

変更後

serverless.yml
provider:
  name: aws
  runtime: python3.10

urllib3のバージョン

ここまでの変更でAWS Lambdaで動かしたら以下のようなエラーメッセージがログに書き込まれ、動きませんでした。

[ERROR] Runtime.ImportModuleError: Unable to import module 'tweet': cannot import name 'DEFAULT_CIPHERS' from 'urllib3.util.ssl_' (/var/task/urllib3/util/ssl_.py)

urllib3というライブラリのバージョンを2より前にしないといけないという情報がありましたので、requirements.txt に以下のように書いたところ、直りました。なにが原因なのかはよくわかっていないです。

requirements.txt
tweepy
urllib3<2

以上。

2
4
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
2
4