Question

I've tried writing a simple program to update my twitter status using Twython(version 3). I am able to do a search of the public timeline, but it returns a "Twitter API returned a 401 (Unauthorized)" when I try to update the status.

from twython import Twython

APP_KEY = 'xxx'
APP_SECRET = 'xxx'

OAUTH_TOKEN = 'xxx'
OAUTH_TOKEN_SECRET = 'xxx'

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

twitter.update_status(status='See how easy using Twython is!')

Does anyone have an idea what is wrong here?

Was it helpful?

Solution

You need to authenticate the user

twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens(callback_url='http://mysite.com/callback')

Store the oauth tokens from the auth variable and store them somewhere you can retrieve them from when the user returns;

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

How you store it depends on your framework

redirect the user to auth url auth['auth_url']

and in the callback, you can retrieve the oauth sessions Retrieve the oauth_verifier from the url params

Store the new tokens iin the sessionm, or wherever

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

twitter_authroized=twitter.get_authorized_tokens(oauth_verifier)

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

Use these new OAUTH tokens from now on to make calls to twitter (instead of the old ones)

Read https://twython.readthedocs.org/en/latest/usage/starting_out.html#authentication for this information

https://github.com/ryanmcgrath/twython-django‎ is django project for twitter. Use it for guidance

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