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


Python Twython.get_friends_list方法代码示例

本文整理汇总了Python中twython.Twython.get_friends_list方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.get_friends_list方法的具体用法?Python Twython.get_friends_list怎么用?Python Twython.get_friends_list使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twython.Twython的用法示例。


在下文中一共展示了Twython.get_friends_list方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fetch_friends

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
    def fetch_friends(self, user):
        """
        fetches the friends from twitter using the
        information on django-social-auth models
        user is an instance of UserSocialAuth

        Returns:
            collection of friend objects fetched from Twitter
        """

        # now fetch the twitter friends using `twython`
        auth_data = self._auth_data(user)
        tw = Twython(**auth_data)
        cursor = -1
        friends = []
        while True:
            data = tw.get_friends_list(cursor=cursor)
            friends += data.get('users', [])

            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 friends
开发者ID:CheckiO,项目名称:django-social-friends-finder,代码行数:28,代码来源:twitter_backend.py

示例2: get_following

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
def get_following(log, id):
    log.debug("  Getting people %s is following", id)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    log.setLevel(old_level)

    cursor = -1
    max_loops = 15
    while cursor != 0:
        try:
            log.setLevel(logging.ERROR)
            following = twitter.get_friends_list(screen_name=id, cursor=cursor, count=200)
            log.setLevel(old_level)
        except TwythonAuthError, e:
            log.exception("   Problem trying to get people following")
            twitter_auth_issue(e)
            raise
        except:
开发者ID:Ninotna,项目名称:evtools,代码行数:23,代码来源:tl_tweets.py

示例3: fetch_friends

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
    def fetch_friends(self, user):
        """
        fetches the friends from twitter

        Returns:
            collection of friend objects fetched from Twitter
        """
        auth_data = self._auth_data(user)
        tw = Twython(**auth_data)
        cursor = -1
        friends = []
        while True:
            data = tw.get_friends_list(cursor=cursor)
            friends += data.get('users', [])

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

示例4: get

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
    def get(self, request, *args, **kwargs):
        APP_KEY = 'Yf8q3TPgL59StYj8KRlsAMmLu'
        APP_SECRET = 'KuMfl4Kvu0Y5W8qVYbusiu6L5x78wK3jpDJV1WAPfcjEy6zAvA'
        OAUTH_TOKEN = "198514629-mTKORfs9NmA29kfbnxrU9bCzyc8NvrzFDP9XLiTw"
        OAUTH_TOKEN_SECRET = 'r9u7SJPrc7u7Vy9pz66uMrfcBSzL8he6HRHprJgEC6bGQ'
        twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        try:
            search_term = request.GET.get('srch-term', 'twitter')
            search_results = twitter.search(q=search_term, count=10)
        except TwythonError as e:
            print e


        my_updates = twitter.get_friends_list(count=500)
        my_updates = my_updates['users']
        the_type = type(my_updates)


        return render(request, "catalog/twitter.html", {
            'search_results': search_results['statuses'],
            'my_updates': my_updates,
            'the_type': the_type
        })
开发者ID:muhtar05,项目名称:ksvadbe,代码行数:25,代码来源:views.py

示例5: TwythonAPITestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]

