Removing Twitter favorites with Python and the Twitter REST API

A friend of mine needed a quick and easy way of removing all of his favorite Tweets. Here’s how to do just that using Python to access the Twitter REST API:

Requirements

I’m using requests along with requests-oauthlib.

Instructions

Create a Twitter app on your Twitter account (you’ll need this to gain access to the REST API. I followed the instructions in this really helpful post.

Then once you have a CONSUMER_KEY , CONSUMER_SECRET , OAUTH_TOKEN , and OAUTH_TOKEN_SECRET , run the below script as many times as you need to, to remove all of your favorited Tweets. You should be able to remove around 2,000 favorites (1 pass through of the script) before the API rate limit is reached. At that point just wait around 15 mins then run again.

Bob’s your uncle


import requests
from requests_oauthlib import OAuth1

CONSUMER_KEY = "Your consumer key"
CONSUMER_SECRET = "Your consumer secret"

OAUTH_TOKEN = "THE OAUTH TOKEN"
OAUTH_TOKEN_SECRET = "THE OAUTH TOKEN SECRET"

def get_oauth():
	oauth = OAuth1(CONSUMER_KEY,
				client_secret=CONSUMER_SECRET,
				resource_owner_key=OAUTH_TOKEN,
				resource_owner_secret=OAUTH_TOKEN_SECRET)
	return oauth

if __name__ == "__main__":
		oauth = get_oauth()
		
		for i in xrange(10):
	 		# get favorites tweet data (maximum 200 per call, "count=200"
			r = requests.get(url="https://api.twitter.com/1.1/favorites/list.json?count=200", auth=oauth)
	                # store fav_ids in a list
			fav_ids = [fav['id'] for fav in r.json()]
			# loop through each fav id and remove from twitter
			for fav in fav_ids :
				data = {'id' : fav}	
				response = requests.post(url="https://api.twitter.com/1.1/favorites/destroy.json",auth=oauth,data=data)
			print i	



Leave a comment