简体   繁体   English

使用Twython发送推文,twitter api错误

[英]Using Twython to send a tweet, twitter api error

I'm trying to make python send a tweet for me using Twython but for some reason everything I'm trying isn't working. 我正在尝试让python使用Twython为我发送一条推文,但出于某种原因,我正在尝试的一切都不起作用。

I've followed the Twython README but still unable to acheive what I want. 我跟着Twython自述文件,但仍无法实现我的想法。

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 以上是从@justhalf提供的代码中收到的回溯

Thanks SMNALLY 谢谢SMNALLY

There is a far simpler way to update your post as opposed to the way Twython actually shows you. 有一种更简单的方法来更新您的帖子,而不是Twython 实际向您展示的方式。 It will take more work on your API console space though, so let me begin. 但是,在API控制台空间上需要做更多的工作,所以让我开始吧。

  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. 默认情况下,您应该位于“ 详细信息”选项卡 在此输入图像描述

  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: 之后,向下滚动,直到看到: 在此输入图像描述

  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 . 现在,在您选择该选项后向下滚动,直到您看到一个蓝色按钮,说明更新此Twitter的应用程序设置

  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): 转到底部并生成所需的令牌,请注意您可能需要多次单击按钮才能使其工作(同样,当令牌为时,请确保您的访问级别为读取,写入和直接消息生成): 在此输入图像描述

  6. Now you have everything necessary for connecting and posting to your twitter account. 现在,您已拥有连接和发布到您的Twitter帐户所需的一切。 You have the Consumer key and the Consumer Secret , the Access token and the Access token secret . 您具有Consumer keyConsumer SecretAccess tokenAccess 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): 好的,现在转到你的代码编辑器,并编写下面的样板代码(这些键不起作用,我只是摆脱了应用程序,所以没有黑客在这里:P我只是给它们作为长度的指示你应该期待的钥匙):

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". 在此之后,检查你的推特,你应该看到一条新的推文,上面写着“你好,来自Python!:D”。

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 现在您已将oauth_verifier存储到变量中,您将需要创建一个新的Twython实例并获取最终用户令牌

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 ? 所以你似乎错过了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 . 之后我想你需要用最终的OAUTH_TOKENOAUTH_TOKEN_SECRET创建另一个新的Twython实例。 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. 我没有Twitter应用程序密钥,所以我无法尝试。

But I guess this should be enough to resolve your problem. 但我想这应该足以解决你的问题。 I hope this helps. 我希望这有帮助。 =) =)

Note that I used the requests package from Python. 请注意,我使用了Python的requests包。

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 代码返回Twitter API returned a 401 (Unauthorized), Invalid or expired token的原因是返回Twitter API returned a 401 (Unauthorized), Invalid or expired token ,在调用get_authentication_tokens()后需要oauth_verifier尝试成功调用twitter并获取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: auth ['auth_url']将打印一个类似的响应:

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

browse to this URL to authorize your app 浏览到此URL以授权您的应用

在此输入图像描述

After the app gets authorize, it will send the client to your callback_url 在应用程序获得授权后,它会将客户端发送到您的callback_url

The callback_url will be appended with the oauth_verifier callback_url将附加oauth_verifier

something like http://google.com/?oauth_verifier=xxxxxx&oauth_token=xxxxxx 例如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 根据您正在使用的webframework,您需要获取 oauth_verifier的响应现在创建一个新的Twython实例

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状态:

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 并按照@Games Brainiac的说明更新twitter的应用程序设置

I am adding to the following discussion that a connection to another server might also prevent the connection on the stream api. 我在以下讨论中添加了与另一台服务器的连接也可能会阻止流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... 例如,我打开了一个Rserve()并且一直收到401错误,但是当我在命令提示符下使用Rilla时,授权被授予了......

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). 通常,如果要使用应用程序更新状态,则必须使用OAuth1.1身份验证(称为用户身份验证 - 而不是仅应用程序身份验证)进行身份验证。

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). 不幸的是,对于任何创建Twitter应用程序的人来说,这需要大量额外的代码(其中app auth仅需要3或4行代码)。

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 . 前一段时间我其实已经张贴用瓶和Twython OAuth1.1处理(没有错误处理,你可以处理这个你希望的任何方式)全码在这里 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) (代码可能不完美,可能会有所改进 - 我是一个相当新手的程序员)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM