当前位置: 首页>>代码示例>>Python>>正文


Python Twython.get_friends_ids方法代码示例

本文整理汇总了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]
开发者ID:jpchen,项目名称:CrazyCorrelations,代码行数:28,代码来源:twitter.py

示例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)
开发者ID:yeti,项目名称:rest_social,代码行数:29,代码来源:views.py

示例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")
开发者ID:koprty,项目名称:REU_scripts,代码行数:60,代码来源:classify_model11.py

示例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
开发者ID:Gointer,项目名称:YAK-server,代码行数:13,代码来源:yak_twitter.py

示例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
开发者ID:alex-pardo,项目名称:6degrees,代码行数:50,代码来源:plot_relationships.py

示例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
开发者ID:mastak,项目名称:python-social-friends-finder,代码行数:24,代码来源:twitter_backend.py

示例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()
开发者ID:aseempatni,项目名称:MentionMe,代码行数:33,代码来源:getFriends.py

示例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)
开发者ID:stefanstranger,项目名称:Python,代码行数:33,代码来源:twitterFF.py

示例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')
开发者ID:hungtrv,项目名称:twython,代码行数:70,代码来源:test_core.py

示例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()
开发者ID:TWHarr,项目名称:JargonTron,代码行数:31,代码来源:JargonTronGit.py

示例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()
#.........这里部分代码省略.........
开发者ID:koprty,项目名称:REU_scripts,代码行数:103,代码来源:getFollowersintoDB.py

示例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')
开发者ID:chrisbol,项目名称:twython,代码行数:70,代码来源:test_twython.py

示例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
开发者ID:koprty,项目名称:REU_scripts,代码行数:91,代码来源:classify_model11.py

示例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)])
        
开发者ID:jokereactive,项目名称:NEWSS-Social-Search,代码行数:69,代码来源:twitterbot.py

示例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)





     
开发者ID:johnardavies,项目名称:Networks-code,代码行数:27,代码来源:Getting+friends+from+a+set+of+usernames.py


注:本文中的twython.Twython.get_friends_ids方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。