Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Displays all users you follow that have not had activity (tweet/rt) within a specified number of days, sorted by least-recent.
#!/usr/bin/env python3
import datetime
import tweepy
def main():
consumer_key = "<add>"
consumer_secret = "<add>"
access_token = "<add>"
access_token_secret = "<add>"
interation_threshold_days = 90 # 90 Days
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
inactive_friends = get_inactive_friends(api, interation_threshold_days)
inactive_friends = sorted_by_val(inactive_friends)
if inactive_friends:
for k, v in inactive_friends.items():
# Max Twitter name length: 15; Max datetime length: 27
print("{k: >15} : {v: <27}".format(k=k, v=v))
print("No accounts meet threshold of >{} day of inactivity".format(interation_threshold_days))
def sorted_by_val(dictionary, reverse=False):
"""Returns a representation of a dictionary sorted by the value"""
return {k: v for k, v in sorted(dictionary.items(), key=lambda f: f[1], reverse=reverse)}
def get_inactive_friends(api, threshold):
"""Returns a dictionary of inactive Twitter friends
Determines a user is inactive if they have not tweeted or retweeted within the threshold.
@param api An authenticated tweepy API instance
@param threshold Integer in days to determine determine when a user is inactive
@return Dictionary of inactive Twitter friends
inactive_friends = dict()
for friend in tweepy.Cursor(api.friends).items():
latest_activity = get_latest_activity(api,
if latest_activity < - datetime.timedelta(days=threshold):
inactive_friends["{}".format(friend.screen_name)] = latest_activity.isoformat()
return inactive_friends
def get_latest_activity(api, user_id):
"""Returns the most recent tweet/retweet activity of a user, evaluating the last 10 statuses"""
return max(status.created_at for status in api.user_timeline(user_id, count=10))
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment