如何使用python-twitter检索我发布的所有推文?

时间:2016-07-09 23:34:27

标签: python twitter python-twitter

我在我的网络应用程序中使用python-twitter发布这样的推文:

import twitter
twitter_api = twitter.Api(
    consumer_key="BlahBlahBlah",
    consumer_secret="BlahBlahBlah",
    access_token_key="BlahBlahBlah",
    access_token_secret="BlahBlahBlah",
)
twitter_api.PostUpdate("Hello World")

如何检索发布到此帐户的所有推文(包括之前从其他Twitter客户端发布到此帐户的推文)?我想这样做,以便我可以通过在每条推文上调用twitter_api.destroyStatus()来删除它们。

1 个答案:

答案 0 :(得分:1)

一种方法可能如下:

import twitter
api = twitter.Api(consumer_key='consumer_key',
                      consumer_secret='consumer_secret',
                      access_token_key='access_token',
                      access_token_secret='access_token_secret')

# get user data from credentials
user_data = api.VerifyCredentials()

user_id = long(user_data.id)
max_status_id = 0 

# repeat until all tweets are deleted
while True:

  # let us get 200 statuses per API call. 
  # trim_user helps improve performance by reducing size of return value
  timeline_args = {'user_id': user_id, 'count': 200, 'trim_user': 'true'}

  # if not first iteration, use max_status_id seen so far
  if max_status_id != 0:
    timeline_args['max_id'] = max_status_id

  # Get statuses from user timeline
  statuses = api.GetUserTimeline(**timeline_args)

  #if no more tweets are left, then break the loop
  if statuses is None or len(statuses) == 0:
    break 

  for status in statuses:
    # remember max_status_id seen so far
    max_status_id = long(status.id) - 1

    # delete the tweet with current status[id]
    api.DestroyStatus(status.id)