1

我正在尝试使用 python 发送自动推文。

我已经尝试了两个不同的包 python-twitter 和 tweepy,但使用任何一个包都没有成功。这些解决方案在这里讨论:

Twitter API:简单状态更新 (Python) 如何从 Django 发推文?

首先,我应该明确一点,几个小时前我刚刚创建了一个 Twitter 帐户,用于发送推文。使用 dev.twitter.com,我已将访问级别设置为“读取、写入和直接消息”,并创建了使用者和访问令牌密钥。

使用这些密钥,我使用 python-twitter 包连接到 twitter。我知道它至少部分有效,因为我可以访问 The Biebs 推文:

>> CONSUMER_KEY = 'XXXX'
>> CONSUMER_SECRET = 'XXXX'
>> ACCESS_TOKEN_KEY= 'XXXX'
>> ACCESS_TOKEN_SECRET= 'XXXX'

>> import twitter
>> api = twitter.Api()
>> api = twitter.Api(
>>     consumer_key=CONSUMER_KEY, 
>>     consumer_secret=CONSUMER_SECRET, 
>>     access_token_key=ACCESS_TOKEN_KEY, 
>>     access_token_secret=ACCESS_TOKEN_SECRET
>> )

>> statuses = api.GetUserTimeline("justinbieber")
>> for s in statuses:
>>     print s.text    

http://t.co/q58qksxp its not finished but heres a little part a song I'm working on
sorry http://t.co/Vtu4Lc2Q
video is at 13 percent done uploading
<... Other Inanities from The Bieb Snipped. You get the picture...>

但是,当我尝试发送推文时,我收到错误消息:“无法使用 OAuth 进行身份验证。”

>> api.PostUpdate('Testing Twitter!')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/python_twitter-0.8.5-py2.7.egg/twitter.py", line 2838, in PostUpdate
    data = self._ParseAndCheckTwitter(json)
  File "/usr/local/lib/python2.7/dist-packages/python_twitter-0.8.5-py2.7.egg/twitter.py", line 3869, in _ParseAndCheckTwitter
    self._CheckForTwitterError(data)
  File "/usr/local/lib/python2.7/dist-packages/python_twitter-0.8.5-py2.7.egg/twitter.py", line 3892, in _CheckForTwitterError
    raise TwitterError(data['error'])
twitter.TwitterError: Could not authenticate with OAuth.

有人可以解释为什么吗?由于这不起作用,我决定安装并尝试 tweepy。

但是当我尝试使用它时,它给了我错误“无效或过期的令牌”

>> import tweepy
>> def tweet(status):
>>     '''
>>     updates the status of my twitter account
>>     requires tweepy (https://github.com/joshthecoder/tweepy)
>>     '''
>>     if len(status) > 140:
>>         raise Exception('status message is too long!')
>>     auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
>>     auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
>>     api = tweepy.API(auth)
>>     result = api.update_status(status)
>>     return result    
>>     
>> result = tweet('Testing Twitter!')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in tweet
  File "/usr/local/lib/python2.7/dist-packages/tweepy-2.0-py2.7.egg/tweepy/binder.py", line 185, in _call
    return method.execute()
  File "/usr/local/lib/python2.7/dist-packages/tweepy-2.0-py2.7.egg/tweepy/binder.py", line 168, in execute
    raise TweepError(error_msg, resp)
tweepy.error.TweepError: [{u'message': u'Invalid or expired token', u'code': 89}]

这里的解决方案是什么?我的 Twitter 密钥错了吗?

4

1 回答 1

1

我不确定您是编辑了它们还是只是忘记将它们放入您的代码中,但您需要您的身份验证密钥才能访问 Twitter 帐户。

此处概述了该过程:http: //www.pythoncentral.io/introduction-to-tweepy-twitter-for-python/

于 2014-02-28T17:51:35.473 回答