|
| 1 | +import csv |
| 2 | + |
| 3 | +import tweepy |
| 4 | + |
| 5 | +# Twitter API credentials |
| 6 | +consumer_key = "" |
| 7 | +consumer_secret = "" |
| 8 | +access_key = "" |
| 9 | +access_secret = "" |
| 10 | + |
| 11 | + |
| 12 | +def get_all_tweets(screen_name: str) -> None: |
| 13 | + |
| 14 | + # authorize twitter, initialize tweepy |
| 15 | + auth = tweepy.OAuthHandler(consumer_key, consumer_secret) |
| 16 | + auth.set_access_token(access_key, access_secret) |
| 17 | + api = tweepy.API(auth) |
| 18 | + |
| 19 | + # initialize a list to hold all the tweepy Tweets |
| 20 | + alltweets = [] |
| 21 | + |
| 22 | + # make initial request for most recent tweets (200 is the maximum allowed count) |
| 23 | + new_tweets = api.user_timeline(screen_name=screen_name, count=200) |
| 24 | + |
| 25 | + # save most recent tweets |
| 26 | + alltweets.extend(new_tweets) |
| 27 | + |
| 28 | + # save the id of the oldest tweet less one |
| 29 | + oldest = alltweets[-1].id - 1 |
| 30 | + |
| 31 | + # keep grabbing tweets until there are no tweets left to grab |
| 32 | + while len(new_tweets) > 0: |
| 33 | + print(f"getting tweets before {oldest}") |
| 34 | + |
| 35 | + # all subsiquent requests use the max_id param to prevent duplicates |
| 36 | + new_tweets = api.user_timeline( |
| 37 | + screen_name=screen_name, count=200, max_id=oldest |
| 38 | + ) |
| 39 | + |
| 40 | + # save most recent tweets |
| 41 | + alltweets.extend(new_tweets) |
| 42 | + |
| 43 | + # update the id of the oldest tweet less one |
| 44 | + oldest = alltweets[-1].id - 1 |
| 45 | + |
| 46 | + print(f"...{len(alltweets)} tweets downloaded so far") |
| 47 | + |
| 48 | + # transform the tweepy tweets into a 2D array that will populate the csv |
| 49 | + outtweets = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] |
| 50 | + |
| 51 | + # write the csv |
| 52 | + with open(f"new_{screen_name}_tweets.csv", "w") as f: |
| 53 | + writer = csv.writer(f) |
| 54 | + writer.writerow(["id", "created_at", "text"]) |
| 55 | + writer.writerows(outtweets) |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + # pass in the username of the account you want to download |
| 60 | + get_all_tweets("FirePing32") |
0 commit comments