Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter API returned a 401 (Unauthorized), Invalid or expired token

I am using the below code to post a Tweet. This is a pretty standard authentication procedure but for some reason I cannot authenticate. The error I am getting is Twitter API returned a 401 (Unauthorized), Invalid or expired token.

from twython import Twython, TwythonError
import requests

APP_KEY = 'rpOzpgp2FZNJqsq0' #fake key
APP_SECRET = 'FKBJWXOJwXTblhi1xBl4PtKgPemNFvumH' #fake secret

twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()

OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

oauth_verifier_url = auth['auth_url']
oauth_verifier = requests.get(oauth_verifier_url)

# Getting the FINAL authentication tokens
final_step = twitter.get_authorized_tokens(oauth_verifier)

OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

twitter.update_status(status='Yo')

Here is the full error message:

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    final_step = twitter.get_authorized_tokens(oauth_verifier)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/twython/api.py", line 380, in get_authorized_tokens
    ken'), error_code=response.status_code)
twython.exceptions.TwythonError: Twitter API returned a 401 (Unauthorized), Invalid / expired To             ken

Why could I be getting this error and what can I do to fix it?

I have tried regenerating my keys multiple times. I have even deleted my app and created new ones multiple times but I still keep getting this error.

Under Application Settings my access level is set to read and write:

Screenshot of app page

I am not behind a firewall.

I have read other solutions concerning Twython authentication on this site but they all seem to provide the above code as the solution but this itself is not working for me.

like image 294
Adriaan Joubert Avatar asked Nov 09 '22 00:11

Adriaan Joubert


1 Answers

I was facing the same problem, but after regeneration of keys the problem got solved.

like image 56
Ritesh Avatar answered Nov 14 '22 22:11

Ritesh