Prompt Detail:
Sure, I can help you with that. Here's a step-by-step guide on how to write a Python script that unfollows people on Twitter who have not posted in the last 12 months:
Step 1: Install necessary libraries
- First, you need to install the
tweepy
library which is used for accessing the Twitter API from Python. You can install it using pip by running the following command in your command prompt or terminal:
pip install tweepy
Step 2: Set up Twitter API credentials
- In order to access the Twitter API, you need to have a set of API credentials. You can get these by applying for a developer account on the Twitter Developer Dashboard. Once you have your credentials, you can store them in environment variables or directly in your script.
Step 3: Authenticate with Twitter API
- You need to authenticate your Python script with the Twitter API by using your API credentials. Here's some sample code that demonstrates how to do this:
pythonimport tweepy
# authenticate with Twitter API
auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")
auth.set_access_token("access_token", "access_token_secret")
# create API object
api = tweepy.API(auth)
Note: Replace "consumer_key"
, "consumer_secret"
, "access_token"
, and "access_token_secret"
with your actual API credentials.
Step 4: Get list of people you're following
- You can use the
API.friends()
method to get a list of people you're following on Twitter. Here's some sample code that demonstrates how to do this:
python# get list of people you're following
following = api.friends()
Step 5: Filter out people who have posted in the last 12 months
- For each person you're following, you can use the
API.user_timeline()
method to get their most recent tweets. You can then check the timestamp of their most recent tweet to see if it was posted more than 12 months ago. Here's some sample code that demonstrates how to do this:
pythonfrom datetime import datetime, timedelta
# filter out people who haven't posted in the last 12 months
for user in following:
tweets = api.user_timeline(screen_name=user.screen_name, count=1)
if tweets:
last_tweet_date = tweets[0].created_at
if datetime.now() - last_tweet_date > timedelta(days=365):
api.destroy_friendship(user.screen_name)
print(f"Unfollowed {user.screen_name}")
Step 6: Unfollow people who have not posted in 12 months
- Finally, you can use the
API.destroy_friendship()
method to unfollow people who have not posted in the last 12 months. Here's some sample code that demonstrates how to do this:
python# unfollow people who haven't posted in the last 12 months
for user in following:
tweets = api.user_timeline(screen_name=user.screen_name, count=1)
if tweets:
last_tweet_date = tweets[0].created_at
if datetime.now() - last_tweet_date > timedelta(days=365):
api.destroy_friendship(user.screen_name)
print(f"Unfollowed {user.screen_name}")
And that's it! You now have a Python script that can unfollow people on Twitter who have not posted in the last 12 months.