-
Notifications
You must be signed in to change notification settings - Fork 7
/
newt.py
1633 lines (1465 loc) · 49.6 KB
/
newt.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
import tweepy, simplejson, urllib, os,datetime,re
import md5, tempfile, time,random
import csv,yql
import itertools
#import klout
import xml.sax.saxutils as saxutils
from urlparse import urlparse
import networkx as nx
import privatebits
import unicodedata
import sqlite3
#----------------------------------------------------------------
#--- sqlite database handling
def getdb():
return sqlite3.connect('newt.db')
def getdbc():
db=getdb()
return db.cursor()
#tables: frfo,user,tweet
#dbc.execute('CREATE TABLE frfo (`from` int, `to` int, `type` text)')
#dbc.execute('CREATE TABLE user ( `id` int, `screen_name` text,`desc` text,`location` text)')
#dbc.execute('CREATE TABLE tweet ( `id` int, `from' int, `text` text,`date` date)')
#----------------------------------------------------------------
#import backtype
#def getBackTypeKey():
# key=privatebits.getBackTypeKey()
# return key
def getBitlyKey():
bu,bkey=privatebits.getBitlyKey()
return bu,bkey
def getTwapperkeeperKey():
key=privatebits.getTwapperkeeperKey()
return key
def getKloutKey():
kkey=privatebits.getKloutKey()
return kkey
def getPeerIndexKey():
pkey=privatebits.getPeerIndexKey()
return pkey
def getYahooOAuthKey():
key,shared_secret=privatebits.getYahooOAuthKey()
return key,shared_secret
def getYahooAppID():
appid=privatebits.getYahooAppID()
return appid
def getTwitterKeys():
consumer_key,consumer_secret,skey,ssecret=privatebits.getTwitterKeys()
return consumer_key,consumer_secret,skey,ssecret
def expandBitlyURL(burl):
bu,bkey=getBitlyKey()
url='http://api.bit.ly/v3/expand?shortUrl='+urllib.quote(burl)+'&login='+bu+'&apiKey='+bkey+'&format=json'
print 'url: '+url
r=simplejson.load(urllib.urlopen(url))
return r['data']['expand']
# for j in r['data']['expand']:
# print 'long '+j['long_url']
def getBackTypedPageData(burl,sources,page,data):
print 'Getting more backtype data... Page:',page
key=getBackTypeKey()
url='http://api.backtype.com/connect.json?page='+str(page)+'&url='+urllib.quote(burl)+'&sources='+sources+'&itemsperpage=1000+&key='+key
xdata=simplejson.load(urllib.urlopen(url))
for c in xdata['comments']:
data['comments'].append(c)
if 'next_page' in xdata:
data=getBackTypedPageData(burl,sources,xdata['next_page'],data)
return data
def clurn(burl):
burl=burl.split('?')[0]
return burl
def ascii(s):
if s!=None: return "".join(i for i in s if ord(i)<128)
else: return
def getBackTypedURLData(burl,sources='twitter'):
key=getBackTypeKey()
burl=clurn(burl)
url='http://api.backtype.com/connect.json?url='+urllib.quote(burl)+'&sources='+sources+'&itemsperpage=1000+&key='+key
data=simplejson.load(urllib.urlopen(url))
print 'Getting Backtype data for',url
if 'next_page' in data:
print 'Trying another page of Backtype data'
data=getBackTypedPageData(burl,sources,data['next_page'],data)
else:
print 'Only 1 page of Backtype data'
return data
def getTweetFromID(api, id):
try:
twt=api.get_status(id)
except:
twt=''
return twt
def getTweetsFromIDs(api, ids):
tweets=[]
for id in ids:
twt=getTweetFromID(api, id)
if twt!='':
tweets.append(twt)
return tweets
def getTweetsAboutURL(api,url):
data=getBackTypedURLData(url)
ids=[]
for id in data['comments']:
ids.append(id['tweet_id'])
return getTweetsFromIDs(api, ids)
def getTwUserNamesTweetingURL(api,url):
statuses=getTweetsAboutURL(api,url)
users=[]
for status in statuses:
user=status.author.screen_name
if user not in users:
users.append(user)
return users
def getTwUserDetailsTweetingURL(api,users,url):
statuses=getTweetsAboutURL(api,url)
for status in statuses:
user=status.author.screen_name
if user not in users:
print user
users[user]=status.author
return users
def generateGoogleCSEDefinitionFile(cse,tag, tw,typ='flat'):
report("Generating Google CSE definition file")
fname='listhomepages_'+typ+'.xml'
f=openTimestampedFile(tag,fname)
f.write("<GoogleCustomizations>\n\t<Annotations>\n")
for u in tw:
un=tw[u]
if type(un) is tweepy.models.User:
l=un.url
if l:
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', l)
for l in urls:
#l=l.split(' ')[0]
#if "http://bit.ly" in url:
# urls=expandBitlyURL(burl)
#l=urls[0]
#l=l.strip()
lo=l
l=l.replace("http://","")
if not l.endswith('/') and '?' not in l:
l=l+"/*"
else:
if l[-1]=="/":
l=l+"*"
report("- using "+lo+" as "+l)
weight=1.0
if typ is 'weighted':
if hasattr(un, 'status'):
weight=un.status
else:
weight=0
f.write("\t\t<Annotation about=\""+l+"\" score=\""+str(weight)+"\">\n")
f.write("\t\t\t<Label name=\""+cse+"\"/>\n")
f.write("\t\t</Annotation>\n")
f.write("\t</Annotations>\n</GoogleCustomizations>")
report("...Google CSE definition file DONE")
f.close()
def googleCSEDefinitionFileWeighted(cse,tag, tw):
generateGoogleCSEDefinitionFile(cse,tag, tw,'weighted')
def googleCSEDefinitionFile(cse,tag, tw):
generateGoogleCSEDefinitionFile(cse,tag, tw,'flat')
def getBitlyUserLinks(user):
links=[]
url='http://bit.ly/u/'+user+'.json'
data = simplejson.load(urllib.urlopen(url))
for i in data['data']:
links.append(i['url'])
return links
#----------------------------------------------------------------
def getTwapperkeeperURL(tag,type,start,end,page=1):
key=getTwapperkeeperKey()
url='http://api.twapperkeeper.com/2/notebook/tweets/?apikey='+key+'&name='+tag+'&type='+type+'&since='+start+'&until='+end+'&rpp=1000&page='+str(page)
return url
#----------------------------------------------------------------
#----------------------------------------------------------------
def getTwapperkeeperPage(tag,type,start,end,page=1):
report("Getting page "+str(page))
url= getTwapperkeeperURL(tag,type,start,end,page)
#fetcher = DiskCacheFetcher('cache')
#page=fetcher.fetch(url, 3600)
#r=simplejson.loads(page)
fetcher=DiskCacheFetcherfname('cache')
fn=fetcher.fetch(url, 3600)
f=open(fn)
data=f.read()
f.close()
r=simplejson.loads(data)
#r=simplejson.load(urllib.urlopen(url))
return r['response']
#----------------------------------------------------------------
#----------------------------------------------------------------
def parseTwapperkeeperResponse(tweeters,response,c):
report("..parsing page")
if 'tweets_returned' in response:
for i in response['tweets_returned']:
c+=1
u=i['from_user'].strip()
if u in tweeters:
tweeters[u]['count']+=1
else:
report("New user: "+u)
tweeters[u]={}
tweeters[u]['count']=1
return tweeters,c
#----------------------------------------------------------------
#----------------------------------------------------------------
def getTwapperkeeperArchiveTweeters(tweeters,tag,start,end,type='hashtag'):
report("Getting Twapperkeeper archive tweeters")
count=0
num=0
r=getTwapperkeeperPage(tag,type,start,end)
tweeters,count=parseTwapperkeeperResponse(tweeters,r,count)
#if there is only one page, does Twapperkeeper report the tweets_found_count?
if 'tweets_found_count' in r:
if r['tweets_found_count'] is not None:
num=int(r['tweets_found_count'])
page=2
while count<num:
r=getTwapperkeeperPage(tag,type,start,end,page)
tweeters,count=parseTwapperkeeperResponse(tweeters,r,count)
page+=1
return tweeters
#----------------------------------------------------------------
#----------------------------------------------------------------
def getTwitterAPI(cachetime=360000):
#----------------------------------------------------------------
#API settings for Twitter
consumer_key,consumer_secret,skey,ssecret=getTwitterKeys()
#----------------------------------------------------------------
#----------------------------------------------------------------
#API initialisation for Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(skey, ssecret)
#api = tweepy.API(auth)
api = tweepy.API(auth, cache=tweepy.FileCache('cache',cachetime), retry_errors=[500], retry_delay=5, retry_count=2)
#----------------------------------------------------------------
return api
#----------------------------------------------------------------
#----------------------------------------------------------------
def getTwitterAuth():
#----------------------------------------------------------------
#API settings for Twitter
consumer_key,consumer_secret,skey,ssecret=getTwitterKeys()
#----------------------------------------------------------------
#----------------------------------------------------------------
#API initialisation for Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(skey, ssecret)
return auth
#----------------------------------------------------------------
#----------------------------------------------------------------
def report(m, verbose=True):
if verbose is True:
print m
#----------------------------------------------------------------
#----------------------------------------------------------------
def getGenericCachedData(url, cachetime=360000):
fetcher=DiskCacheFetcherfname('cache')
fn=fetcher.fetch(url, cachetime)
f=open(fn)
data=f.read()
f.close()
#print 'data----',data
jdata=simplejson.loads(data)
return jdata
def getKloutDetails(twpl,kd={}):
kkey=getKloutKey()
#klout=new Klout()
print twpl
twl=chunks(twpl,5)
for f5 in twl:
u=','.join(f5)
url='http://api.klout.com/1/users/show.json?key='+kkey+'&users='+u
data=getGenericCachedData(url)
for d in data['users']:
print d
kd[d['twitter_screen_name']]=d
return kd
#----------------------------------------------------------------
def getPeerIndexDetails(twpl,cachetime=360000):
pkey=getPeerIndexKey()
for u in twpl:
url='http://api.peerindex.net/1/profile/show.json?id='+u+'&api_key='+pkey
data=getGenericCachedData(url,cachetime)
for d in data:
print data[d]
time.sleep(2)
#----------------------------------------------------------------
def createListIfRequired(api, tag):
lists=api.lists()
listexists= False
for l in lists:
for l2 in l:
if type(l2) is tweepy.models.List:
if l2.slug==tag:
listexists= True
report("List appears to exist")
if listexists is False:
report("List doesn't appear to exist... creating it now")
api.create_list(tag)
#----------------------------------------------------------------
def getLanyrdPeopleXingEvent(twpl,year, event,typ='attendees'):
#attendees or trackers
y = yql.Public()
query="select href from html where url='http://lanyrd.com/"+str(year)+"/"+event+"/' and xpath='//div[@class=\""+typ+"-placeholder placeholder\"]/ul[@class=\"user-list\"]/li/a'"
result = y.execute(query)
for row in result.rows:
lpersonpath=row.get('href')
twurl=getTwitterNameFromLanyrdPerson(lpersonpath)
ret=(twurl.replace('http://twitter.com/',''),typ)
twpl.append(ret)
return twpl
def getLanyrdPeopleFromEvent(year,event):
twpl=[]
print "Getting attendees of",event
twpl=getLanyrdPeopleXingEvent(twpl,year, event,typ='attendees')
print "Getting trackers of",event
twpl=getLanyrdPeopleXingEvent(twpl,year, event,typ='trackers')
return twpl
def getTwitterNameFromLanyrdPerson(lpersonpath):
y = yql.Public()
query = "select href from html where url='http://lanyrd.com"+lpersonpath+"' and xpath='//a[@class=\"icon twitter url nickname\"]'"
result = y.execute(query)
for row in result.rows:
return row.get('href')
return 'oops'
#----------------------------------------------------------------
def placemakerGeocodeLatLon(address):
encaddress=urllib.quote_plus(address)
appid=getYahooAppID()
url='http://where.yahooapis.com/geocode?location='+encaddress+'&flags=J&appid='+appid
data = simplejson.load(urllib.urlopen(url))
if data['ResultSet']['Found']>0:
for details in data['ResultSet']['Results']:
return details['latitude'],details['longitude']
else:
return False,False
def twSearchNear(tweeters,tags,num,place='mk7 6aa,uk',term='', dist=1,exclRT=False):
t=int(num/100)+1
if t>15:t=15
bigdata=[]
page=1
lat,lon=placemakerGeocodeLatLon(place)
while page<=t:
#url='http://search.twitter.com/search.json?rpp=100&page='+str(page)+'&q='+urllib.quote_plus(q)
url='http://search.twitter.com/search.json?geocode='+str(lat)+'%2C'+str(lon)+'%2C'+str(1.0*dist)+'km&rpp=100&page='+str(page)+'&q=''within%3A'+str(dist)+'km'
print url
if term!='':
url+='+'+urllib.quote_plus(term)
'''
if since!='':
url+='+since:'+since
'''
page+=1
data = simplejson.load(urllib.urlopen(url))
for i in data['results']:
if (exclRT==False) or (exclRT==True and not i['text'].startswith('RT @')):
u=i['from_user'].strip()
if u in tweeters:
tweeters[u]['count']+=1
else:
report("New user: "+u)
tweeters[u]={}
tweeters[u]['count']=1
ttags=re.findall("#([a-z0-9]+)", i['text'], re.I)
for tagx in ttags:
if tagx not in tags:
tags[tagx]=1
else:
tags[tagx]+=1
bigdata.extend(data['results'])
return tweeters,tags,bigdata
'''
t=int(num/100)+1
if t>15:t=15
page=1
lat,lon=placemakerGeocodeLatLon(place)
while page<=t:
url='http://search.twitter.com/search.json?geocode='+str(lat)+'%2C'+str(lon)+'%2C'+str(1.0*dist)+'km&rpp=100&page='+str(page)+'&q=+within%3A'+str(dist)+'km'
print url
if term!='':
url+='+'+urllib.quote_plus(term)
#if since!='':
# url+='+since:'+since
page+=1
data = simplejson.load(urllib.urlopen(url))
for i in data['results']:
if not i['text'].startswith('RT @'):
u=i['from_user'].strip()
if u in tweeters:
tweeters[u]['count']+=1
else:
report("New user: "+u)
tweeters[u]={}
tweeters[u]['count']=1
ttags=re.findall("#([a-z0-9]+)", i['text'], re.I)
for tag in ttags:
if tag not in tags:
tags[tag]=1
else:
tags[tag]+=1
return tweeters,tags
'''
def twSearchHashtag(tweeters,tags,num,tag='ukoer', since='',term='',exclRT=False):
t=int(num/100)+1
if t>15:t=15
page=1
bigdata=[]
while page<=t:
url='http://search.twitter.com/search.json?tag='+tag+'&rpp=100&page='+str(page)+'&result_type=recent&include_entities=false&q='
print url
if term!='':
url+='+'+urllib.quote_plus(term)
'''
if since!='':
url+='+since:'+since
'''
page+=1
data = simplejson.load(urllib.urlopen(url))
for i in data['results']:
if (exclRT==False) or (exclRT==True and not i['text'].startswith('RT @')):
u=i['from_user'].strip()
if u in tweeters:
tweeters[u]['count']+=1
else:
report("New user: "+u)
tweeters[u]={}
tweeters[u]['count']=1
ttags=re.findall("#([a-z0-9]+)", i['text'], re.I)
for tagx in ttags:
if tagx not in tags:
tags[tagx]=1
else:
tags[tagx]+=1
bigdata.extend(data['results'])
return tweeters,tags,bigdata
def twSearchTerm(tweeters,tags,num,q='ukoer', since='',term='',exclRT=False):
t=int(num/100)+1
if t>15:t=15
bigdata=[]
page=1
while page<=t:
url='http://search.twitter.com/search.json?rpp=100&page='+str(page)+'&q='+urllib.quote_plus(q)
print url
if term!='':
url+='+'+urllib.quote_plus(term)
'''
if since!='':
url+='+since:'+since
'''
page+=1
data = simplejson.load(urllib.urlopen(url))
for i in data['results']:
if (exclRT==False) or (exclRT==True and not i['text'].startswith('RT @')):
u=i['from_user'].strip()
if u in tweeters:
tweeters[u]['count']+=1
else:
report("New user: "+u)
tweeters[u]={}
tweeters[u]['count']=1
ttags=re.findall("#([a-z0-9]+)", i['text'], re.I)
for tagx in ttags:
if tagx not in tags:
tags[tagx]=1
else:
tags[tagx]+=1
bigdata.extend(data['results'])
return tweeters,tags,bigdata
#----------------------------------------------------------------
def destroyListIfRequired(api,tag):
lists=api.lists()
listexists= False
for l in lists:
for l2 in l:
if type(l2) is tweepy.models.List:
if l2.slug==tag:
listexists=True
report("List appears to exist...destroying it now")
api.destroy_list(l2.slug)
if listexists is False:
report("List did not appear to exist...")
#----------------------------------------------------------------
def txtFileToList(api,o,tag,fname):
f=open(fname)
members=[]
for i in f:
members.append(i)
addManyToListByScreenName(api,o,tag,members)
f.close()
#----------------------------------------------------------------
def addManyToListByScreenName(api,o,tag,members):
l=[]
createListIfRequired(api, tag)
for u in tweepy.Cursor(api.list_members,owner=o,slug=tag).items():
if type(u) is tweepy.models.User:
l.append(u.screen_name)
for u in members:
if u in l:
report(u+' in list')
else:
report('Adding '+u+' to '+tag+' list')
try:
api.add_list_member(tag, u)
except:
report("Hmm... didn't work for some reason")
#----------------------------------------------------------------
def mergeDicts(dicts,x=False):
merger={}
for d in dicts:
for i in d:
if x is True:
if i in merger:
for c in merger[i]['classVals']:
d[i]['classVals'][c]+='::'+merger[i]['classVals'][c]
merger[i]=d[i]
return merger
def twNamesFromIds(api,idlist):
twr={}
twl=chunks(idlist,99)
for f100 in twl:
report("Hundred batch....")
try:
twd=api.lookup_users(user_ids=f100)
for u in twd:
if type(u) is tweepy.models.User:
if u.screen_name != 'none':
print u.id,u.screen_name
twr[u.id]=u.screen_name
except:
report("Failed lookup...")
return twr
def twDetailsFromIds(api,idlist):
twr={}
twl=chunks(idlist,99)
for f100 in twl:
report("Hundred batch....")
try:
twd=api.lookup_users(user_ids=f100)
for u in twd:
if type(u) is tweepy.models.User:
if u.screen_name != 'none':
print u.id,u.screen_name
twr[u.id]=u
except:
report("Failed lookup...")
return twr
def twWhois(api,idlist):
twr={}
twl=chunks(idlist,99)
for f100 in twl:
report("Hundred batch....")
try:
twd=api.lookup_users(user_ids=f100)
for u in twd:
if type(u) is tweepy.models.User:
if u.screen_name != 'none':
print u.id,u.screen_name
twr[u.screen_name]=u
except:
report("Failed lookup...")
return twr
def getTwitterUsersDetailsByScreenNames(api,users):
twr={}
twl=chunks(users,99)
for f100 in twl:
report("Hundred batch....")
try:
twd=api.lookup_users(screen_names=f100)
for u in twd:
if type(u) is tweepy.models.User:
twr[u.screen_name]=u
#also works on screen_names
except:
report("Failed lookup...")
return twr
def getTwitterUsersDetailsByIDs(api,users):
twr={}
twl=chunks(users,99)
for f100 in twl:
report("Hundred batch....")
try:
twd=api.lookup_users(user_ids=f100)
for u in twd:
if type(u) is tweepy.models.User:
twr[u.screen_name]=u
#also works on screen_names
except:
report("Failed lookup...")
return twr
def getTwitterFriendsDetailsByIDs(api,user,sample='all'):
return getTwitterUserDetailsByIDs(api,user,"friends",sample)
def getTwitterFollowersDetailsByIDs(api,user,sample='all'):
return getTwitterUserDetailsByIDs(api,user,"followers",sample)
def getTwitterUserDetailsByIDs(api,user,typ="friends",sample='all'):
twr={}
if typ is 'friends':
#members=api.friends_ids(user)
#NEED to rewrute downstream to work with iterator?
mi=tweepy.Cursor(api.friends_ids,id=user).items()
members=[]
for m in mi: members.append(m)
#hack bugfix - no idea what's going on
if isinstance(members,tuple): members,junk=members
else:
try:
#members=api.followers_ids(user)
mi=tweepy.Cursor(api.followers_ids,id=user).items()
members=[]
for m in mi: members.append(m)
if isinstance(members,tuple): members,junk=members
except:
members=[]
#hack bugfix - no idea what's going on
if isinstance(members,tuple): members,junk=members
if sample=='all': twl=chunks(members,99)
else:
sample=int(sample)
if len(members)>sample:
membersSample=random.sample(members, sample)
print 'Using a random sample of '+str(sample)+' from '+str(len(members))
else:
membersSample=members
print 'Fewer members ('+str(len(members))+') than sample size: '+str(sample)
twl=chunks(membersSample,99)
for f100 in twl:
report("Hundred batch on "+typ+"....")
try:
twd=api.lookup_users(user_ids=f100)
for u in twd:
if type(u) is tweepy.models.User:
twr[u.screen_name]=u
#also works on screen_names
except:
report("Failed lookup...")
return twr
def gephiOutputNodeDef(f,members,extras=None):
header=gephiCoreGDFNodeHeader()
f.write(header+'\n')
for u in members:
u2=members[u]
if u2.screen_name!='none':
f.write(gephiCoreGDFNodeDetails(u2)+'\n')
def gephiOutputNodeDefPlus(f,members,membersPlus,extras=None):
header=gephiCoreGDFNodeHeader()
f.write(header+','+membersPlus['newt::headerPlus']+'\n')
extras=membersPlus['newt::headerPlus'].split(',')
for u in members:
u2=members[u]
if u2.screen_name!='none':
extension=''
for e in extras:
e=e.strip()
key=e.split(' ')[0]
if u in membersPlus:
print 'extras',extras,'e',e,'key',key,'val',str(membersPlus[u][key])
extension=extension+','+str(membersPlus[u][key]).strip()
else:
print 'extras',extras,'e',e,'key',key,'val',str(0),'error',u
extension=extension+','+str(0)
f.write(gephiCoreGDFNodeDetails(u2)+extension+'\n')
def gephiCoreGDFNodeHeader(typ='twitter'):
if (typ=='delicious'):
header='nodedef> name VARCHAR,label VARCHAR, type VARCHAR'
elif (typ=='min'):
header='nodedef> name VARCHAR,label VARCHAR'
else:
header='nodedef> name VARCHAR,label VARCHAR, totFriends INT,totFollowers INT, location VARCHAR, description VARCHAR'
return header
def gephiCoreGDFNodeDetails(u2):
u2=tidyUserRecord(u2)
details=str(u2.id)+','+u2.screen_name+','+str(u2.friends_count)+','+str(u2.followers_count)+',"'+u2.location+'","'+u2.description+'"'
return details
def gephiOutputNodeDefExtended(f,members,extensions):
header=gephiCoreGDFNodeHeader()
for x in extensions:
y=x.split(' ')
header+=','+y[0]+' '+y[1]
f.write(header+'\n')
for u in members:
u2=members[u]['user']
if u2.screen_name!='none':
fout=gephiCoreGDFNodeDetails(u2)
for x in extensions:
y=x.split(' ')
if y[1]=='INT':
fout+=','+str(members[u]['classVals'][y[0]])
else:
fout+=',"'+str(members[u]['classVals'][y[0]])+'"'
f.write(fout+'\n')
def tidyUserRecord(u2):
if u2.location is not None:
u2.location=u2.location.replace('\r',' ')
u2.location=u2.location.replace('\n',' ')
u2.location=u2.location.encode('ascii','ignore')
else:
u2.location=''
if u2.description is not None:
u2.description=u2.description.replace('\r',' ')
u2.description=u2.description.replace('\n',' ')
u2.description=u2.description.encode('ascii','ignore')
else:
u2.description=''
return u2
def gephiOutputEdgeDefInner(api,f,members,typ='friends',maxf=4000):
f.write('edgedef> user VARCHAR,friend VARCHAR\n')
i=0
membersid=[]
for id in members:
membersid.append(members[id].id)
M=len(members)
Ms=str(M)
for id in members:
i=i+1
friend=members[id]
foafs={}
report("- finding "+typ+" of whatever (friends? followers?) was passed in of "+friend.screen_name+' ('+str(i)+' of '+Ms+')')
#danger hack AJH TH - try to minimise long waits for large friend counts
if typ == 'friends' and int(friend.friends_count)>0 and int(friend.friends_count)<int(maxf):
try:
#foafs=api.friends_ids(friend.id)
mi=tweepy.Cursor(api.friends_ids,id=friend.id).items()
foafs=[]
for m in mi: foafs.append(m)
#hack bugfix - no idea what's going on
if isinstance(foafs,tuple): foafs,junk=foafs
except tweepy.error.TweepError,e:
report(e)
elif typ == 'followers':
if int(friend.followers_count)>0 and int(friend.followers_count)<int(maxf):
try:
#foafs=api.followers_ids(friend.id)
mi=tweepy.Cursor(api.followers_ids,id=friend.id).items()
foafs=[]
for m in mi: foafs.append(m)
#hack bugfix - no idea what's going on
if isinstance(foafs,tuple): foafs,junk=foafs
except tweepy.error.TweepError,e:
report(e)
else: print 'too many...skipping'
#print membersid,'.....',foafs
cofriends=intersect(membersid,foafs)
#being naughty - changing .status to record no. of foafs/no. in community
if hasattr(members[id], 'status'):
members[id].status=0.7+0.3*len(cofriends)/M
report("...weight: "+str(members[id].status))
for foaf in cofriends:
f.write(str(friend.id)+','+str(foaf)+'\n')
def gephiOutputEdgeDefExtra(api,f,members,typ='friends',maxf=100000):
f.write('edgedef> user VARCHAR,friend VARCHAR\n')
i=0
membersid=[]
for id in members:
membersid.append(members[id].id)
M=len(members)
for id in members:
friend=members[id]
foafs={}
report("- finding extra"+typ+" of whatever (friends? followers?) was passed in of "+friend.screen_name)
if typ =='friends':
if friend.friends_count>maxf:
foafs=[]
else:
try:
#foafs=api.friends_ids(friend.id)
mi=tweepy.Cursor(api.friends_ids,id=friend.id).items()
foafs=[]
for m in mi: foafs.append(m)
if isinstance(foafs,tuple): foafs,junk=foafs
except tweepy.error.TweepError,e:
report(e)
else:
if friend.followers_count>maxf:
foafs=[]
else:
try:
#foafs=api.followers_ids(friend.id)
mi=tweepy.Cursor(api.followers_ids,id=friend.id).items()
foafs=[]
for m in mi: foafs.append(m)
if isinstance(foafs,tuple): foafs,junk=foafs
except tweepy.error.TweepError,e:
report(e)
extrafriends=diffset(foafs,membersid)
#being naughty - changing .status to record no. of foafs/no. in community
if hasattr(members[id], 'status'):
members[id].status=0.7+0.3*len(extrafriends)/M
report("...weight: "+str(members[id].status))
for foaf in extrafriends:
f.write(str(friend.id)+','+str(foaf)+'\n')
def gephiOutputEdgeDefOuter(api,f,members,typ='friends',mode='inclusive',maxf=100000):
f.write('edgedef> user VARCHAR,friend VARCHAR\n')
i=0
membersid=[]
for id in members:
membersid.append(members[id].id)
M=len(members)
Ms=str(M)
i=0
for id in members:
i=i+1
friend=members[id]
foafs={}
report("- finding "+typ+" of whatever (friends? followers?) was passed in of "+friend.screen_name+' ('+Ms+' of '+str(i)+')')
try:
if typ is 'friends':
if friend.friends_count>maxf: foafs=[]
else:
try:
#foafs=api.friends_ids(friend.id)
mi=tweepy.Cursor(api.friends_ids,id=friend.id).items()
foafs=[]
for m in mi: foafs.append(m)
if isinstance(foafs,tuple): foafs,junk=foafs
except:
foafs=[]
else:
if friend.followers_count>maxf: foafs=[]
else:
try:
#foafs=api.followers_ids(friend.id)
mi=tweepy.Cursor(api.followers_ids,id=friend.id).items()
foafs=[]
for m in mi: foafs.append(m)
if isinstance(foafs,tuple): foafs,junk=foafs
except:
foafs=[]
#cofriends=intersect(membersid,foafs)
#being naughty - changing .status to record no. of foafs/no. in community
#if hasattr(members[id], 'status'):
# members[id].status=0.7+0.3*len(foafs)/M
# report("...weight: "+str(members[id].status))
if (mode=='inclusive'):
for foaf in foafs:
f.write(str(friend.id)+','+str(foaf)+'\n')
else:
for foaf in foafs:
if foaf not in membersid:
f.write(str(friend.id)+','+str(foaf)+'\n')
except tweepy.error.TweepError,e:
report(e)
def gephiOutputFilePlus(api,dirname, members,membersPlus,typ='innerfriends',fname='PlusNet.gdf'):
report("Generating Gephi file using: "+typ)
f=openTimestampedFile(dirname,typ+fname)
gephiOutputNodeDefPlus(f,members,membersPlus)
if typ is 'innerfriends':
gephiOutputEdgeDefInner(api,f,members,'friends')
elif typ is 'innerfollowers':
gephiOutputEdgeDefInner(api,f,members,'followers')
elif typ is 'outerfriends':
gephiOutputEdgeDefOuter(api,f,members,'friends')
elif typ is 'outerfollowers':
gephiOutputEdgeDefOuter(api,f,members,'followers')
elif typ is 'extrafriends':
gephiOutputEdgeDefExtra(api,f,members,'friends')
f.close()
report("...Gephi "+typ+" file generated")
def gephiOutputFile(api,dirname, members,typ="innerfriends",fname='Net.gdf',maxf=100000):
report("Generating Gephi file using: "+typ)
f=openTimestampedFile(dirname,typ+fname)
gephiOutputNodeDef(f,members)
if typ is 'innerfriends':
gephiOutputEdgeDefInner(api,f,members,'friends',maxf=maxf)
elif typ is 'innerfollowers':
gephiOutputEdgeDefInner(api,f,members,'followers',maxf=maxf)
elif typ is 'extrafriends':
gephiOutputEdgeDefExtra(api,f,members,'friends',maxf=maxf)
elif typ is 'outerfriends':
gephiOutputEdgeDefOuter(api,f,members,'friends',maxf=maxf)
elif typ is 'outerfollowers':
gephiOutputEdgeDefOuter(api,f,members,'followers',maxf=maxf)
elif typ is 'extrafollowers':
gephiOutputEdgeDefExtra(api,f,members,'followers',maxf=maxf)
f.close()
report("...Gephi "+typ+" file generated")
def gephiOutputFileByName(api,fname, members,typ="innerfriends",maxf=100000):
report("Generating Gephi file using: "+typ)
f=open(fname,'wb+')
gephiOutputNodeDef(f,members)
if typ is 'innerfriends':
gephiOutputEdgeDefInner(api,f,members,'friends',maxf=maxf)
elif typ is 'innerfollowers':
gephiOutputEdgeDefInner(api,f,members,'followers',maxf=maxf)
elif typ is 'extrafriends':
gephiOutputEdgeDefExtra(api,f,members,'friends',maxf=maxf)
elif typ is 'outerfriends':
gephiOutputEdgeDefOuter(api,f,members,'friends',maxf=maxf)
elif typ is 'outerfollowers':
gephiOutputEdgeDefOuter(api,f,members,'followers',maxf=maxf)
elif typ is 'extrafollowers':
gephiOutputEdgeDefExtra(api,f,members,'followers',maxf=maxf)
f.close()
report("...Gephi "+typ+" file generated")
def report_hashtagsearch(dirname,tweeters,tags):
report("Generating search summary files")
f=openTimestampedFile(dirname,'tweeps.txt')