forked from Coppersmith/trawler
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtwitter_crawler.py
1196 lines (1009 loc) · 52 KB
/
twitter_crawler.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Shared classes and functions for crawling Twitter
"""
# Standard Library modules
import codecs
import datetime
import itertools
import logging
import time
import gzip
try:
import ujson as json #much quicker
except:
import json
# Third party modules
from twython import Twython, TwythonError
### Functions ###
def get_console_info_logger():
"""
Return a logger that logs INFO and above to stderr
"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logger.addHandler(console_handler)
return logger
def get_screen_names_from_file(filename):
"""
Opens a text file containing one Twitter screen name per line,
returns a list of the screen names.
"""
screen_name_file = codecs.open(filename, "r", "utf-8")
screen_names = []
for line in screen_name_file.readlines():
if line.strip():
screen_names.append(line.strip().replace('@',''))
screen_name_file.close()
return screen_names
def get_ids_from_file(filename):
"""
Opens a text file containing one Twitter `user_id` per line,
returns a list of the properly casted `user_id`s.
"""
id_file = codecs.open(filename, "r", "utf-8")
ids = []
for line in id_file.readlines():
stripped = line.strip()
if stripped:
ids.append(int(stripped))
id_file.close()
return ids
def grouper(iterable, n, fillvalue=None):
"""Collect data into fixed-length chunks or blocks"""
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
# Taken from: http://docs.python.org/2/library/itertools.html
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
def save_screen_names_to_file(screen_names, filename, logger=None):
"""
Saves a list of Twitter screen names to a text file with one
screen name per line.
"""
if logger:
logger.info("Saving %d screen names to file '%s'" % (len(screen_names), filename))
f = codecs.open(filename, 'w', 'utf-8')
for screen_name in screen_names:
f.write("%s\n" % screen_name)
f.close()
def save_tweets_to_json_file(tweets, json_filename, gzip_out=True):
"""
Takes a Python dictionary of Tweets from the Twython API, and
saves the Tweets to a JSON file, storing one JSON object per
line.
`gzip_out=True` will write it to a gzip file, rather than a flat file
"""
if gzip_out:
OUT = gzip.open(json_filename, 'wb')
for tweet in tweets:
OUT.write(unicode("%s\n" % json.dumps(tweet)).encode('utf-8'))
else:
json_file = codecs.open(json_filename, "w", "utf-8")
for tweet in tweets:
json_file.write("%s\n" % json.dumps(tweet))
json_file.close()
def tweets_to_kafka_stream(tweets, channel='trawler', kafka_producer=None,
host=None, port=None):
"""
Sends each tweet in `tweets` as a message on the Kafka channel `channel`.
Requires either a `kafka_producer`, an instance of `kafka.SimpleProducer` or
the `host` and `port` upon which to connect.
#TODO should probably be removed, to keep this purely about REST API
"""
if not kafka_producer:
from kafka import KafkaClient, SimpleProducer
kafka_client = KafkaClient('%s:%s' % (host,port) )
kafka_producer = SimpleProducer(kafka_client)
for tweet in tweets:
producer.send_messages(channel, json.dums(tweet))
### Classes ###
class CrawlTwitterTimelines:
def __init__(self, twython, logger=None):
if logger is None:
self._logger = get_console_info_logger()
else:
self._logger = logger
self._twitter_endpoint = RateLimitedTwitterEndpoint(twython, "statuses/user_timeline", logger=self._logger)
###
### Accessing the users by `screen_name`
###
def get_all_timeline_tweets_for_screen_name(self, screen_name):
"""
Retrieves all Tweets from a user's timeline based on this procedure:
https://dev.twitter.com/docs/working-with-timelines
"""
# This function stops requesting additional Tweets from the timeline only
# if the most recent number of Tweets retrieved is less than 100.
#
# This threshold may need to be adjusted.
#
# While we request 200 Tweets with each API, the number of Tweets we retrieve
# will often be less than 200 because, for example, "suspended or deleted
# content is removed after the count has been applied." See the API
# documentation for the 'count' parameter for more info:
# https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS = 100
self._logger.info("Retrieving Tweets for user '%s'" % screen_name)
# Retrieve first batch of Tweets
try:
tweets = self._twitter_endpoint.get_data(screen_name=screen_name, count=200)
self._logger.info(" Retrieved first %d Tweets for user '%s'" % (len(tweets), screen_name))
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % screen_name)
return []
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % screen_name)
return []
else:
# Unhandled exception
raise e
if len(tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
# Retrieve rest of Tweets
while 1:
max_id = int(tweets[-1]['id']) - 1
more_tweets = self._twitter_endpoint.get_data(screen_name=screen_name, count=200, max_id=max_id)
tweets += more_tweets
self._logger.info(" Retrieved %d Tweets for user '%s' with max_id='%d'" % (len(more_tweets), screen_name, max_id))
if len(more_tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
def get_most_recent_tweets(self, screen_name):
"""
Makes a single call to the user's timeline to obtain the most recent
(up to 200) tweets. Great for getting a better snapshot of user behavior
than available from a single tweet.
"""
self._logger.info("Retrieving Tweets for user '%s'" % screen_name)
tweets = self._twitter_endpoint.get_data(screen_name=screen_name,count=200)
self._logger.info(" Retrieved first %d Tweets for user '%s'" % (len(tweets),screen_name))
return tweets
def get_all_timeline_tweets_for_screen_name_since(self, screen_name, since_id,max_id=None):
"""
Retrieves all Tweets from a user's timeline since the specified Tweet ID
based on this procedure:
https://dev.twitter.com/docs/working-with-timelines
"""
# This function stops requesting additional Tweets from the timeline only
# if the most recent number of Tweets retrieved is less than 100.
#
# This threshold may need to be adjusted.
#
# While we request 200 Tweets with each API, the number of Tweets we retrieve
# will often be less than 200 because, for example, "suspended or deleted
# content is removed after the count has been applied." See the API
# documentation for the 'count' parameter for more info:
# https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS = 100
self._logger.info("Retrieving Tweets for user '%s'" % screen_name)
# Retrieve first batch of Tweets
if not max_id:
tweets = self._twitter_endpoint.get_data(screen_name=screen_name, count=200, since_id=since_id)
self._logger.info(" Retrieved first %d Tweets for user '%s'" % (len(tweets), screen_name))
if len(tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
else:
tweets = []
# Retrieve rest of Tweets
while 1:
if tweets: #Will only trigger
max_id = int(tweets[-1]['id']) - 1
more_tweets = self._twitter_endpoint.get_data(screen_name=screen_name, count=200, max_id=max_id, since_id=since_id)
tweets += more_tweets
self._logger.info(" Retrieved %d Tweets for user '%s' with max_id='%d'" % (len(more_tweets), screen_name, since_id))
if len(more_tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
###
### Accessing the users by `user_id`
###
def get_all_timeline_tweets_for_id(self, user_id):
"""
Retrieves all Tweets from a user's timeline based on this procedure:
https://dev.twitter.com/docs/working-with-timelines
"""
# This function stops requesting additional Tweets from the timeline only
# if the most recent number of Tweets retrieved is less than 100.
#
# While we request 200 Tweets with each API, the number of Tweets we retrieve
# will often be less than 200 because, for example, "suspended or deleted
# content is removed after the count has been applied." See the API
# documentation for the 'count' parameter for more info:
# https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS = 100
self._logger.info("Retrieving Tweets for user_id '%s'" % user_id)
try:
# Retrieve first batch of Tweets
tweets = self._twitter_endpoint.get_data(user_id=user_id, count=200)
self._logger.info(" Retrieved first %d Tweets for user_id '%s'" % (len(tweets), user_id))
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % user_id)
return []
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % user_id)
return []
else:
# Unhandled exception
raise e
if len(tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
# Retrieve rest of Tweets
while 1:
max_id = int(tweets[-1]['id']) - 1
more_tweets = self._twitter_endpoint.get_data(user_id=user_id, count=200, max_id=max_id)
tweets += more_tweets
self._logger.info(" Retrieved %d Tweets for user '%s' with max_id='%d'" % (len(more_tweets), user_id, max_id))
if len(more_tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
def get_most_recent_tweets_by_id(self, user_id):
"""
Makes a single call to the user's timeline to obtain the most recent
(up to 200) tweets. Great for getting a better snapshot of user behavior
than available from a single tweet.
"""
self._logger.info("Retrieving Tweets for user_id '%s'" % user_id)
tweets = self._twitter_endpoint.get_data(user_id=user_id,count=200)
self._logger.info(" Retrieved first %d Tweets for user '%s'" % (len(tweets),user_id))
return tweets
def get_all_timeline_tweets_for_id_since(self, user_id, since_id,max_id=None):
"""
Retrieves all Tweets from a user's timeline since the specified Tweet ID
based on this procedure:
https://dev.twitter.com/docs/working-with-timelines
"""
# This function stops requesting additional Tweets from the timeline only
# if the most recent number of Tweets retrieved is less than 100.
#
# While we request 200 Tweets with each API, the number of Tweets we retrieve
# will often be less than 200 because, for example, "suspended or deleted
# content is removed after the count has been applied." See the API
# documentation for the 'count' parameter for more info:
# https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS = 100
self._logger.info("Retrieving Tweets for user_id '%s'" % user_id)
# Retrieve first batch of Tweets
if not max_id:
tweets = self._twitter_endpoint.get_data(user_id=user_id, count=200, since_id=since_id)
self._logger.info(" Retrieved first %d Tweets for user '%s'" % (len(tweets), user_id))
if len(tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
else:
tweets = []
# Retrieve rest of Tweets
while 1:
if tweets: #Will only trigger
max_id = int(tweets[-1]['id']) - 1
more_tweets = self._twitter_endpoint.get_data(user_id=user_id, count=200, max_id=max_id, since_id=since_id)
tweets += more_tweets
self._logger.info(" Retrieved %d Tweets for user_id '%s' with max_id='%d'" % (len(more_tweets), user_id, since_id))
if len(more_tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
def get_all_timeline_tweets_for_id_between_ids(self, user_id, since_id, max_id):
"""
Retrieves all Tweets from a user's timeline since the specified Tweet ID
based on this procedure:
https://dev.twitter.com/docs/working-with-timelines
"""
# This function stops requesting additional Tweets from the timeline only
# if the most recent number of Tweets retrieved is less than 100.
#
# This threshold may need to be adjusted.
#
# While we request 200 Tweets with each API, the number of Tweets we retrieve
# will often be less than 200 because, for example, "suspended or deleted
# content is removed after the count has been applied." See the API
# documentation for the 'count' parameter for more info:
# https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS = 100
self._logger.info("Retrieving Tweets for user '%s'" % user_id)
# Retrieve first batch of Tweets
tweets = self._twitter_endpoint.get_data(user_id=user_id, count=200, since_id=since_id, max_id=max_id)
self._logger.info(" Retrieved first %d Tweets for user '%s'" % (len(tweets), user_id))
if len(tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
# Retrieve rest of Tweets
while 1:
max_id = int(tweets[-1]['id']) - 1 #It's okay that this adjusts the max_id, since we are going backwards in time
more_tweets = self._twitter_endpoint.get_data(user_id=user_id, count=200, max_id=max_id, since_id=since_id)
tweets += more_tweets
self._logger.info(" Retrieved %d Tweets for user '%s' with max_id='%d'" % (len(more_tweets), user_id, since_id))
if len(more_tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
import datetime as dt
class FindFriendFollowers:
def __init__(self, twython, logger=None):
if logger is None:
self._logger = get_console_info_logger()
else:
self._logger = logger
self._friend_endpoint = RateLimitedTwitterEndpoint(twython, "friends/ids", logger=self._logger)
self._follower_endpoint = RateLimitedTwitterEndpoint(twython, "followers/ids", logger=self._logger)
self._user_lookup_endpoint = RateLimitedTwitterEndpoint(twython, "users/lookup", logger=self._logger)
self.calls_remaining = 1
self.last_checked_status = dt.datetime.now()
def api_calls_remaining(self):
now = dt.datetime.now()
#If it's been more than 7 minutes, go check the status before blindly returning
if (now - self.last_checked_status) > dt.timedelta(minutes=7):
self.last_checked_status = dt.datetime.now()
self._friend_endpoint.update_rate_limit_status()
self._follower_endpoint.update_rate_limit_status()
self._user_lookup_endpoint.update_rate_limit_status()
return min(self._friend_endpoint.api_calls_remaining_for_current_window,
self._follower_endpoint.api_calls_remaining_for_current_window,
self._user_lookup_endpoint.api_calls_remaining_for_current_window)
###
### Accessing data by screen_name
###
def get_ff_ids_for_screen_name(self, screen_name, all=False):
"""
Returns Twitter user IDs for users who are both Friends and Followers
for the specified screen_name.
The 'friends/ids' and 'followers/ids' endpoints return at most 5000 IDs,
so IF a user has more than 5000 followers, this function
will return the first 'page' from each.
This tends to be enough for all users except celebrities.
For these cases, specify `all=True`. This call will likely get
very costly in terms of time, so use sparingly.
"""
try:
response = self._friend_endpoint.get_data(screen_name=screen_name)
friend_ids = response['ids']
next_cursor = response['next_cursor_str']
while all and next_cursor:
response = self._friend_endpoint.get_data(screen_name=screen_name,
cursor=next_cursor)
friend_ids += response['ids']
next_cursor = response['next_cursor_str']
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % screen_name)
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % screen_name)
else:
# Unhandled exception
raise e
return [] #No data will be found
# We shouldn't get 404s and 401s on this call, so need for the try/except
response = self._follower_endpoint.get_data(screen_name=screen_name)
follower_ids = response['ids']
next_cursor = response['next_cursor_str']
while len(follower_ids) < count and next_cursor:
response = self._follower_endpoint.get_data(screen_name=screen_name,
cursor=next_cursor)
follower_ids += response['ids']
next_cursor = response['next_cursor_str']
# Return those in common
return list(set(friend_ids).intersection(set(follower_ids)))
def get_ff_screen_names_for_screen_name(self, screen_name):
"""
Returns Twitter screen names for users who are both Friends and Followers
for the specified screen_name.
"""
ff_ids = self.get_ff_ids_for_screen_name(screen_name)
ff_screen_names = []
# The Twitter API allows us to look up info for 100 users at a time
for ff_id_subset in grouper(ff_ids, 100):
user_ids = ','.join([str(id) for id in ff_id_subset if id is not None])
users = self._user_lookup_endpoint.get_data(user_id=user_ids, entities=False)
for user in users:
ff_screen_names.append(user[u'screen_name'])
return ff_screen_names
###
### Accessing data by user_id
###
def get_ff_ids_for_id(self, user_id, all=False):
"""
Returns Twitter user IDs for users who are both Friends and Followers
for the specified `user_id`.
The 'friends/ids' and 'followers/ids' endpoints return at most 5000 IDs,
so IF a user has more than 5000 followers, this function
will return the first 'page' from each.
This tends to be enough for all users except celebrities.
For these cases, specify `all=True`. This call will likely get
very costly in terms of time, so use sparingly.
"""
try:
response = self._friend_endpoint.get_data(user_id=user_id)
friend_ids = response['ids']
next_cursor = response['next_cursor_str']
while all and next_cursor:
response = self._friend_endpoint.get_data(user_id=user_id,
cursor=next_cursor)
friend_ids += response['ids']
next_cursor = response['next_cursor_str']
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % user_id)
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % user_id)
else:
# Unhandled exception
raise e
return [] #No data will be found
# We shouldn't get 404s and 401s on this call, so need for the try/except
response = self._follower_endpoint.get_data(user_id=user_id)
follower_ids = response['ids']
next_cursor = response['next_cursor_str']
while len(follower_ids) < count and next_cursor:
response = self._follower_endpoint.get_data(user_id=user_id,
cursor=next_cursor)
follower_ids += response['ids']
next_cursor = response['next_cursor_str']
# Return those in common
return list(set(friend_ids).intersection(set(follower_ids)))
def get_ff_screen_names_for_id(self, user_id):
"""
Returns Twitter screen names for users who are both Friends and Followers
for the specified `user_id`.
"""
ff_ids = self.get_ff_ids_for_screen_name(screen_name)
ff_screen_names = []
# The Twitter API allows us to look up info for 100 users at a time
for ff_id_subset in grouper(ff_ids, 100):
user_ids = ','.join([str(id) for id in ff_id_subset if id is not None])
users = self._user_lookup_endpoint.get_data(user_id=user_ids, entities=False)
for user in users:
ff_screen_names.append(user[u'screen_name'])
return ff_screen_names
class FindFollowers:
def __init__(self, twython, logger=None):
if logger is None:
self._logger = get_console_info_logger()
else:
self._logger = logger
self._follower_endpoint = RateLimitedTwitterEndpoint(twython, "followers/ids", logger=self._logger)
self._user_lookup_endpoint = RateLimitedTwitterEndpoint(twython, "users/lookup", logger=self._logger)
self.calls_remaining = 1
self.last_checked_status = dt.datetime.now()
def api_calls_remaining(self):
now = dt.datetime.now()
#If it's been more than 7 minutes, go check the status before blindly returning
if (now - self.last_checked_status) > dt.timedelta(minutes=7):
self.last_checked_status = dt.datetime.now()
self._follower_endpoint.update_rate_limit_status()
self._user_lookup_endpoint.update_rate_limit_status()
return min(self._follower_endpoint.api_calls_remaining_for_current_window,
self._user_lookup_endpoint.api_calls_remaining_for_current_window)
###
### Access Users by `screen_name`
###
def get_follower_ids_for_screen_name(self, screen_name, count=-1, incremental_output=None):
"""
Returns Twitter user IDs for users who are Followers of
the specified screen_name.
The 'followers/ids' endpoint return at most 5000 IDs,
so IF a user has more than 5000 followers, this function
will return the first 'page'.
To get it to return ALL the followers (or up to a specific number),
this call can get quite costly in terms of time -- specifying exactly
how many users to return can by done via `count`. If we run out of
available followers, we will return with less than `count` ids.
`incremental_output` is a function that stores data even if the
crawl isn't finished, this allow follow-on processes to proceed
during long calls. In the simplest case, this just writes to a file or
kafka queue.
"""
try:
response = self._follower_endpoint.get_data(screen_name=screen_name)
follower_ids = response['ids']
next_cursor = response['next_cursor_str']
print "*",next_cursor,"*"
keep_going = True
while len(follower_ids) < count and next_cursor and keep_going:
response = self._follower_endpoint.get_data(screen_name=screen_name,
cursor=next_cursor)
new_ids = response['ids']
follower_ids += new_ids
print new_ids
if len(new_ids)<1:
keep_going = False
if incremental_output:
incremental_output( new_ids)
next_cursor = response['next_cursor_str']
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % screen_name)
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % screen_name)
else:
# Unhandled exception
raise e
follower_ids = []
return follower_ids
def get_follower_screen_names_for_screen_name(self, screen_name, **kwargs):
"""
Returns Twitter screen names for users who are Followers
of the specified screen_name.
Any additional keyword arguments are passed on to
`get_follower_ids_for_screen_name`
"""
follower_ids = self.get_follower_ids_for_screen_name(screen_name, **kwargs)
follower_screen_names = []
# The Twitter API allows us to look up info for 100 users at a time
for follower_id_subset in grouper(follower_ids, 100):
user_ids = ','.join([str(id) for id in follower_id_subset if id is not None])
users = self._user_lookup_endpoint.get_data(user_id=user_ids, entities=False)
for user in users:
follower_screen_names.append(user[u'screen_name'])
return follower_screen_names
###
### Access Users by `user_id`
###
def get_follower_ids_for_id(self, user_id, count=-1):
"""
Returns Twitter user IDs for users who are Followers of
the specified `user_id`.
The 'followers/ids' endpoint return at most 5000 IDs,
so IF a user has more than 5000 followers, this function
will return the first 'page'.
To get it to return ALL the followers (or up to a specific number),
this call can get quite costly in terms of time -- specifying exactly
how many users to return can by done via `count`. If we run out of
available followers, we will return with less than `count` ids.
"""
try:
response = self._follower_endpoint.get_data(user_id=user_id)
follower_ids = response['ids']
next_cursor = response['next_cursor_str']
while len(follower_ids) < count and next_cursor:
response = self._follower_endpoint.get_data(user_id=user_id,
cursor=next_cursor)
follower_ids += response['ids']
next_cursor = response['next_cursor_str']
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % user_id)
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % user_id)
else:
# Unhandled exception
raise e
follower_ids = []
return follower_ids
def get_follower_screen_names_for_id(self, user_id):
"""
Returns Twitter screen names for users who are Followers
of the specified `user_id`.
"""
follower_ids = self.get_follower_ids_for_screen_name(user_id)
follower_screen_names = []
# The Twitter API allows us to look up info for 100 users at a time
for follower_id_subset in grouper(follower_ids, 100):
user_ids = ','.join([str(id) for id in follower_id_subset if id is not None])
users = self._user_lookup_endpoint.get_data(user_id=user_ids, entities=False)
for user in users:
follower_screen_names.append(user[u'screen_name'])
return follower_screen_names
class FindFollowees:
def __init__(self, twython, logger=None):
if logger is None:
self._logger = get_console_info_logger()
else:
self._logger = logger
self._followee_endpoint = RateLimitedTwitterEndpoint(twython, "followers/ids", logger=self._logger)
self._user_lookup_endpoint = RateLimitedTwitterEndpoint(twython, "users/lookup", logger=self._logger)
self.calls_remaining = 1
self.last_checked_status = dt.datetime.now()
def api_calls_remaining(self):
now = dt.datetime.now()
#If it's been more than 7 minutes, go check the status before blindly returning
if (now - self.last_checked_status) > dt.timedelta(minutes=7):
self.last_checked_status = dt.datetime.now()
self._followee_endpoint.update_rate_limit_status()
self._user_lookup_endpoint.update_rate_limit_status()
return min(self._followee_endpoint.api_calls_remaining_for_current_window,
self._user_lookup_endpoint.api_calls_remaining_for_current_window)
###
### Access Users by `screen_name`
###
def get_followee_ids_for_screen_name(self, screen_name, count=-1):
"""
Returns Twitter user IDs for users who `screen_name` follows.
The 'followers/ids' endpoint return at most 5000 IDs,
so IF a user follows more than 5000 users, this function
will return the first 'page'.
To get it to return ALL the followers (or up to a specific number),
this call can get quite costly in terms of time -- specifying exactly
how many users to return can by done via `count`. If we run out of
available followers, we will return with less than `count` ids.
"""
try:
response = self._followee_endpoint.get_data(screen_name=screen_name)
followee_ids = response['ids']
next_cursor = response['next_cursor_str']
while len(followee_ids) < count and next_cursor:
response = self._followee_endpoint.get_data(screen_name=screen_name,
cursor=next_cursor)
followee_ids += response['ids']
next_cursor = response['next_cursor_str']
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % screen_name)
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % screen_name)
else:
# Unhandled exception
raise e
followee_ids = []
return followee_ids
def get_followee_screen_names_for_screen_name(self, screen_name):
"""
Returns Twitter screen_names for users who `screen_name` follows.
"""
followee_ids = self.get_followee_ids_for_screen_name(screen_name)
followee_screen_names = []
# The Twitter API allows us to look up info for 100 users at a time
for followee_id_subset in grouper(followee_ids, 100):
user_ids = ','.join([str(id) for id in followee_id_subset if id is not None])
users = self._user_lookup_endpoint.get_data(user_id=user_ids, entities=False)
for user in users:
followee_screen_names.append(user[u'screen_name'])
return followee_screen_names
###
### Access Users by `user_id`
###
def get_followee_ids_for_id(self, user_id, count=-1):
"""
Returns Twitter user IDs for users who `screen_name` follows.
The 'followees/ids' endpoint return at most 5000 IDs,
so IF a follows more than 5000 users, this function
will return the first 'page'.
To get it to return ALL the followees (or up to a specific number),
this call can get quite costly in terms of time -- specifying exactly
how many users to return can by done via `count`. If we run out of
available followees, we will return with less than `count` ids.
"""
try:
response = self._followee_endpoint.get_data(user_id=user_id)
followee_ids = response['ids']
next_cursor = response['next_cursor_str']
while len(follower_ids) < count and next_cursor:
response = self._followee_endpoint.get_data(user_id=user_id,
cursor=next_cursor)
followee_ids += response['ids']
next_cursor = response['next_cursor_str']
except TwythonError as e:
if e.error_code == 404:
self._logger.warn("HTTP 404 error - Most likely, Twitter user '%s' no longer exists" % user_id)
elif e.error_code == 401:
self._logger.warn("HTTP 401 error - Most likely, Twitter user '%s' no longer publicly accessible" % user_id)
else:
# Unhandled exception
raise e
followee_ids = []
return followee_ids
def get_followee_screen_names_for_id(self, user_id):
"""
Returns Twitter screen names for users who `user_id` follows.
"""
followee_ids = self.get_followee_ids_for_screen_name(user_id)
followee_screen_names = []
# The Twitter API allows us to look up info for 100 users at a time
for followee_id_subset in grouper(followee_ids, 100):
user_ids = ','.join([str(id) for id in followee_id_subset if id is not None])
users = self._user_lookup_endpoint.get_data(user_id=user_ids, entities=False)
for user in users:
followee_screen_names.append(user[u'screen_name'])
return followee_screen_names
class UserLookup:
def __init__(self, twython, logger=None):
if logger is None:
self._logger = get_console_info_logger()
else:
self._logger = logger
self._user_lookup_endpoint = RateLimitedTwitterEndpoint(twython, "users/lookup", logger=self._logger)
self.calls_remaining = 1
self.last_checked_status = dt.datetime.now()
def api_calls_remaining(self):
now = dt.datetime.now()
#If it's been more than 7 minutes, go check the status before blindly returning
if (now - self.last_checked_status) > dt.timedelta(minutes=7):
self.last_checked_status = dt.datetime.now()
self._user_lookup_endpoint.update_rate_limit_status()
return min(self._user_lookup_endpoint.api_calls_remaining_for_current_window)
def lookup_users(self, twitter_ids):
"""
Returns the user lookup for the users specified by `twitter_id`
To maximize throughput of Twitter API, this looks up 100 users with a
single call.
"""
# The Twitter API allows us to look up info for 100 users at a time
amassed_users = []
for id_subset in grouper(twitter_ids, 100):
user_ids = ','.join([str(id) for id in id_subset if id is not None])
users = self._user_lookup_endpoint.get_data(user_id=user_ids, entities=False)
amassed_users += users
return amassed_users
class ListMembership:
def __init__(self, twython, logger=None):
if logger is None:
self._logger = get_console_info_logger()
else:
self._logger = logger
self._lists_memberships_endpoint = RateLimitedTwitterEndpoint(twython, "lists/memberships", logger=self._logger)
self._lists_members_endpoint = RateLimitedTwitterEndpoint(twython, "lists/members", logger=self._logger)
self._user_lookup_endpoint = RateLimitedTwitterEndpoint(twython, "users/lookup", logger=self._logger)
self.calls_remaining = 1
self.last_checked_status = dt.datetime.now()
def api_calls_remaining(self):
now = dt.datetime.now()
#If it's been more than 7 minutes, go check the status before blindly returning
if (now - self.last_checked_status) > dt.timedelta(minutes=7):
self.last_checked_status = dt.datetime.now()
self._lists_memberships_endpoint.update_rate_limit_status()
self._lists_members_endpoint.update_rate_limit_status()
self._user_lookup_endpoint.update_rate_limit_status()
return min(self._lists_memberships_endpoint.api_calls_remaining_for_current_window,
self._lists_members_endpoint.api_calls_remaining_for_current_window,
self._user_lookup_endpoint.api_calls_remaining_for_current_window)
###
### Accessing data by screen_name
###
def get_list_memberships_for_screen_name(self, screen_name, count=1000):
"""
Returns full listings for any lists this `screen_name` was added to.
Paging will be applied if user is a member of more than 1000 lists,
until we reach `count` lists or we run out of cursors.
"""
try:
response = self._lists_memberships_endpoint.get_data(screen_name=screen_name)
list_memberships = response[u'lists']
next_cursor = response['next_cursor']
while next_cursor and len(list_memberships) < count:
response = self._lists_memberships_endpoint.get_data(screen_name=screen_name, cursor=next_cursor)
list_memberships += response['lists']
except TwythonError as e:
print "Error:", e.error_code
print e
raise e
list_memberships = []
return list_memberships
def get_list_membership_ids_for_screen_name( self, screen_name):
"""
Returns the list `id`s for each list that `screen_name` is a member of.
"""
return [x['id'] for x in self.get_list_memberships_for_screen_name(screen_name)]
def get_list_members_by_list_id( self, list_id):
"""
Returns the users who are members of list `list_id`.
This output is cursored, which is not currently implemented, so only the
first 5000 members of each list are returned.
"""
# Retrieve first batch of members
response = self._lists_members_endpoint.get_data(list_id=list_id, count=5000 )
members = response['users']
next_cursor = response['next_cursor']
while next_cursor:
response = self._lists_members_endpoint.get_data(list_id=list_id, count=5000,
cursor=next_cursor)
members += response['users']
next_cursor = response['next_cursor']
self._logger.info(" Retrieved first %d Members for List '%s'" % (len(members), list_id))
return members
class SearchTwitterTimelines:
def __init__(self, twython, logger=None):
if logger is None:
self._logger = get_console_info_logger()
else:
self._logger = logger
self._twitter_endpoint = RateLimitedTwitterEndpoint(twython, "search/tweets", logger=self._logger)
###
### Accessing the users by `screen_name`
###
def get_all_search_tweets_for_term(self, term, max_id=None, **kwargs):
"""
Retrieves all available Tweets from the search API for the given
search term.
`max_id` can specify a tweet to search prior to, and all
other arguments will be passed on to the search API
"""
# This function stops requesting additional Tweets from the timeline only
# if the most recent number of Tweets retrieved is less than 50.
#
# This threshold may need to be adjusted.
#
# While we request 100 Tweets with each API, the number of Tweets we retrieve
# will often be less than 100 because, for example, "suspended or deleted
# content is removed after the count has been applied." See the API
# documentation for the 'count' parameter for more info:
# https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS = 1
self._logger.info("Retrieving Tweets for '%s'" % term)
# Retrieve first batch of Tweets
if max_id:
tweets = self._twitter_endpoint.get_data(q=term, count=100,
max_id=max_id-1,
**kwargs)['statuses']
else:
tweets = self._twitter_endpoint.get_data(q=term, count=100,
**kwargs)['statuses']
self._logger.info(" Retrieved first %d Tweets for '%s'" % (len(tweets), term))
if len(tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
iterations = 0
# Retrieve rest of Tweets
while 1:
iterations += 1
max_id = int(tweets[-1]['id']) - 1
more_tweets = self._twitter_endpoint.get_data(q=term, count=100,
max_id=max_id,
**kwargs)['statuses']
tweets += more_tweets
self._logger.info(" Retrieved %d Tweets for '%s' with max_id='%d'"
% (len(more_tweets), term, max_id))
if len(more_tweets) < MINIMUM_TWEETS_REQUIRED_FOR_MORE_API_CALLS:
return tweets
#HARDCODE -- temporary
try:
if iterations % 100 == 0:
print "Hit a round number, dumping to file"
import ujson as json
import gzip
with gzip.open('%s.json.gz' % term,'w') as OUT:
for t in tweets:
OUT.write('%s\n' % json.dumps(t))
except:
print "Broke on HARDCODE temporary"