geduldig / TwitterAPI

Minimal python wrapper for Twitter's REST and Streaming APIs
936 stars 263 forks source link

Publish Tweets w/ v2 #228

Closed cboden closed 1 year ago

cboden commented 1 year ago

With Twitter's recent changes my long-running bot stopped working. In changing from API v1 to v2 my code has changed from:

api = TwitterAPI(
  os.getenv("TWITTER_API_KEY"),
  os.getenv("TWITTER_SECRET_KEY"),
  os.getenv("TWITTER_ACCESS_TOKEN"),
  os.getenv("TWITTER_ACCESS_SECRET"),
)
api.request("statuses/update", {"status": "Hello World!"})

to

api = TwitterAPI(
  os.getenv("TWITTER_API_KEY"),
  os.getenv("TWITTER_SECRET_KEY"),
  os.getenv("TWITTER_ACCESS_TOKEN"),
  os.getenv("TWITTER_ACCESS_SECRET"),
  api_version="2",
)
api.request("tweets", {"text": "Hello World"}, method_override="POST")

I'm receiving the following 403 error:

Your client app is not configured with the appropriate oauth1 app permissions for this endpoint.

What should I be doing?

cboden commented 1 year ago

I also attempted this code and received the following error:

TwitterAPI(
  oauth2_access_token=os.getenv("TWITTER_BEARER_TOKEN"),
  auth_type="oAuth2User",
  api_version="2",
)
api.request("tweets", {"text": "Hello World"}, method_override="POST")

Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint. Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 User Context].

geduldig commented 1 year ago

The following code worked for me.

from TwitterAPI import TwitterAPI, TwitterRequestError, TwitterConnectionError

try:
        api = TwitterAPI(
                consumer_key, consumer_secret, access_token_key, access_token_secret,
                auth_type='oAuth1',
                api_version='2')

        r = api.request('tweets', {'text':'a test to test'}, method_override='POST')

        for item in r:
                print(item)

except TwitterRequestError as e:
        print(e.status_code)
        for msg in iter(e):
                print(msg)

except TwitterConnectionError as e:
        print(e)

except Exception as e:
        print(e)
cboden commented 1 year ago

Thanks for getting back to me so quickly @geduldig. Your code is correct, the problem was on the Twitter side of things. I'll leave steps below in case anyone else comes across this: