Eric
Eric

Reputation: 409

"code":32,"message":"Could not authenticate you." when using the access token obtained from tweepy

I was trying to use the chunk upload feature of twitter.

Reference: https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload-init

Since this feature is not available on tweepy, I was trying to implement that from scratch. However, since the user already login with the application using tweepy, tweepy saved the access token and secret of the user obtained there.

I tried to use these access token as following, but I got the error of "code":32,"message":"Could not authenticate you."

I want to explore a way that will not ask user to type their email and password again to upload video.

from requests_oauthlib import OAuth1, OAuth1Session
import os

def upload_video(video_file):
  video_file = os.path.join(MEDIA_ROOT, 'test_video.mp4')

  oauth_token = OAUTH_TOKEN
  oauth_token_secret = OAUTH_TOKEN_SECRET

  consumer_key = TWITTER_CONSUMER_TOKEN
  consumer_secret = TWITTER_CONSUMER_TOKEN_SECRET

  oauth = OAuth1Session(consumer_key,
                client_secret=consumer_secret,
                resource_owner_key=oauth_token,
                resource_owner_secret=oauth_token_secret,
                signature_method='HMAC-SHA1')

  headers = requests.utils.default_headers()

  headers.update(
    {
        'User-Agent': 'OAuth gem v0.4.4',
    }
  )

  video_url = 'https://upload.twitter.com/1.1/media/upload.json?command=INIT&total_bytes={size}&media_type={type}'.format(size=os.path.getsize(video_file), type='video/mp4')

  response = oauth.post(video_url,
                         headers=headers,
                         files=dict(foo='bar')) # to make it in multipart/form-data
  print(response.content)
  print(response.request.body)
  print(response.request.headers)  

I also printed out the request headers which was something like the following:

{'User-Agent': b'OAuth gem v0.4.4', 'Accept-Encoding': b'gzip, deflate', 'Accept': b'*/*', 'Connection': b'keep-alive', 'Content-Length': '141', 'Content-Type': b'multipart/form-data; boundary=f5c7d61e8ab8a14b2a22ced4171b723e', 
'Authorization': b'OAuth oauth_nonce="147920959083366377161589749583", oauth_timestamp="1589749583", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="consumer_key", oauth_token="oauth_token", oauth_signature="mcEaLBsANVu%2B7lavaNfrOiHZbgs%3D"'}

I also tried twurl command which did get a proper response back, but it required me to type in username and password and which generated a different set of oauth_token and secret from that of tweepy.

Upvotes: 0

Views: 724

Answers (1)

Eric
Eric

Reputation: 409

It turned out that the reason I got this was because I needed to put the params in the data instead of like queries.

This repository really helped me on how to upload videos to Twitter.

https://github.com/twitterdev/large-video-upload-python

Upvotes: 1

Related Questions