#.........这里部分代码省略.........
        '''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')

    def test_update_friendship(self):
        '''Test updating friendships succeeds'''
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='false')

    def test_show_friendships(self):
        '''Test showing specific friendship succeeds'''
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    def test_get_friends_list(self):
        '''Test getting list of users authenticated user then random user is
        following succeeds'''
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    def test_get_followers_list(self):
        '''Test getting list of users authenticated user then random user are
        followed by succeeds'''
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    def test_get_account_settings(self):
        '''Test getting the authenticated user account settings succeeds'''
        self.api.get_account_settings()

    def test_verify_credentials(self):
        '''Test representation of the authenticated user call succeeds'''
        self.api.verify_credentials()

    def test_update_account_settings(self):
        '''Test updating a user account settings succeeds'''
        self.api.update_account_settings(lang='en')

    def test_update_delivery_service(self):
        '''Test updating delivery settings fails because we don't have
        a mobile number on the account'''
        self.assertRaises(TwythonError, self.api.update_delivery_service,
                          device='none')

    def test_update_profile(self):
        '''Test updating profile succeeds'''
开发者ID:chrisbol,项目名称:twython,代码行数:70,代码来源:test_twython.py

示例6: TwythonAPITestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]

#.........这里部分代码省略.........
        """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')

    def test_update_friendship(self):
        """Test updating friendships succeeds"""
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets=False)

    def test_show_friendships(self):
        """Test showing specific friendship succeeds"""
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    def test_get_friends_list(self):
        """Test getting list of users authenticated user then random user is
        following succeeds"""
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    def test_get_followers_list(self):
        """Test getting list of users authenticated user then random user are
        followed by succeeds"""
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    def test_get_account_settings(self):
        """Test getting the authenticated user account settings succeeds"""
        self.api.get_account_settings()

    def test_verify_credentials(self):
        """Test representation of the authenticated user call succeeds"""
        self.api.verify_credentials()

    def test_update_account_settings(self):
        """Test updating a user account settings succeeds"""
        self.api.update_account_settings(lang='en')

    def test_update_delivery_service(self):
        """Test updating delivery settings fails because we don't have
        a mobile number on the account"""
        self.assertRaises(TwythonError, self.api.update_delivery_service,
                          device='none')

    def test_update_profile(self):
        """Test updating profile succeeds"""
开发者ID:hungtrv,项目名称:twython,代码行数:70,代码来源:test_core.py

示例7: add_alert

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
def add_alert(request):
	if not request.user.is_authenticated():
		return HttpResponseRedirect('/')
		
	context = {}
	context.update(csrf(request))
	
	user = request.user
	profile = TwitterProfile.objects.all().filter(user=user).get()
	
	alerts_count = len(GrainVacuum.objects.all().filter(profile=profile))
	
	screen_name_list = None
	name_list = None
	
	if request.method == "POST":
		follow_user = request.POST['follow_user']
		key_words = request.POST['key_words_list']
		
		follow_user = follow_user.replace('@','')
		
		new_grain = GrainVacuum(profile=profile,user=user,follow_user=follow_user,key_words=key_words)
		new_grain.save()
		
		return HttpResponseRedirect('/dashboard/')
	else:
		# Update FriendList
		
		try:
			# Determine if friend_list exists
			try:
				friend_list = FriendList.objects.all().filter(twitter_profile=profile).get()
			except:
				# if it doesn't exist create a blank one
				
				new_friend_list = FriendList(twitter_profile=profile)
				new_friend_list.save()
				friend_list = FriendList.objects.all().filter(twitter_profile=profile).get()
			
			est = pytz.timezone('US/Eastern') # Eastern Time Zone
			last_checked = friend_list.last_checked
			now = datetime.datetime.now()
			tdelta = 0
			if last_checked != None:
				last_checked = last_checked.astimezone(est).replace(tzinfo=None)
				tdelta = int((now - last_checked).total_seconds() / 60)
			
			print last_checked
			
			if tdelta > 15 or last_checked == None:
				APP_KEY = Config.objects.all().latest('id').twitter_key
				APP_SECRET = Config.objects.all().latest('id').twitter_secret
				
				# Get Authorization Credentials
				OAUTH_TOKEN = profile.oauth_token
				OAUTH_TOKEN_SECRET = profile.oauth_secret
				
				friend_list_update = FriendList.objects.all().filter(twitter_profile=profile)
				twitter = Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
				
				# Query Twitter Friends List API until none
				screen_name_list = ""
				name_list = ""
				next_cursor=-1
				count = 0
				while next_cursor:
					follow_list = twitter.get_friends_list(count=200,cursor=next_cursor)
					
					y = 0
					for user in follow_list['users']:
						screen_name = user['screen_name']
						name = user['name']
						
						if y == 0:
							screen_name_list += screen_name
							name_list += name
						else:
							screen_name_list += "," + screen_name
							name_list += "," + name
						
						y += 1
						print screen_name + ' ' + name
						
					count += 1
					if count == 15 or next_cursor == 0:
						break
					next_cursor = follow_list["next_cursor"]
					
				friend_list_update.update(last_checked=now,name=name_list,handle=screen_name_list)
			else:
				screen_name_list = friend_list.handle
				name_list = friend_list.name
				
		except Exception as error:
			print error
	
	return render_to_response('add_alert.html', {'screen_name_list':screen_name_list,'name_list':name_list,'alerts_count':alerts_count}, context_instance=RequestContext(request))
开发者ID:alexandercrosson,项目名称:grained,代码行数:99,代码来源:views.py

示例8: TwythonEndpointsTestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]

#.........这里部分代码省略.........
        """Test returning incoming friendship ids succeeds"""
        self.api.get_incoming_friendship_ids()

    @unittest.skip('skipping non-updated test')
    def test_get_outgoing_friendship_ids(self):
        """Test returning outgoing friendship ids succeeds"""
        self.api.get_outgoing_friendship_ids()

    @unittest.skip('skipping non-updated test')
    def test_create_friendship(self):
        """Test creating a friendship succeeds"""
        self.api.create_friendship(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_destroy_friendship(self):
        """Test destroying a friendship succeeds"""
        self.api.destroy_friendship(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_update_friendship(self):
        """Test updating friendships succeeds"""
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets=False)

    @unittest.skip('skipping non-updated test')
    def test_show_friendships(self):
        """Test showing specific friendship succeeds"""
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    @unittest.skip('skipping non-updated test')
    def test_get_friends_list(self):
        """Test getting list of users authenticated user then random user is
        following succeeds"""
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_followers_list(self):
        """Test getting list of users authenticated user then random user are
        followed by succeeds"""
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    @unittest.skip('skipping non-updated test')
    def test_get_account_settings(self):
        """Test getting the authenticated user account settings succeeds"""
        self.api.get_account_settings()

    @unittest.skip('skipping non-updated test')
    def test_verify_credentials(self):
        """Test representation of the authenticated user call succeeds"""
        self.api.verify_credentials()

    @unittest.skip('skipping non-updated test')
    def test_update_account_settings(self):
        """Test updating a user account settings succeeds"""
        self.api.update_account_settings(lang='en')

    @unittest.skip('skipping non-updated test')
    def test_update_delivery_service(self):
        """Test updating delivery settings fails because we don't have
        a mobile number on the account"""
开发者ID:nouvak,项目名称:twython,代码行数:70,代码来源:test_endpoints.py

示例9: Twython

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)

friends_file = unicodecsv.writer(open(FILE_LOC, "wb"))

#Run basic program
if(ADVANCED==0):
	#Write csv column headers
	friends_file.writerow(["User Name","Name","ID","Description","Location","URL"])

	next_cursor=-1
	p = 1
	while(next_cursor != 0):
		print "Loading page", p , "of results from Twitter"
		#Loop/set variables for each user in friends list
		friends = twitter.get_friends_list(screen_name = USERNAME, count = 200, cursor = next_cursor)

		print "Writing page", p , "to csv file"
		for result in friends['users']:
			screen_name = result['screen_name']
			name = result['name']
			tw_id = result['id']
			description = result['description']
			location = result['location']
			entities = result['entities']
			expanded_url = None
			if('url' in entities):
				entities_url = entities['url']
				entities_urls = entities_url['urls']
				for entities_result in entities_urls:
					expanded_url = entities_result['expanded_url']
开发者ID:nathancheek,项目名称:twitter-archive-extra,代码行数:32,代码来源:getfriends.py

示例10: Tweety

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
class Tweety(object):
    """
    Twitter client using Twython
    """

    def __init__(self, app_key=TWITTER_APP_KEY, app_secret=TWITTER_APP_SECRET,
                 oauth_token=TWITTER_OAUTH_TOKEN, oauth_token_secret=TWITTER_OAUTH_SECRET):
        try:
            self.twitter = Twython(
            app_key,
            app_secret,
            oauth_token,
            oauth_token_secret)
            self.cache = RedisCache({
            'server': REDIS_SERVER,
            'port': REDIS_PORT,
            'database': REDIS_DATABASE,
            'key_prefix': 'domus-twitter'
            })
        except TwythonAuthError:
            raise Exception("Unable to connect to twitter")

    def __get_friends(self):
        """
        Using twitter get_friends and redis, gets a list of screen names
        :return:a list of twitter users
        """
        results = self.cache.get('twitter_friends')
        if not results:
            try:
                results = [a['screen_name'] for a in self.twitter.get_friends_list()['users']]
                self.cache.store('twitter_friends',json.dumps(results), expires=120)
            except (TwythonError, TwythonRateLimitError):
                raise Exception('Unable to get followers list')
        else:
            results = json.loads(results)
        return results

    def tweet(self, message,to_friends=False):
        """
        Writtes a twit
        :param message: what to tweet
        :param to_friends: send to all friends?
        :return:
        """
        try:
            if to_friends:
                for a_friend in self.__get_friends():
                    mention = "@{} ".format(a_friend)
                    available_chars = 140 - len(mention)
                    self.twitter.update_status(
                        status=(mention+message)[:available_chars] + ((mention+message)[(available_chars-2):] and '..'))
            else:
                self.twitter.update_status(
                        status=message[:140] + (message[138:] and '..'))
        except (TwythonError, TwythonRateLimitError):
            raise Exception("Unable to post update")

    def dm(self, user, message):
        try:
            self.twitter.send_direct_message(screen_name=user, text=message)
        except TwythonError:
            raise Exception("Unable to send dm to {}".format(user))

    def get_dms(self):
        """
        Gets a list of dms. Stores the last id seen so the next request is for the new messages only.
        :return: a dict of the form {tweet_id:{sender:screen_name,text:the_message}}
        """
        results = {}
        dms = []
        last_id = self.cache.get('twitter_last_dm')
        if last_id:
            dms = self.twitter.get_direct_messages(count=100,since_id = last_id)
        else:
            dms = self.twitter.get_direct_messages(count=100)
        if dms:
            last_id = 0
            for a_dm in dms:
                results[a_dm['id']] = {'from':a_dm['sender_screen_name'],'text': a_dm['text']}
                last_id = a_dm['id'] if a_dm['id'] > last_id else last_id
            self.cache.store('twitter_last_dm', last_id)
        return results

    def get_mentions(self):
        """
        Gets a list of mentions.  Stores the last id seen so the next request is for the new messages only.
        :return: a dict of the form {tweet_id:{sender:screen_name,text:the_message}}
        """
        results = {}
        mentions = []
        last_id = self.cache.get('twitter_last_mention')
        if last_id:
            mentions = self.twitter.get_mentions_timeline(count=100,since_id = last_id)
        else:
            mentions = self.twitter.get_mentions_timeline(count=100)
        if mentions:
            last_id = 0
            for a_mention in mentions:
                results[a_mention['id']] = {'from':a_mention['user']['screen_name'],'text': a_mention['text']}
#.........这里部分代码省略.........
开发者ID:Esiravegna,项目名称:domus,代码行数:103,代码来源:tweety.py

示例11: print

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
tweets = twitter.get_home_timeline(count=1)
for tweet in tweets:
    print(tweet['text'])

print
print "My Settings"
print "==========="

settings = twitter.get_account_settings()
#print settings
print "I am @%s" % settings['screen_name']

print
print "My friends"
print "=========="

list = twitter.get_friends_list()
for friend in list['users']:
    print "I follow user @%s, name %s, id %d" % (
        friend['screen_name'], friend['name'], friend['id'])

print
print "My followers"
print "============"

list = twitter.get_followers_list()
for friend in list['users']:
    print "User @%s, name %s, id %d is following me" % (
        friend['screen_name'], friend['name'], friend['id'])
    #print friend
开发者ID:ArduinoAndoain,项目名称:test,代码行数:32,代码来源:twitter_followers.py

示例12: Twython

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_friends_list [as 别名]
REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token="
ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"

CONSUMER_KEY = "K7ddHMoZcHXu0WyWdnp6wdQxf"
CONSUMER_SECRET = "OcvSpsGJ5e1f9GvHbT1y5TXLzwETVkL9wkd1WDzL3FHgC7WDzk"

ACCESS_KEY = "2539409241-FFZPA5lh2vZklUx3q5jASFesRVVXPxqfS6nY8QB"
ACCESS_SECRET = "zzQVXih1Gy2cR1WdMtcMhmXbWpi1S45Jc7vlLlkHFWwm9"

twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)




user_Friends = twitter.get_friends_list(screen_name="Francis_Pruter", count=200, skip_status='true', include_user_entities='false')

ctr = 1

fcountlist={}

for friend in user_Friends['users']:
  fcountlist[friend['name']] = friend['friends_count']
  ctr = ctr+1

fcountlist["ME"] = ctr-1

#sort list by friend count https://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

fcountlist = OrderedDict(sorted(fcountlist.items(), key=lambda t: t[1]))
开发者ID:fpruter,项目名称:cs595-f14,代码行数:32,代码来源:twitterFriendCounter.py


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