Skip to content

Instantly share code, notes, and snippets.

Last active April 22, 2018 10:53
Show Gist options
  • Save keithrozario/2cf05656335e604e1ec1896c8ff4cd44 to your computer and use it in GitHub Desktop.
Save keithrozario/2cf05656335e604e1ec1896c8ff4cd44 to your computer and use it in GitHub Desktop.
Delete all tweets older than x days
import tweepy
from tweepy import TweepError
from datetime import datetime, timedelta
import logging
import json
from custom_config import consumer_key, consumer_secret, access_key, access_secret
tweets_delete = []
max_age = 90 # in days
archive_file = 'archive.jsonl'
# Logging setup
format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger(__name__)
console = logging.StreamHandler()
# Connecting to Twitter API via tweepy"Connecting to Twitter API")
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
# Getting Tweets over max_age days old"GETTING TWEETS under %d days" % max_age)
tweet_count = 1
for tweet in tweepy.Cursor(api.user_timeline).items():
if tweet.created_at < ( - timedelta(days=max_age)): # anything older than 90 days
'created_at': tweet.created_at,
'json': json.dumps(tweet._json)})
tweet_count += 1
if tweet_count%100 == 0:"Processed %d tweets" % tweet_count)"%d Tweets Processed" % tweet_count)"Found %d tweets older than %d days" % (len(tweets_delete) + 1, max_age))
# Archive tweets before deletion"Archiving tweets")
with open(archive_file, 'w') as archive:
tweet_count = 1
for tweet in tweets_delete:
archive.write(tweet['json'] + "\n")
tweet_count += 1"Archived %d tweets to %s" % (tweet_count, archive_file))
# Deleting Tweets
tweet_count = 1
for tweet in tweets_delete:
api.destroy_status(tweet['id'])'Tweet ID:%d from %s deleted!' % (tweet['id'], tweet['created_at']))
tweet_count += 1
except TweepError as e:'Tweet ID:%d could not be deleted due to %s' % (tweet['id'], e.response.text))"%d Tweets Deleted" % tweet_count)"END")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment