Python 为什么我无法发送推文?

1 投票
1 回答
2655 浏览
提问于 2025-04-17 15:28

我正在尝试用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密钥是错的吗?

1 个回答

1

我不太确定你是不是把它们删掉了,还是忘记在代码里加上,但你需要你的认证密钥才能访问你的推特账户。

具体的步骤可以在这里找到: http://www.pythoncentral.io/introduction-to-tweepy-twitter-for-python/

撰写回答