Basically, this is a new script, very handy to clear all your older tweets and to also keep yourself private/safe online.
An example of this is shown in the video below:
Brief Code Review
Script is 148 lines long, with comments and could be shorter without constants included, error controls and just some variations which come in handy at runtime.
Firstly, the required libraries. All are standard Python3 libraries with the exception of tweepy which is available here. I think I may have used pip3 to install but can’t remember – either way it’s fairly easy.
import tweepy import os import time import datetime
Second thing to note is the sleep timer. I learnt the slow way with Twitter API coding that the rate limitations will infuriate you. It’s something like 200 requests in a 15 minute period or something like that. This sleep timer is activated anytime you hit one of these limits and rather than exit, it should sleep for 5 minutes and go into a new window.
# Sleep Timer - WARNING: this prevents a RateLimitError, so be careful changing it (unit = seconds) SLEEP_TIMER = 5*60
Set the option of tweet age – in this case, it will delete all tweets older than 7 days, you could set this to 0 if you wanted to delete everything.
# Age of tweet - default: all tweets older than 7 days AGE_OF_TWEET = 7
Here is where the code actually does the dirty work. It uses tweepy’s Cursor method to paginate api calls which you can then loop through before going back for the next page.
When the age of the tweet is older than 7 days a call to api.destroy_status is made with the tweet’s ID included. That will delete/destroy the tweet.
for get_statuses in tweepy.Cursor(api.user_timeline, screen_name=target_username, count=1).pages(): for status in get_statuses: try: # Get API returned variables ready tweet_id = status.id tweet_text = (status.text).replace("\n", "") tweet_creation_date = status.created_at # Get the age of the tweet in days - e.g. return of "8" indicates it was 8 days ago difference = get_days(tweet_creation_date) # If the age of the tweet is greater than the pre-set variable (set at the top), then deleteif difference > AGE_OF_TWEET: deleted += 1print ("#" + str(deleted) + ": \t Deleting this tweet --> " + tweet_text) api.destroy_status(tweet_id) # Sleep just a tiny bit... time.sleep(SMALL_SLEEP) except: continue
Scheduling the script
If using Linux, like in this example, add the script into a cronjob and run it once a month, every week etc… to regularly delete your tweets if you want to clear your history.
View the code here…
View/obtain the code – by clicking here for GitHub
(Disclaimer: I’m not a software engineer so I’m aware there may be sexier ways to do this…)