Categories We Write About

Create a tweet archive tool

Here’s a basic Tweet Archive Tool in Python using the tweepy library. It fetches a user’s tweets and stores them in a local .csv file.


Features:

  • Fetches tweets from a specified username

  • Saves tweet content, timestamp, and ID

  • Supports Twitter API v2 (via bearer token)


Requirements:

  • Twitter Developer account

  • Bearer Token (from Twitter API)

  • Python 3.x

  • tweepy and pandas libraries


Code:

python
import tweepy import pandas as pd # Twitter API credentials (use your Bearer Token) BEARER_TOKEN = "YOUR_TWITTER_BEARER_TOKEN" # Initialize client client = tweepy.Client(bearer_token=BEARER_TOKEN, wait_on_rate_limit=True) def get_user_id(username): try: user = client.get_user(username=username) return user.data.id except Exception as e: print("Error fetching user ID:", e) return None def archive_tweets(username, max_results=1000): user_id = get_user_id(username) if not user_id: return tweets_data = [] pagination_token = None total_fetched = 0 while total_fetched < max_results: try: response = client.get_users_tweets( id=user_id, max_results=min(100, max_results - total_fetched), pagination_token=pagination_token, tweet_fields=["created_at", "text", "id"] ) if not response.data: break for tweet in response.data: tweets_data.append({ "id": tweet.id, "created_at": tweet.created_at, "text": tweet.text }) total_fetched += 1 pagination_token = response.meta.get("next_token") if not pagination_token: break except Exception as e: print("Error fetching tweets:", e) break df = pd.DataFrame(tweets_data) df.to_csv(f"{username}_tweet_archive.csv", index=False) print(f"Archived {len(df)} tweets to '{username}_tweet_archive.csv'.") # Example usage: archive_tweets("elonmusk", max_results=500)

Notes:

  • Replace "YOUR_TWITTER_BEARER_TOKEN" with your actual bearer token.

  • The Twitter API currently limits tweet retrieval to the most recent ~3200 tweets per user.

Would you like a web-based version or a GUI version of this tool as well?

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About