-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_dpla.py
68 lines (50 loc) · 1.96 KB
/
query_dpla.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# By Tim Walsh, for QueryDPLA
# Searches the Digital Public Library of America (DPLA) for a term tweeted
# at it and responds with the title and URL of a random item from the
# query's results.
from dpla.api import DPLA
import random
import tweepy
consumer_key = 'xxxxx'
consumer_secret = 'xxxxx'
access_key = 'xxxxx'
access_secret = 'xxxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
# get data from tweet
querier = status.author.screen_name
twt = status.text
twt_term = twt.replace("@QueryDPLA ", "")
# search DPLA
dpla = DPLA('xxxxx') # your DPLA API key
result = dpla.search(q="%s" % twt_term, fields=["sourceResource.title", "id"],
page_size=50)
# pick random result
total = result.count
if total > 49:
json_data = result.items[random.randint(0, 49)]
elif total in range (1, 50):
json_data = result.items[random.randint(0, (total - 1))]
else:
pass
# tweet DPLA metadata at querier
if total >= 1:
title = json_data['sourceResource.title']
json_id = json_data['id']
item_url = 'http://dp.la/item/%s' % json_id
api.update_status(".@%s %s %s" % (querier, title[:80], item_url),
in_reply_to_status_id = status.id)
else:
api.update_status(".@%s No items found. Try another term!" % querier,
in_reply_to_status_id = status.id)
def on_error(self, status_code):
return True
def on_timeout(self):
return True
sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=['@QueryDPLA'])