本文整理汇总了Python中twython.Twython.get_friends_ids方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.get_friends_ids方法的具体用法?Python Twython.get_friends_ids怎么用?Python Twython.get_friends_ids使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.get_friends_ids方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scrape
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def scrape(arg):
results = {}
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
friends = twitter.get_friends_ids(screen_name = arg)
#hard cap for time
limit = 10
for follower_id in friends['ids']:
if limit > 0 :
params = {'user_id':follower_id, 'count':3 }
tweets = twitter.get_user_timeline(**params)
for tweet in tweets:
encoded = tweet['text'].encode("utf8")
results = dict(Counter(results) + Counter(text_tags(encoded)))
#random.choice(news)
#f.write(str(text_tags(encoded)))
limit = limit - 1
else:
break
#print results
key = max(results.iteritems(), key=operator.itemgetter(1))[0]
n = random.choice(news)
return [key, n]
示例2: get_queryset
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def get_queryset(self):
provider = self.request.QUERY_PARAMS.get('provider', None)
if provider == 'facebook':
# TODO: what does it look like when a user has more than one social auth for a provider? Is this a thing
# that can happen? How does it affect SocialShareMixin? The first one is the oldest--do we actually want
# the last one?
user_social_auth = self.request.user.social_auth.filter(provider='facebook').first()
graph = facebook.GraphAPI(user_social_auth.extra_data['access_token'])
facebook_friends = graph.request("v2.2/me/friends")["data"]
friends = User.objects.filter(social_auth__provider='facebook',
social_auth__uid__in=[user["id"] for user in facebook_friends])
return friends
elif provider == 'twitter':
user_social_auth = self.request.user.social_auth.filter(provider='twitter').first()
twitter = Twython(
app_key=settings.SOCIAL_AUTH_TWITTER_KEY,
app_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
oauth_token=user_social_auth.tokens['oauth_token'],
oauth_token_secret=user_social_auth.tokens['oauth_token_secret']
)
twitter_friends = twitter.get_friends_ids()["ids"]
friends = User.objects.filter(social_auth__provider='twitter',
social_auth__uid__in=twitter_friends)
return friends
else:
return Response({"errors": "{} is not a valid social provider".format(provider)},
status=status.HTTP_400_BAD_REQUEST)
示例3: get_followers_following
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def get_followers_following(usr_id):
index = 0
print "GETTING FOLLOWERS AND FOLLOWING: " + str(usr_id)
friend_cursor = -1
follower_cursor = -1
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
while (1==1):
try:
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
friends = ""
while (friend_cursor != 0):
following = twitter.get_friends_ids(id = usr_id, cursor = friend_cursor)
for ID in following['ids']:
friends += str(ID) + " "
friend_cursor = following["next_cursor"]
friends = friends[:-1]
if len(friends) == 0:
friends = "null"
follow = ""
while (follower_cursor != 0):
followers = twitter.get_followers_ids(id = usr_id,cursor= follower_cursor)
for ID in followers['ids']:
follow += str(ID) + " "
follower_cursor = followers["next_cursor"]
follow= follow[:-1]
if len(follow) == 0:
follow = "null"
return (friends,follow)
except Exception as e:
print e
if "429 (Too Many Requests)" in str(e):
#global index
index += 1
if index == len(APP_KEYS):
index = 0
print "sleepy time - 15 minutes"
print datetime.datetime.now()
time.sleep(910)
return get_followers_following(usr_id)
elif "401 (Unauthorized)" in str(e):
print "401 error"
return ("null","null")
elif "404 (Not Found)" in str(e):
print "404 error"
return ("null","null")
else:
print e
return ("null","null")
示例4: get_friends
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def get_friends(user_social_auth):
twitter = Twython(
app_key=settings.SOCIAL_AUTH_TWITTER_KEY,
app_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
oauth_token=user_social_auth.tokens['oauth_token'],
oauth_token_secret=user_social_auth.tokens['oauth_token_secret']
)
twitter_friends = twitter.get_friends_ids()["ids"]
friends = User.objects.filter(social_auth__provider='twitter',
social_auth__uid__in=twitter_friends)
return friends
示例5: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def main():
APP_KEY = 'ORbbZFlJWipi3HFblfPuQ'
APP_SECRET = 's2em5f68RBV8UDgW7iXOH5PMFArF5aVj8GG6IgsU'
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
OAUTH_TOKEN = '165916420-31NTOhsitabrC6tgo0Zd87q0f60mGUdjBZan56HQ'
OAUTH_TOKEN_SECRET = '8gpWg3g207b4QMuabv2xkw2VkkMyBPnDEImTquPgZC0vV'
main_user = 100
# Requires Authentication as of Twitter API v1.1
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
user_timeline = twitter.get_friends_ids(screen_name='alex_pardo5', count=5000)
except TwythonError as e:
print e
i = 0
print user_timeline
#G=nx.Graph()
#G.add_node(main_user)
#print user_timeline
#server = xmlrpclib.Server('http://localhost:20738/RPC2')
#G = server.ubigraph
G = ubigraph.Ubigraph()
G.clear()
main_user = G.newVertex(shape="sphere", color="#ffff00", label='alex_pardo5')
red = G.newVertexStyle(shape="sphere", color="#ff0000", size="1")
for user in user_timeline['ids']:
#print twitter.show_user(user_id=user)
#tmp = twitter.show_user(user_id=user)['screen_name']
tmp = user
tmp = G.newVertex(style=red, label=str(tmp))
G.newEdge(main_user,tmp,arrow=True, width=random.randint(1, 5))
i += 1
print i
示例6: fetch_friend_ids
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def fetch_friend_ids(self, user):
"""
fetches friend id's from twitter
Return:
collection of friend ids
"""
auth_data = self._auth_data(user)
tw = Twython(**auth_data)
cursor = -1
friend_ids = []
while True:
data = tw.get_friends_ids(cursor=cursor)
friend_ids += data.get('ids', [])
next_cursor = data.get('next_cursor', 0)
prev_cursor = data.get('prev_cursor', 0)
if not next_cursor or next_cursor == prev_cursor:
break
else:
cursor = next_cursor
return friend_ids
示例7: int
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
for line in fp1:
user = int(line.rstrip())
userIDs.append(user)
apiKey = 'Tl4x7q0fMxTTnwU4gacWOaTBW' #str(argList[1])
accessToken = 'AAAAAAAAAAAAAAAAAAAAAA2BewAAAAAABUUGEYgpIQ1z056Xaib2hyrc6mI%3DTjG1tqzGOv7PfiTJAjPtkA2AmVkw4gqmPduB4UnIteNK2xEpAw' #str(argList[2])
twitter = Twython(apiKey,access_token = accessToken,client_args = client_args)
for user in userIDs:
cur = -1
friendList = []
while cur != 0:
try:
response = twitter.get_friends_ids(user_id=user,count=5000,cursor = cur)
print response
except Exception as e:
print e
continue
cur = response['next_cursor']
friendList = friendList + response['ids']
if cur != 0:
continue
dictionary = {}
dictionary[str(user)] = friendList
fp2.write("{0}\n".format(dictionary))
fp1.close()
fp2.close()
示例8: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
# Get your keys from https://dev.twitter.com/
# Change the api key values marked ##### below with the twitter keys
# Schedule twitterFF.py using crontab or another task scheduler to run every Friday.
import time
import random
from twython import Twython
CONSUMER_KEY = '####'
CONSUMER_SECRET = '####'
ACCESS_KEY = '####'
ACCESS_SECRET = '####'
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
friends = api.get_friends_ids(screen_name="yourtwitterhandle")
new_list = []
for x in friends["ids"]:
new_list.append(x)
#print random id 6 times
ff = ''
for y in range(1,7):
id_position = random.randint(0, len(new_list) -1)
userid = new_list[id_position]
data = api.show_user(user_id=userid)
following = data["screen_name"]
ff = ff + ' ' + '@' + following
api.update_status(status='#FF ' + ff)
示例9: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
#.........这里部分代码省略.........
"""Test searching tweets succeeds"""
self.api.search(q='twitter')
# Direct Messages
def test_get_direct_messages(self):
"""Test getting the authenticated users direct messages succeeds"""
self.api.get_direct_messages()
def test_get_sent_messages(self):
"""Test getting the authenticated users direct messages they've
sent succeeds"""
self.api.get_sent_messages()
def test_send_get_and_destroy_direct_message(self):
"""Test sending, getting, then destory a direct message succeeds"""
message = self.api.send_direct_message(screen_name=protected_twitter_1,
text='Hey d00d! %s' % int(time.time()))
self.api.get_direct_message(id=message['id_str'])
self.api.destroy_direct_message(id=message['id_str'])
def test_send_direct_message_to_non_follower(self):
"""Test sending a direct message to someone who doesn't follow you
fails"""
self.assertRaises(TwythonError, self.api.send_direct_message,
screen_name=protected_twitter_2, text='Yo, man!')
# Friends & Followers
def test_get_user_ids_of_blocked_retweets(self):
"""Test that collection of user_ids that the authenticated user does
not want to receive retweets from succeeds"""
self.api.get_user_ids_of_blocked_retweets(stringify_ids=True)
def test_get_friends_ids(self):
"""Test returning ids of users the authenticated user and then a random
user is following succeeds"""
self.api.get_friends_ids()
self.api.get_friends_ids(screen_name='twitter')
def test_get_followers_ids(self):
"""Test returning ids of users the authenticated user and then a random
user are followed by succeeds"""
self.api.get_followers_ids()
self.api.get_followers_ids(screen_name='twitter')
def test_lookup_friendships(self):
"""Test returning relationships of the authenticating user to the
comma-separated list of up to 100 screen_names or user_ids provided
succeeds"""
self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')
def test_get_incoming_friendship_ids(self):
"""Test returning incoming friendship ids succeeds"""
self.api.get_incoming_friendship_ids()
def test_get_outgoing_friendship_ids(self):
"""Test returning outgoing friendship ids succeeds"""
self.api.get_outgoing_friendship_ids()
def test_create_friendship(self):
"""Test creating a friendship succeeds"""
self.api.create_friendship(screen_name='justinbieber')
def test_destroy_friendship(self):
"""Test destroying a friendship succeeds"""
self.api.destroy_friendship(screen_name='justinbieber')
示例10: on_demand
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def on_demand(items):
""" Use generate() to provide a new tweet for a
user when they tweet 'hit me' """
for tweet in reversed(items):
text = tweet['text'][12:]
if ((text[:6].strip().lower() == "hit me")
and (int(tweet['id']) > lastTweet)):
newJargon = generate()
newTweet = "@" + tweet['user']['screen_name'] + " " + newJargon
newTweet = newTweet[:139]
twitter.update_status(status=newTweet,
in_reply_to_status_id=int(tweet['id']))
def periodic():
""" Periodically tweet out a jargon phrase using generate() """
tweetCheck = randint(0,35)
if (tweetCheck == 5):
newTweet = generate()
twitter.update_status(status=newTweet)
tweets = twitter.get_mentions_timeline()
get_last()
intake(simplify(tweets, twitter.get_friends_ids()['ids']))
on_demand(tweets)
periodic()
示例11: get_following_to_db
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def get_following_to_db(dbpath, sn_table = "tweets9_users"):
distinct = get_D_UsrID(dbpath,sn_table )
index=0
num_checked = 0
rate_ex = 0
ind = 0
already_checked = False
follower_cursor = -1
friend_cursor = -1
print "Starting @ %d"%(ind)
print datetime.datetime.now()
while ind < len(distinct):
#for i in distinct:
i = distinct[ind][0]
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
try:
#twitter = Twython (APP_KEY, APP_SECRET)
#auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
#friend_results = twitter.cursor(twitter.get_friends_ids, id = i, cursor= friend_cursor)
friends = ""
while (friend_cursor):
following = twitter.get_friends_ids(id = i,cursor= friend_cursor)
for ID in following['ids']:
friends += str(ID) + " "
friend_cursor = following["next_cursor"]
num_checked += 1
friends = friends[:-1]
if len(friends) == 0:
friends = "null"
follow = ""
while (follower_cursor):
followers = twitter.get_followers_ids(id = i,cursor= follower_cursor)
for ID in followers['ids']:
follow += str(ID) + " "
follower_cursor = followers["next_cursor"]
num_checked += 1
follow= follow[:-1]
if len(follow) == 0:
follow = "null"
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = '%s' where Usr_ID = '%s'"% (sn_table, friends, i)
cursor.execute(query)
#print query
print "____________________ %dth following updated ________ %d" % (ind, i)
conn.commit()
query = "UPDATE %s SET Followers = '%s' where Usr_ID = '%s' "% (sn_table, follow, i)
cursor.execute(query)
#print query
conn.commit()
conn.close()
print "%dth follower updated_______________________ %d" % (ind, i)
print num_checked
print
follower_cursor = -1
friend_cursor = -1
ind+=1
except Exception as e:
print e
if "429 (Too Many Requests)" in str(e):
index += 1
if index == len(APP_KEYS):
index = 0
print "sleepy time - 15 minutes"
print datetime.datetime.now()
time.sleep(910)
elif "401 (Unauthorized)" in str(e):
print "401 error"
f = open("skipped.txt", "a")
f.write("skipped %dth element, ID: %d\n"%(ind, i))
f.write("__________________________________________"+str(datetime.datetime.now()) + "\n")
f.close()
print "401 nulled %d"%ind
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = 'null', Followers = 'null' where Usr_ID = '%s'"% (sn_table, i)
cursor.execute(query)
conn.commit()
conn.close()
ind+=1
time.sleep(1)
elif "404 (Not Found)" in str(e):
print "404 error"
f = open("skipped.txt", "a")
f.write("404: skipped %dth element, ID: %d \n"%(ind, i))
f.write("__________________________________________"+str(datetime.datetime.now()) + "\n")
f.close()
#.........这里部分代码省略.........
示例12: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
#.........这里部分代码省略.........
'''Test searching tweets succeeds'''
self.api.search(q='twitter')
# Direct Messages
def test_get_direct_messages(self):
'''Test getting the authenticated users direct messages succeeds'''
self.api.get_direct_messages()
def test_get_sent_messages(self):
'''Test getting the authenticated users direct messages they've
sent succeeds'''
self.api.get_sent_messages()
def test_send_get_and_destroy_direct_message(self):
'''Test sending, getting, then destory a direct message succeeds'''
message = self.api.send_direct_message(screen_name=protected_twitter_1,
text='Hey d00d!')
self.api.get_direct_message(id=message['id_str'])
self.api.destroy_direct_message(id=message['id_str'])
def test_send_direct_message_to_non_follower(self):
'''Test sending a direct message to someone who doesn't follow you
fails'''
self.assertRaises(TwythonError, self.api.send_direct_message,
screen_name=protected_twitter_2, text='Yo, man!')
# Friends & Followers
def test_get_user_ids_of_blocked_retweets(self):
'''Test that collection of user_ids that the authenticated user does
not want to receive retweets from succeeds'''
self.api.get_user_ids_of_blocked_retweets(stringify_ids='true')
def test_get_friends_ids(self):
'''Test returning ids of users the authenticated user and then a random
user is following succeeds'''
self.api.get_friends_ids()
self.api.get_friends_ids(screen_name='twitter')
def test_get_followers_ids(self):
'''Test returning ids of users the authenticated user and then a random
user are followed by succeeds'''
self.api.get_followers_ids()
self.api.get_followers_ids(screen_name='twitter')
def test_lookup_friendships(self):
'''Test returning relationships of the authenticating user to the
comma-separated list of up to 100 screen_names or user_ids provided
succeeds'''
self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')
def test_get_incoming_friendship_ids(self):
'''Test returning incoming friendship ids succeeds'''
self.api.get_incoming_friendship_ids()
def test_get_outgoing_friendship_ids(self):
'''Test returning outgoing friendship ids succeeds'''
self.api.get_outgoing_friendship_ids()
def test_create_friendship(self):
'''Test creating a friendship succeeds'''
self.api.create_friendship(screen_name='justinbieber')
def test_destroy_friendship(self):
'''Test destroying a friendship succeeds'''
self.api.destroy_friendship(screen_name='justinbieber')
示例13: updateFollowerFollowings
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
def updateFollowerFollowings(dbpath, user_table = "users"):
distinct = get_D_UsrID(dbpath,sn_table )
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "select Usr_ID from %s where Following is null or Followers is null"
cursor.execute(query)
distinct = cursor.fetchall()
follower_cursor = -1
friend_cursor = -1
print "Starting @ %d"%(ind)
print datetime.datetime.now()
while ind < len(distinct):
#for i in distinct:
i = distinct[ind][0] # Usr_ID
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
try:
#twitter = Twython (APP_KEY, APP_SECRET)
#auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
friends = ""
while (friend_cursor):
following = twitter.get_friends_ids(id = i,cursor= friend_cursor)
for ID in following['ids']:
friends += str(ID) + " "
friend_cursor = following["next_cursor"]
num_checked += 1
friends = friends[:-1]
if len(friends) == 0:
friends = "null"
follow = ""
while (follower_cursor):
followers = twitter.get_followers_ids(id = i,cursor= follower_cursor)
for ID in followers['ids']:
follow += str(ID) + " "
follower_cursor = followers["next_cursor"]
num_checked += 1
follow= follow[:-1]
if len(follow) == 0:
follow = "null"
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = '%s', Followers = '%s', NumFollowing = '%d', NumFollowers = '%d' where Usr_ID = '%s'"% (sn_table, friends,follow, len(friends.split(" ")), len(follow.split(" ")), i)
cursor.execute(query)
#print query
conn.close()
print "____________________ %dth following and friends and their corresponding counts updated ________ %d" % (ind, i)
follower_cursor = -1
friend_cursor = -1
ind+=1
except Exception as e:
print e
if "429 (Too Many Requests)" in str(e):
index += 1
if index == len(APP_KEYS):
index = 0
print "sleepy time; pausing for 15 minutes for APP Keys to renew"
print datetime.datetime.now()
#time.sleep(910)
print "App Rate Limits has been exceeded- we will wait for next runtime before running rest of followers and followings"
return
elif "401 (Unauthorized)" in str(e):
print "401 Unauthorized Error nulling %d________________Usr_ID:%d"%(ind,i)
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = 'null', Followers = 'null' where Usr_ID = '%s'"% (sn_table, i)
cursor.execute(query)
conn.commit()
conn.close()
ind+=1
elif "404 (Not Found)" in str(e):
print "404 Not Found Error nulling %d________________Usr_ID:%d"%(ind,i)
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = 'null', Followers = 'null' where Usr_ID = '%s'"% (sn_table, i)
cursor.execute(query)
conn.commit()
conn.close()
ind+=1
else:
print e
示例14: TwitterBot
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
#.........这里部分代码省略.........
dbaccess.Bookmark.addToDB(url, None)
dbaccess.Tweet.addReferenceToDB(resourceUri, url)
# add user social network relations to repository
# add friends
for u in user_ntw['knows']:
knownUserUri = self.userBaseUri % u
dbaccess.User.addToDB(knownUserUri, self.service, u,
TwitterBot.getDefaultAvatar(), udate=udate)
dbaccess.User.addToDBUserKnowsUser(userUri, knownUserUri, udate=udate)
# add followers
for u in user_ntw['fans']:
otherUserUri = self.userBaseUri % u
dbaccess.User.addToDB(otherUserUri, self.service, u,
TwitterBot.getDefaultAvatar(), udate=udate)
dbaccess.User.addToDBUserKnowsUser(otherUserUri, userUri, udate=udate)
# return number of added resources and last added resource uri
return added
def fetchUserMetadata(self, username):
# get user tweets (only last 20)
data = self.twapi.get_user_timeline(screen_name=username)
return { 'username': username, 'data': data}
def fetchUserNetwork(self, username):
chunk_size = 100 # max returned by bulkUserLookup
# Get Friends
fids, cursor = [], -1
fchunks = [fids[i:i + chunk_size] for i in range(0, len(fids), chunk_size)]
while True:
f = self.twapi.get_friends_ids(screen_name=username, cursor=cursor)
fids.extend(f['ids'])
if f['next_cursor'] == cursor or len(f['ids']) == 0:
break
cursor = f['next_cursor']
# get screen names from ids in chunks of 100
screen_names = []
for chunk in fchunks:
screen_names = []
screen_names.extend([userdata['screen_name']
for userdata in self.twapi.lookup_user(user_id=chunk)])
ntw_knows = screen_names
print ntw_knows
# Get Followers
fids, cursor = [], -1
while True:
f = self.twapi.get_followers_ids(screen_name=username, cursor=cursor)
fids.extend(f['ids'])
if f['next_cursor'] == cursor or len(f['ids']) == 0:
break
cursor = f['next_cursor']
fchunks = [fids[i:i + chunk_size] for i in range(0, len(fids), chunk_size)]
fan_screen_names = []
for chunk in fchunks:
# get all data for all user ids
fan_screen_names.extend([userdata['screen_name']
for userdata in self.twapi.lookup_user(user_id=chunk)])
示例15: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_ids [as 别名]
twitter = Twython(APP_KEY,APP_SECRET, access_token=ACCESS_TOKEN)
#creates the dictionary the results will be stored in
stored=defaultdict(list)
#Reads in the csv with the Twitter handles
ifile = open('inpath.csv', "rb")
for name in ifile:
next_cursor=-1 #initiates the cursor
try:
while(next_cursor != 0):#keeps looping through as long as there are pages there
print(name)
time.sleep(60) # sets a time delay of 60 seconds to keep within the rate limits
#gets the people followed by the screen name
following=twitter.get_friends_ids(screen_name=str(name), cursor=next_cursor)
for x in following[u'ids']: #loops through the ids returned by the Twitter api
name=name.encode('utf-8')
stored[str(name)].append(x) # and appends them to the dictionary where the key is the associated persons user id
next_cursor=following['next_cursor'] #gets the next cursor value
except: # if the call fails which may be because there are no more pages
print('unable to access the people followed by '+str(name)+','+str(next_cursor)+'\n')
#writes the dictionary as a json file to the computer
with open('outpath.json', 'w') as f:
json.dump(stored, f)