Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active February 9, 2022 14:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/b7b19c81269edfaa94e392b01f618d17 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/b7b19c81269edfaa94e392b01f618d17 to your computer and use it in GitHub Desktop.
Delete all tweets older than 90 days
#!/usr/bin/env python
"""Deletes all tweets older than 90 days.
"""
from __future__ import print_function
# Dependencies: pip install twitter python-dateutil
import twitter
import dateutil.parser
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 age_timedelta(tweet):
"""Determine the age of a tweet.
Returns a datetime.timedelta value.
"""
created_at = dateutil.parser.parse(tweet['created_at'])
now = datetime.datetime.now(datetime.timezone.utc)
return now - created_at
def delete_tweets(tw, max_age_in_days = 90, count = 200):
"""Delete tweets older than the specified age.
Returns number of tweets deleted. Returns 0 when there are no old tweets to delete.
"""
deleted_count = 0
tweets = tw.statuses.user_timeline(count=count, exclude_replies=False)
for tweet in tweets:
age = age_timedelta(tweet)
if age.days > max_age_in_days:
id = tweet['id']
tw.statuses.destroy(id=id)
print('Deleted tweet {} with age {}\n{}\n--'.format(id, age, tweet['text']))
deleted_count += 1
return deleted_count
tw = twitter_login()
total_count = 0
while True:
count = delete_tweets(tw)
if count == 0:
break
total_count += count
if total_count > 0:
print('==\nDeleted tweet count: {}'.format(total_count))
else:
print('There are no old tweets to delete')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment