我正在尝试使用python发送自动推文。
我尝试过两个不同的软件包python-twitter和tweepy,但是使用这两个软件包都没有成功。这些解决方案在这里讨论:
Twitter API: simple status update (Python) How to tweet from 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的密钥错了吗?
答案 0 :(得分:1)
我不确定您是否编辑过它们或只是忘记将它们放入您的代码中,但您需要使用身份验证密钥才能访问Twitter帐户。
此过程概述如下: http://www.pythoncentral.io/introduction-to-tweepy-twitter-for-python/