/
microblogging.py
executable file
·203 lines (156 loc) · 5.54 KB
/
microblogging.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python
###############################################################################
##
## digger - Digging into some data mines
## Copyright (C) 2010 core, Thammi
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have received a copy of the GNU Affero General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
###############################################################################
import sys
import json
import re
import urllib
from warnings import warn
from json_batch import save_batch
class UnknownServiceException(Exception):
def __init__(self, service):
self.service = service
def __str__(self):
return self.service
class ServiceFailedException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ProtectedUserException(Exception):
pass
class PromptlessOpener(urllib.FancyURLopener):
def prompt_user_passwd(self, host, realm):
# this is kind of hacky ..
raise ProtectedUserException()
myopener = PromptlessOpener()
urls = {
'identica': {
'api': "http://identi.ca/api/",
'search': "http://identi.ca/api/search.json",
},
'twitter': {
'api': "http://api.twitter.com/1/",
'search':"http://search.twitter.com/search.json",
},
'telecomix': {
'api': "http://status.telecomix.org/api/",
'search': "http://status.telecomix.org/api/search.json",
},
}
def available_services():
return urls.keys()
def api_call(service, method, options, tries=3):
if service not in urls:
raise UnknownServiceException(service)
url_parts = {
'query': urllib.urlencode(options),
'base_url': urls[service]['api'],
'method': method,
}
res = myopener.open("{base_url}{method}.json?{query}".format(**url_parts))
# watch rate limit (twitter only)
ratelimit = re.search("X-RateLimit-Remaining: ([0-9]+)", str(res.info()))
if ratelimit != None:
print "remaining API-calls: %s" % ratelimit.group(1)
if res.getcode() < 300:
return json.load(res)
else:
if tries > 1 and res.getcode() >= 500:
print "ERROR while fetching, retrying"
return api_call(service, method, options, tries-1)
else:
msg = "Unable to fetch: %i" % res.getcode()
raise ServiceFailedException(msg)
def search(service, query, page=1):
if service not in urls:
raise UnknownServiceException(service)
options = {
'q': query,
'rpp': 100,
'page': page,
}
url_parts = {
'query': urllib.urlencode(options),
'url': urls[service]['search'],
}
res = myopener.open("{url}?{query}".format(**url_parts))
if res.getcode() < 300:
raw = json.load(res)
updates = raw['results']
if raw['results_per_page'] == len(updates):
updates.extend(search(service, query, page + 1))
return updates
else:
msg = "Unable to fetch: %i" % res.getcode()
raise ServiceFailedException(msg)
def get_page(service, user, count, page):
options = {
'page': page,
'count': count,
'id': user,
'include_rts': 'true', #get all 200 tweets from twitter
}
return api_call(service, 'statuses/user_timeline', options)
def find_updates(service, query):
api_call(service, 'search', {})
def get_statuses(service, user, limit=None):
step = 200
page = 1
statuses = []
# how many dents are there?
try:
count = api_call(service, 'users/show', {'id': user})['statuses_count']
if limit:
count = min(count, limit)
while count > 0:
print "Fetching page %i, %i updates remaining" % (page, count)
# how many statuses to fetch?
fetch_count = min(step, count)
# fetch them
new_statuses = get_page(service, user, fetch_count, page)
# update the count
count -= len(new_statuses)
# save the statuses
statuses.extend(new_statuses)
# next page
page += 1
return statuses
except ProtectedUserException:
print "Unable to fetch this user, protected account!"
return []
def save_users(service, users):
for user in users:
print "===> Fetching %s on %s" % (user, service)
updates = get_statuses(service, user)
if not updates:
print "ERROR: No results!"
else:
save_batch(user, updates, "raw_updates_%s.json" % service)
print "Amount of updates: %i" % len(updates)
print
if __name__ == '__main__':
if len(sys.argv) < 3:
print "Please specify at least the service (identica or twitter) and one user id"
sys.exit(1)
else:
service = sys.argv[1]
users = sys.argv[2:]
save_users(service, users)