Skip to content

Instantly share code, notes, and snippets.

@TheGU
Last active August 6, 2017 21:25
Show Gist options
  • Save TheGU/348b39607f190106fc95414fb3444253 to your computer and use it in GitHub Desktop.
Save TheGU/348b39607f190106fc95414fb3444253 to your computer and use it in GitHub Desktop.
Python 3 script to unfollow inactive tumblr blog. You can specific numbers of inactive days to unfollow. Set CONSUMBER KEY and CONSUMBER SECRET then run a script and follow the step.
#!/usr/bin/env python
# pip install oauth2
# oauth2==1.9.0.post1
import oauth2 as oauth
from urllib.parse import urlparse, parse_qsl, urlencode
import json
from datetime import datetime,timedelta
# Number of inactive days of blog to unfollow
delete_older_than_days = 90
# Create user hear to get API key : https://www.tumblr.com/oauth/register
# or get your exsiting app here : https://www.tumblr.com/oauth/apps
consumer_key = '<API CONSUMBER KEY>'
consumer_secret = '<API CONSUMBER SECRET>'
# Provide token from last step to skip authen process or leave blank to run gen token process
access_oauth_token = ''
access_oauth_token_secret = ''
# access_oauth_token = '<ACCESS TOKEN>'
# access_oauth_token_secret = '<ACCESS SECRET>'
request_token_url = 'http://www.tumblr.com/oauth/request_token'
access_token_url = 'http://www.tumblr.com/oauth/access_token'
authorize_url = 'http://www.tumblr.com/oauth/authorize'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
delete_datetime = datetime.now() - timedelta(days=delete_older_than_days)
if not (access_oauth_token and access_oauth_token_secret):
# Step 1: Get a request token. This is a temporary token that is used for
# having the user authorize an access token and to sign the request to obtain
# said access token.
resp, content = client.request(request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
# request_token = dict(parse_qsl(content))
request_token = {key.decode('utf-8'): value.decode('utf-8') for (key, value) in dict(parse_qsl(content)).items()}
print("Request Token:")
print(" - oauth_token = %s" % request_token['oauth_token'])
print(" - oauth_token_secret = %s" % request_token['oauth_token_secret'])
print()
# Step 2: Redirect to the provider. Since this is a CLI script we do not
# redirect. In a web application you would redirect the user to the URL
# below.
print("Go to the following link in your browser:")
print("%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']))
print()
# resp, content = client.request("%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']), "GET")
# print(resp)
# print(dict(parse_qsl(content)))
# After the user has granted access to you, the consumer, the provider will
# redirect you to whatever URL you have told them to redirect to. You can
# usually define this in the oauth_callback argument as well.
accepted = 'n'
while accepted.lower() == 'n':
accepted = input('Have you authorized me? (y/n) ')
oauth_verifier = input('What is the [oauth_verifier] value from URL? ')
# Step 3: Once the consumer has redirected the user back to the oauth_callback
# URL you can request the access token the user has approved. You use the
# request token to sign this request. After this is done you throw away the
# request token and use the access token returned. You should store this
# access token somewhere safe, like a database, for future use.
token = oauth.Token(request_token['oauth_token'],
request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "POST")
access_token = {key.decode('utf-8'): value.decode('utf-8') for (key, value) in dict(parse_qsl(content)).items()}
print("Access Token:")
print(" - access_oauth_token = %s" % access_token['oauth_token'])
print(" - access_oauth_token_secret = %s" % access_token['oauth_token_secret'])
print()
print("You may now access protected resources using the access tokens above." )
print()
access_oauth_token = access_token['oauth_token']
access_oauth_token_secret = access_token['oauth_token_secret']
token = oauth.Token(access_oauth_token,access_oauth_token_secret)
client = oauth.Client(consumer, token)
total_blogs = 0
offset = 0
step = 20
following_list = []
outdate_list = []
while total_blogs >= offset :
resp, content = client.request("http://api.tumblr.com/v2/user/following?offset={0}&limit={1}".format(offset,step), method="GET")
# following_list = {str(key): str(value) for (key, value) in dict(content).items()}
data = json.loads(str(content,'utf-8'))
if data['meta']['status'] != 200:
print(data['meta'])
break
for blog in data['response']['blogs']:
last_update = datetime.fromtimestamp(blog['updated'])
diff_date = datetime.now() - last_update
blog_url = blog['url']
following_list.append({
'blog_url': blog_url,
'updated': last_update
})
if last_update < delete_datetime:
outdate_list.append({
'blog_url': blog_url,
'updated': last_update
})
print(("unfollow:",blog_url," LastUpdate:",'{} days ago'.format(diff_date.days),last_update.isoformat()))
client.request(
"http://api.tumblr.com/v2/user/unfollow",
method="POST",
body=urlencode({"url" : blog_url})
)
if total_blogs == 0:
total_blogs = data['response']['total_blogs']
print("loading: {0}/{1}".format(offset,total_blogs))
offset += step
print(("Total Blogs : ",len(following_list)))
print(("Unfollow : ",len(outdate_list)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment