Question

I'm trying to make python send a tweet for me using Twython but for some reason everything I'm trying isn't working.

I've followed the Twython README but still unable to acheive what I want.

Below is my latest attempted code:

from twython import Twython, TwythonError

APP_KEY = "KEYHERE"
APP_SECRET = "SECRETHERE"

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)

try:
    twitter.update_status(status='See how easy this was?')
except TwythonError as e:
    print e

On running the above code I get the following traceback error:

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

Does anyone know what I'm doing wrong and more importantly how do I fix this?

I dont have enough points for a bounty, but I would really appreciate the help!

Thanks in advance

edit

Traceback (most recent call last):
  File "C:\testtweet.py", line 20, in <module>
    final_step = twitter.get_authorized_tokens(oauth_verifier)
  File "C:\Python27\lib\site-packages\twython\api.py", line 313, in get_authorized_tokens
    raise TwythonError('Unable to decode authorized tokens.')
TwythonError: Unable to decode authorized tokens.

The above is the traceback recieved from the code supplied by @justhalf

Thanks SMNALLY

Was it helpful?

Solution

There is a far simpler way to update your post as opposed to the way Twython actually shows you. It will take more work on your API console space though, so let me begin.

  1. Firstly, you will need to go to your apps page. After you've selected the application that you are using right now, take a look at the page you are given. You should be at the Details tab by default. enter image description here

  2. Now that you are where you're supposed to be, click on the Settings tab right next to the Details tab as shown above.

  3. After that, scroll down until you see this: enter image description here

  4. Click the option as shown above. Now after you've selected the option scroll down until you see a blue button saying Update this twitter's application settings.

  5. Now, head back over to your Details tab. Go to the bottom and generate your required tokens, please note that you might have to click the buttons a couple of times to get it to work (also, make sure that your access level is Read, write, and direct messages when the token is generated): enter image description here

  6. Now you have everything necessary for connecting and posting to your twitter account. You have the Consumer key and the Consumer Secret, the Access token and the Access token secret. You have everything that you need.

Okay, now head over to your code editor, and write the following boiler-plate code (these keys wont work, I just got rid of the application, so no hacking here :P I've given them simply as an indication of the length of the keys that you should expect):

from twython import Twython

APP_KEY = ''  # Customer Key here
APP_SECRET = ''  # Customer secret here
OAUTH_TOKEN = '1936951807-z5bBNING8P1TU2onWvJh5dh8hoYlYAmNOaAx2OX'  # Access Token here
OAUTH_TOKEN_SECRET = 'QWJEZ7ridSeZGdxJELSBk7mupCpMA9q9sLCou5ywg'  # Access Token Secret here

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

twitter.update_status(status="Hello from Python! :D")

After this, check your twitter, you should see a new tweet saying "Hello from Python! :D".

OTHER TIPS

Let's try to find out together what went wrong.

I notice this in the documentation:

Now that you have the oauth_verifier stored to a variable, you'll want to create a new instance of Twython and grab the final user tokens

And the code below it:

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

final_step = twitter.get_authorized_tokens(oauth_verifier)

So it seems that you missed the final_step?

Then after that (from documentation):

Once you have the final user tokens, store them in a database for later use!:

OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECERT = final_step['oauth_token_secret']

After that I guess you will need to create another new Twython instance with the final OAUTH_TOKEN and OAUTH_TOKEN_SECRET. So the complete code would be something like this, I presume:

from twython import Twython, TwythonError
import requests

APP_KEY = "KEYHERE"
APP_SECRET = "SECRETHERE"

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)

### This is the part you're missing ###
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)
### Up until this line ###

try:
    twitter.update_status(status='See how easy this was?')
except TwythonError as e:
    print e

I don't have Twitter app key, so I can't try it.

But I guess this should be enough to resolve your problem. I hope this helps. =)

Note that I used the requests package from Python.

the reason why the code is returning Twitter API returned a 401 (Unauthorized), Invalid or expired token is it needs oauth_verifier after a call to get_authentication_tokens() Try thsse steps for a successful call to twitter & get the oauth_verifier

from twython import Twython, TwythonError

twitter = Twython(APP_KEY, APP_SECRET)

auth = twitter.get_authorization_tokens(callback_url='http://google.com')
oauth_token = auth['oauth_token']
oauth_token_secret = auth['oauth_token_secret']
print auth
print auth['auth_url']

auth['auth_url'] will print a response something like:

https://api.twitter.com/oauth/authenticate?oauth_token=xxxxxxxxx

browse to this URL to authorize your app

enter image description here

After the app gets authorize, it will send the client to your callback_url

The callback_url will be appended with the oauth_verifier

something like http://google.com/?oauth_verifier=xxxxxx&oauth_token=xxxxxx

depending on the webframework you are using you need to GET the response for oauth_verifier Now create a new Twython instance

twitter = Twython(APP_KEY, APP_SECRET, oauth_token, oauth_token_secret)
final_tokens = twitter.get_authorized_tokens(oauth_verifier)

print final_tokens

# these are the keys you will use to make calls on the users behalf from here on forward
f_oauth_token = final_tokens['oauth_token']
f_oauth_token_secret = final_tokens['oauth_token_secret']

Updating Twitter Status:

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

try:
    twitter.update_status(status='See how easy this was?')
except TwythonError as e:
    print e

And do Update twitter's application settings as mentioned by @Games Brainiac

I am adding to the following discussion that a connection to another server might also prevent the connection on the stream api. For example, I had a Rserve() open and kept getting the 401 error but when I killall Rserve in my command prompt , the authorization was granted...

Normally if you want to update a status using your app, you have to be authenticated using the OAuth1.1 authentication (which is being referred to as a User Authentication - as opposed to Application-only Authentication).

Unfortunately for anyone creating a Twitter app, this requires a lot of additional code (where app auth only requires like 3 or 4 lines of code).

Some time ago I have actually posted a full code for dealing with OAuth1.1 using Flask and Twython (without error handling, you could deal with this any way you wish) here. This solution is using session files to handle tokens, and then clears session on logout. (the code might not be perfect and could probably be improved - I am a rather novice programmer)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top