8
tweepy.error.TweepError: [{u'message': u'Invalid or expired token.', u'code': 89}]

Do tokens have to be hard coded? I have the OAuth and access tokens hard coded right now, but the token seems to expire every 24 hours. What can I do to renew the token programatically? Can I get a new token via Tweepy?

The goal of my script is to run overnight every day without my permission. I have it set as a cronjob. I don't want to do any manual entry.

I am just using the API on 1 account, my account. So I have the username/password, etc.

Normally, I get the token from clicking "Create my access token," then when I check back a few days later, the token is gone and the button to create it re-appears again.

enter image description here

After regenerating and using it for another day, it happened again! Screenshot: https://i.stack.imgur.com/yQuqU.png

User
  • 23,729
  • 38
  • 124
  • 207
  • Twitter states in their OAuth FAQ that they do not expire auth tokens. – Klaus D. May 10 '16 at 22:22
  • @KlausD. I know, isn't it strange? The token disappears after a day or two of use. It has done this to me 3 times now. I don't believe they are telling the truth. How can I handle this error anyways? I don't get how their statement can be true when it just randomly stops working? – User May 10 '16 at 22:23
  • How do you acquire the token? – Klaus D. May 10 '16 at 22:25
  • @KlausD. I click the button at https://apps.twitter.com/app/12312345/keys and I also just added a screenshot to the OP – User May 10 '16 at 22:26

2 Answers2

2

Not sure what the goal of your app is, but to answer some of your questions-concerns:

Do tokens have to be hard coded?

No, Depending on nature of the app you are coding, you can request this data upon executing your program via webform, or textfield in a GUI or include it in another file and encrypt it or import the file it is in and use it...

I have the OAuth and access tokens hard coded right now, but the token seems to expire every 24 hours. What can I do to renew the token programatically?

You cant for the API key and Consumer Secret, this has to be done manually. This information should be permanent, based on https://dev.twitter.com/oauth/overview

The access Token is another story, you can use the API to request one apparently: https://dev.twitter.com/oauth/reference/post/oauth/access_token

POST oauth/request_token Allows a Consumer application to obtain an OAuth Request Token to request user authorization. This method fulfills Section 6.1 of the OAuth 1.0 authentication flow. It is strongly recommended you use HTTPS for all OAuth authorization steps. Usage Note: Only ASCII values are accepted for the oauth_nonce

Resource URL https://api.twitter.com/oauth/request_token

Concerning the access token expiration:

How long does an access token last? We do not currently expire access tokens. Your access token will be invalid if a user explicitly rejects your application from their settings or if a Twitter admin suspends your application. If your application is suspended there will be a note on your application page saying that it has been suspended. as per twitter:

What do I do if an access token I have becomes invalid? You should plan that a user’s access token may become invalid at any time and you will need to re-authorize for that user in the case that it does. Ensuring you handle this situation gracefully is imperative for a quality user experience.

According to twitters documentation https://dev.twitter.com/oauth/application-only

API request contains invalid bearer token Using an incorrect or revoked bearer token to make API requests will result in:

HTTP/1.1 401 Unauthorized Content-Type: application/json; charset=utf-8 Content-Length: 61 ...

{"errors":[{"message":"Invalid or expired token","code":89}]}

Maybe this needs resolving on twitters side? I would suggest contacting them directyl https://dev.twitter.com/solutions/customer-service

glls
  • 2,325
  • 1
  • 22
  • 39
  • So API access requires user input every 24 hours? `via webform, or textfield in a GUI`. I notice you said something about encrypting and importing a file, which may mean that I don't need user input? – User May 20 '16 at 06:43
  • this can be covered here: http://stackoverflow.com/questions/7014953/i-need-to-securely-store-a-username-and-password-in-python-what-are-my-options maybe you can describe what kind of app you are coding for future reference. and No, api access does not require user input every 24hrs. again, depends what are your needs – glls May 20 '16 at 07:01
  • also, if you can provide code samples of what you are trying to achieve, and how you are getting the error using tweepy it would be helpfull – glls May 20 '16 at 07:17
  • I'm trying to follow and unfollow people – User May 23 '16 at 19:11
  • good to know =) ... again, if your token is being revoked every now and then, you should raise the flag with twitters customer service, this is not normal, ive had mine for a year now, for an app, and have not have mine revoked or expire – glls May 23 '16 at 19:14
0

You can get your access token using code below. I used configparser to store my config. Once you've got token it doesn't expire.

if not config['APP']['AUTH_SECRET'] or not config['APP']['AUTH_TOKEN']:
    try:
        redirect_url = auth.get_authorization_url()
        print redirect_url
    except tweepy.TweepError:
        print 'Error! Failed to get request token.'

    # Example w/o callback (desktop)
    # You even can start browser here
    verifier = raw_input('Go to URL above, authorize and enter the code:')

    try:
        auth.get_access_token(verifier)
    except tweepy.TweepError:
        print 'Error! Failed to get access token.'

    config['APP']['AUTH_SECRET'] = auth.access_token_secret
    config['APP']['AUTH_TOKEN'] = auth.access_token
    with open(CONFIG_FILE,'w') as configfile:
        config.write(configfile)
else:
    auth.set_access_token(config['APP']['AUTH_TOKEN'], config['APP']['AUTH_SECRET'])
andjelx
  • 199
  • 1
  • 13