Skip to content

Instantly share code, notes, and snippets.

@garcia
Created July 12, 2013 05:55
Show Gist options
  • Save garcia/5982195 to your computer and use it in GitHub Desktop.
Save garcia/5982195 to your computer and use it in GitHub Desktop.
Source for imgurwords.tumblr.com. Written in 30 minutes. Reuses some components of autotumble.py.
#!/usr/bin/env python
import json
import pickle
import pprint
import sys
import time
import traceback
import oauth2
import requests
# User-defined constants
IMGUR_CLIENT_ID = '***************'
IMGUR_CLIENT_SECRET = '****************************************'
TUMBLR_CONSUMER_KEY = '**************************************************'
TUMBLR_SECRET_KEY = '**************************************************'
TUMBLR_OAUTH_TOKEN = '**************************************************'
TUMBLR_OAUTH_SECRET = '**************************************************'
TUMBLR_BLOG_NAME = '**********'
# Constants
IMGUR_IMAGE_ENDPOINT = 'https://api.imgur.com/3/image/{id}'
TUMBLR_OAUTH_BASE_URL = 'http://www.tumblr.com/oauth/'
TUMBLR_REQUEST_TOKEN_URL = TUMBLR_OAUTH_BASE_URL + 'request_token'
TUMBLR_AUTHORIZATION_URL = TUMBLR_OAUTH_BASE_URL + 'authorize'
TUMBLR_ACCESS_TOKEN_URL = TUMBLR_OAUTH_BASE_URL + 'access_token'
TUMBLR_POST_URL = 'http://api.tumblr.com/v2/blog/{user}.tumblr.com/post'
TUMBLR_POST_URL = TUMBLR_POST_URL.format(user=TUMBLR_BLOG_NAME)
TUMBLR_PHOTO_DATA = 'type=photo&state=queue&format=markdown&caption={link}&source={link}'
def tumblr_req(*args):
"""Send an OAuth request through the client."""
resp, content = client.request(*args)
j = json.loads(content)
if not str(j['meta']['status']).startswith('2'):
raise ValueError(j['meta']['status'])
return j
if __name__ == '__main__':
# Authenticate with Tumblr
client = oauth2.Client(
oauth2.Consumer(TUMBLR_CONSUMER_KEY, TUMBLR_SECRET_KEY),
oauth2.Token(TUMBLR_OAUTH_TOKEN, TUMBLR_OAUTH_SECRET)
)
# This was necessary at some point but I don't remember when or why
client.disable_ssl_certificate_validation = True
# Get wordbank
wordbank = set()
with open('wordbank.txt', 'r') as wordbank_file:
for word in wordbank_file:
for method in str.lower, str.upper, str.title:
wordbank.add(method(word.strip()))
# Load already_seen wordbank
try:
with open('already_seen.txt', 'rb') as infile:
already_seen = pickle.load(infile)
except IOError:
already_seen = set()
# Look for valid imgur IDs
first_run = True
for word in wordbank:
try:
if word in already_seen:
continue
already_seen.add(word)
if not first_run:
time.sleep(15)
else:
first_run = False
try:
req = requests.get(
IMGUR_IMAGE_ENDPOINT.format(id=word),
headers={'Authorization': 'Client-ID ' + IMGUR_CLIENT_ID},
)
if req.status_code != 200:
print 'No image at %s' % word
continue
print 'Imgur ID %s exists' % word
image = json.loads(req.text)
tumblr_response = tumblr_req(TUMBLR_POST_URL, 'POST',
TUMBLR_PHOTO_DATA.format(**image['data']))
if tumblr_response['meta']['status'] == 201:
print 'Uploaded successfully'
else:
pprint.pprint(tumblr_response)
except Exception:
traceback.print_exc()
except KeyboardInterrupt:
with open('already_seen.txt', 'wb') as outfile:
pickle.dump(already_seen, outfile)
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment