Using Twython to send a tweet, twitter api error
Asked Answered
R

5

15

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

Rosemonde answered 30/9, 2013 at 13:16 Comment(5)
Answered the question. Solution completely works :)Tornado
the reason why the code is returning Twitter API returned a 401 (Unauthorized), Invalid or expired token is it needs 'oauth_verifier' after get_authentication_tokens() more on it here also this might be helpfulLeyla
check this answer to get oauth_verifierLeyla
Thanks Simon I will check it out.Rosemonde
@Rosemonde Was I able to solve your problem?Tornado
T
42

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".

Tornado answered 5/10, 2013 at 10:15 Comment(7)
If the answer worked for you, please say something. Because I was helping a friend with this problem. I gave him the same solution.Tornado
yeap, this works well, up vote for mentioning the settings part on apps page of twitter, also I want to add make sure the box Allow this application to be used to Sign in with Twitter is uncheckedLeyla
@SimonKB You don't really need that to be turned on. It was turned off for me, and I was able to post my message on twitter. I don't think it matters on client side.Tornado
hmm, sorry about it, it seems to be working fine with it checked as well, my bad.Leyla
Perfect answer :) Works perfectly :)Rosemonde
So I'm doing this, but it gives me a 401 can't authenticate error when trying to upload media files likes images. Any ideas about how to deal with that?Trehala
+1 I happened to try to make my cli work following through Twitter documentation. All things failed, but need enable Read, Write and Direct message as per your suggestion so I can finally update tweet via REST API. Horrible documentation :( Thanks again!Inflow
T
3

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.

Thunderhead answered 3/10, 2013 at 1:38 Comment(4)
Hi @Thunderhead thanks for your reply, In your first line where you define twitter you can't have OAUTH_TOKEN and OAUTH_TOKEN_SECRET because you haven't been able to get the tokens, the part what is supposed to get tokens is auth = twitter.get_authentication_tokens() If I print auth I get the token numbers and everything needed but it seems to expire straight away, also where do I define what account(s) to login/post with? Any thoughts? Many thanks SMNALLYRosemonde
The first code in my sample is not the first line, I copied it from the documentation. It is supposed to be put after your first twitter definition. See the update on my answer.Thunderhead
sorry, not your first twitter definition, but the second.Thunderhead
I attempted to do this the same way, but the API has changed a little.Tornado
L
0

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

Leyla answered 9/10, 2013 at 9:37 Comment(0)
D
0

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...

Dimpledimwit answered 6/6, 2017 at 16:28 Comment(0)
C
0

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)

Cigarillo answered 27/9, 2017 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.