Skip to content

Instantly share code, notes, and snippets.

@samplereality
Created December 11, 2015 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samplereality/3fb1dcef6aadd9f655c0 to your computer and use it in GitHub Desktop.
Save samplereality/3fb1dcef6aadd9f655c0 to your computer and use it in GitHub Desktop.
DPLAbot Code (minus API credentials)
import re, random, tweepy
from wordnik import *
import inflect
from PIL import Image
from dpla.api import DPLA
import urllib
p = inflect.engine()
views = []
def smart_truncate(content, length=80, suffix=u'\u2026'.encode('utf-8')):
if len(content) <= length:
return content
else:
return content[:length].rsplit(' ', 1)[0]+suffix
apiUrl = 'http://api.wordnik.com/v4'
apiKey = 'wordnikAPIKey'
client = swagger.ApiClient(apiKey, apiUrl)
wordApi = WordsApi.WordsApi(client)
dpla = DPLA('dplaAPIKey')
auth = tweepy.OAuthHandler("TwitterConsumerKey", "TwitterConsumerSecretKey")
auth.set_access_token('TwitterAccessToken', 'TwitterAccessTokenSecret')
api = tweepy.API(auth)
#Find a random keyword to search DPLA for
example = wordApi.getRandomWords(includePartOfSpeech='noun',limit=10,minCorpusCount=10000,hasDictionaryDef='true',minDictionaryCount=30)
keyword = example[random.randint(0,10)].word
#Get a bunch of results from the DPLA
result = dpla.search(keyword,page_size=100,fields=["hasView","sourceResource.title","isShownAt","object","sourceResource.type","sourceResource.date.displayDate"])
for i in range(len(result.items)):
if 'image' in str(result.items[i]):
views.append(result.items[i])
print str(len(views)) + " items"
# Some funny business to sort through DPLA results and attempt to make sure there's an image available
view = random.choice(views)
print view
if (view.has_key('sourceResource.date.displayDate') == True):
date = view['sourceResource.date.displayDate'].encode('utf-8')
else:
date = 'Date Unknown'
title = view['sourceResource.title']
location = view['isShownAt']
imageurl = str(view['object'])
# Get the image from the DPLA, save it as JPG and covert to GIF (for some reason Twitter didn't like DPLA's jpegs)
print imageurl
urllib.urlretrieve(imageurl, "dpla_image.jpg")
im = Image.open('dpla_image.jpg')
#im.thumbnail((440,880), Image.ANTIALIAS)
im.save('dpla_image.gif','GIF')
status = title + " (" + date + ") " + location
if (len(status) > 120):
status = smart_truncate(title) + " (" + str(date) + ") " + location
print status
#Upload the image to Twitter along with the metadata
api.update_with_media('dpla_image.gif',status=status)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment