|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +Downloads all tweets from a given user. |
| 6 | +
|
| 7 | +Uses twitter.Api.GetUserTimeline to retreive the last 3,200 tweets from a user. |
| 8 | +Twitter doesn't allow retreiving more tweets than this through the API, so we get |
| 9 | +as many as possible. |
| 10 | +
|
| 11 | +t.py should contain the imported variables. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import print_function |
| 15 | + |
| 16 | +import json |
| 17 | +import sys |
| 18 | + |
| 19 | +import twitter |
| 20 | +from t import ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET |
| 21 | + |
| 22 | + |
| 23 | +def get_tweets(api=None, screen_name=None): |
| 24 | + timeline = api.GetUserTimeline(screen_name=screen_name, count=200) |
| 25 | + earliest_tweet = min(timeline, key=lambda x: x.id).id |
| 26 | + print("getting tweets before:", earliest_tweet) |
| 27 | + |
| 28 | + while True: |
| 29 | + tweets = api.GetUserTimeline( |
| 30 | + screen_name=screen_name, max_id=earliest_tweet, count=200 |
| 31 | + ) |
| 32 | + new_earliest = min(tweets, key=lambda x: x.id).id |
| 33 | + |
| 34 | + if not tweets or new_earliest == earliest_tweet: |
| 35 | + break |
| 36 | + else: |
| 37 | + earliest_tweet = new_earliest |
| 38 | + print("getting tweets before:", earliest_tweet) |
| 39 | + timeline += tweets |
| 40 | + |
| 41 | + return timeline |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + api = twitter.Api( |
| 46 | + CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET |
| 47 | + ) |
| 48 | + screen_name = sys.argv[1] |
| 49 | + print(screen_name) |
| 50 | + timeline = get_tweets(api=api, screen_name=screen_name) |
| 51 | + |
| 52 | + with open('examples/timeline.json', 'w+') as f: |
| 53 | + for tweet in timeline: |
| 54 | + f.write(json.dumps(tweet._json)) |
| 55 | + f.write('\n') |
0 commit comments