Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active August 12, 2018 01:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/46c3e4e1b4a3771380767aa8d44d7b92 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/46c3e4e1b4a3771380767aa8d44d7b92 to your computer and use it in GitHub Desktop.
Delete all tweets that are listed in a tweets.csv archive that are over 90 days old
#!/usr/bin/env python
"""Deletes all tweets in your 'tweets.csv' archive older than 90 days.
You can obtain your 'tweets.csv' archive by going to
<https://twitter.com/settings/account>, requesting your archive,
downloading it, and then extracting the 'tweets.csv' file.
"""
from __future__ import print_function
# Dependencies:
# pip install twitter python-dateutil
import twitter
import dateutil.parser
import csv
import datetime
# Go to http://apps.twitter.com/, create an app, and fill in these values:
consumer_key = 'aaa'
consumer_secret = 'bbb'
access_token = 'ccc'
access_token_secret = 'ddd'
def twitter_login():
"""Connect to Twitter.
Returns a Twitter instance.
"""
auth = twitter.OAuth(access_token, access_token_secret, consumer_key, consumer_secret)
return twitter.Twitter(auth=auth, retry=True)
def tweets_from_archive(filename = 'tweets.csv'):
"""Reads tweets from CSV file.
"""
with open(filename) as f:
reader = csv.DictReader(f)
return [row for row in reader]
def age_of_archived_tweet(tweet):
"""Determine the age of a tweet read from tweets.cxv.
Returns a datetime.timedelta value.
"""
created_at = dateutil.parser.parse(tweet['timestamp'])
now = datetime.datetime.now(datetime.timezone.utc)
return now - created_at
def delete_archived_tweet(twitter, tweet):
"""Delete a tweet read from tweets.csv.
"""
twitter.statuses.destroy(id=tweet['tweet_id'])
def delete_old_archived_tweets(twitter, filename = 'tweets.csv', max_age_in_days = 90):
"""Delete all tweets from archive older than the specified age.
Returns number of tweets deleted.
"""
deleted_count = 0
for tweet in tweets_from_archive(filename):
age = age_of_archived_tweet(tweet)
if age.days > max_age_in_days:
try:
delete_archived_tweet(twitter, tweet)
print('Deleted tweet {} with age {}'
.format(tweet['tweet_id'], age))
deleted_count += 1
except Exception as exc:
print('Unable to delete tweet {} with age {}: {}'
.format(tweet['tweet_id'], age, exc.args))
return deleted_count
tw = twitter_login()
count = delete_old_archived_tweets(tw)
print('\nDeleted tweet count:', count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment