Social media usage has exploded over the last decade. According to thorough research by the Kepios team, there were 5.22 billion (63.8% of the world’s total population) social media users worldwide by the beginning of October 2024.
Platforms such as X (formerly Twitter) are the foundation of modern life, and people and companies use them to connect, share updates, and exchange materials. Conversely, increased social media presence can also come with risks; statements can resurface many years later, become contentious, humiliating or obsolete, and cause you problems. That’s why today’s correct maintenance of social media profiles is so crucial.
Follow Artsyl on X for expert tips on optimizing business processes, from invoice handling to order management.
Fortunately, Python scripting and automation allow you to control your X presence without a lot of time-consuming effort. In this post, you will see how to quickly erase past X tweets in bulk using the Python programming language and the Tweepy module.
Before diving into the code, let’s briefly discuss the benefits of automating your tweet deletion process:
Save time. It’s tedious and time-consuming to review and delete old tweets manually. You can mass delete tweets instantly with TweetEraser, while automation handles the busy work of identifying and removing tweets that meet your criteria in the background.
Maintain account hygiene. Tweet pruning on a regular basis makes sure that your account remains relevant, focused and professional — both to new and old followers.
Reduce future issues. Proactively deleting outdated, unimportant, or problematic tweets reduces potential reputation damage down the road. Out of sight, out of mind.
Customize as needed. With automated scripts, you have granular control over which tweets are deleted, from time-based criteria to keyword filtering and beyond.
Schedule and forget. Once you have the script in place, you can set up automated deletions as often as you need them, with no additional work.
Now that you’ve covered the main benefits let’s examine how to implement automated tweet deletion with Tweepy and Python.
Recommended reading: Saving Money on Document Processing
Before you can delete tweets programmatically, you need the following:
When you have those in place, you can then get to the script itself.
The first step is to authenticate against the X API with OAuth. This makes our Python script run securely on the account that needs tweets deleted.
Here’s an overview of the credential components needed:
Get Real-Time Updates on Process Automation!
Follow Artsyl on X for the latest in document processing, automation best practices, and case studies.
Inside your Python script, you need to import Tweepy and instantiate an OAuth handler like so:
import tweepy
auth = tweepy.OAuthHandler(“consumer_key”, “consumer_secret”)
auth.set_access_token(“access_token”, “access_token_secret”)
Replace the credential string values with your keys. With the auth handler configured, you can now create an API instance.
The Tweepy API client provides the interface to the X platform, allowing us to query data and perform account actions. Initialize your API client like this:
api = tweepy.API(auth)
You now have full access to Tweepy endpoints to call! Next, you can write functions to gather and delete tweet data.
You want reusable functions that handle querying tweets and deleting any that meet set criteria. Here is a simple delete_tweets function as an example:
def delete_tweets(days_to_keep=30):
# Get timeline tweets
timeline = tweepy.Cursor(api.user_timeline).items()
for tweet in timeline:
# Calculate tweet age
tweet_age = datetime.now() — tweet.created_at
# Delete old tweets
if tweet_age > days_to_keep:
try:
api.destroy_status(tweet.id)
print(“Deleted tweet from”, tweet.created_at)
except Exception as e:
print(“Delete failed:”, e)
This grabs tweets from the account timeline, calculates their age, and deletes any that are older than the defined days_to_keep parameter. You can improve on this further, but it’s a good starting point!
Recommended reading: What Are the Latest Trends in Financial Technology (FinTech)?
Some ways to extend the functionality:
The key is the api.destroy_status() call actually deletes the tweet by its ID. Now let’s look at running the script.
To finish up, you just need actually to run our tweet deletion script. Here is a simple example of Python code to execute it:
# Authenticate
auth = tweepy.OAuthHandler(..)
auth.set_access_token(..)
api = tweepy.API(auth)
# Define functions
def delete_tweets(..):
# .. see above ..
# Invoke deletion
if __name__ == “__main__”:
delete_tweets(days=30)
print(“Old tweets deleted successfully!”)
And that’s it! The script will now automatically connect to the X API, gather your account’s tweets, determine any that are older than 30 days, and permanently delete them.
Stay ahead with the latest trends in process automation! Get access to exclusive insights and tools by joining Artsyl X. Book a demo and learn how our solutions can transform your business.
So far, what you’ve covered is just the foundation. In this case, let’s talk about how you can extend this script to make tweet deletion more robust and tailored to your needs.
Rather than manually running the script whenever you’d like to purge old tweets, use the Python schedule module to run it automatically on a recurring schedule you specify.
For example, to delete tweets older than 60 days every Monday:
import schedule
import time
def job():
delete_tweets(days=60)
schedule.every().monday.do(job)
while True:
schedule.run_pending()
time.sleep(1)
This allows fully hands-off tweet pruning without having to remember to start the script.
Recommended reading: Cloud-Based Automation: Best Practices
Rather than only checking tweet age, build in keywords, hashtags, links, and mention filtering to delete specific tweets that contain unwanted content.
For example:
def delete_tweets():
for tweet in timeline:
# Check text
if “badphrase” in tweet.text.lower():
api.destroy(tweet.id)
# Check entities
entities = [e[“text”] for e in tweet.entities[“hashtags”]]
if “oldhashtag” in entities:
api.destroy(tweet.id)
# etc..
This gives you finer-grained control over which tweets to delete.
Take the next step in automation beyond social media management. Streamline document processing and transform your workflows with docAlpha. Discover how it works—book your demo today!
Book a demo now
It’s good practice to log deleted tweets to a file, as well as set up email/SMS notifications if errors occur during automated runs.
For example:
import logging
from twilio.rest import Client
logging.basicConfig(filename=”deletes.log”, level=logging.INFO)
def delete_tweets():
for tweet in timeline:
try:
api.destroy(tweet.id)
logging.info(f”Deleted tweet {tweet.id}”)
except Exception as e:
print(“Delete failed:”, e)
# Send SMS notification
client = Client()
client.messages.create(..)
Logging and notifications are robust enough to monitor automated runs and troubleshoot problems.
Recommended reading: Document Capture Technology: Best Tips and Tricks
Contact Us for an in-depth
product tour!
As the use of X continues to grow each year, maintaining your X social media presence is important. Keeping your account professional is easy and flexible: automate tweet deletion using Python and Tweepy.
Once you have your foundations in place, you can customize and extend automated tweet management to meet your needs exactly. Pruning old or irrelevant tweets periodically keeps your X profile in shape and saves you time and effort.
In other words, use your Python skills, use Tweepy to easily access the X APIs, and hand the grunt work of keeping your tweet history squeaky clean over to automation!