本文整理汇总了Python中tweepy.API.favorites方法的典型用法代码示例。如果您正苦于以下问题:Python API.favorites方法的具体用法?Python API.favorites怎么用?Python API.favorites使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tweepy.API
的用法示例。
在下文中一共展示了API.favorites方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
class TweepyApi(BaseTweepyApi, ApiAdapter):
"""
A `ApiAdapter` implementation using `tweepy` library.
http://github.com/tweepy/tweepy/
"""
def __init__(self, *args, **kwargs):
ApiAdapter.__init__(self, *args, **kwargs)
# from `turses.api.base.ApiAdapter`
def init_api(self):
oauth_handler = TweepyOAuthHandler(self._consumer_key,
self._consumer_secret)
oauth_handler.set_access_token(self._access_token_key,
self._access_token_secret)
self._api = BaseTweepyApi(oauth_handler)
@to_user
def verify_credentials(self):
return self._api.me()
@to_user
@include_entities
def get_user(self, screen_name, **kwargs):
return self._api.get_user(screen_name=screen_name, **kwargs)
# timelines
@to_status
@include_entities
def get_home_timeline(self, **kwargs):
tweets = self._api.home_timeline(**kwargs)
retweets = self._api.retweeted_to_me(**kwargs)
tweets.extend(retweets)
return tweets
@to_status
@include_entities
def get_user_timeline(self, screen_name, **kwargs):
return self._api.user_timeline(screen_name, **kwargs)
@to_status
@include_entities
def get_own_timeline(self, **kwargs):
me = self.verify_credentials()
tweets = self._api.user_timeline(screen_name=me.screen_name,
**kwargs)
retweets = self._api.retweeted_by_me(**kwargs)
tweets.extend(retweets)
return tweets
@to_status
@include_entities
def get_mentions(self, **kwargs):
return self._api.mentions(**kwargs)
@to_status
@include_entities
def get_favorites(self, **kwargs):
return self._api.favorites(**kwargs)
@to_direct_message
@include_entities
def get_direct_messages(self, **kwargs):
dms = self._api.direct_messages(**kwargs)
sent = self._api.sent_direct_messages(**kwargs)
dms.extend(sent)
return dms
# NOTE:
# `get_thread` is not decorated with `to_status` because
# it uses `TweepyApi.get_user_timeline` which is already
# decorated
@include_entities
def get_thread(self, status, **kwargs):
"""
Get the conversation to which `status` belongs.
It filters the last tweets by the participanting users and
based on mentions to each other.
"""
author = status.authors_username
mentioned = status.mentioned_usernames
if author not in mentioned:
mentioned.append(author)
tweets = []
for username in mentioned:
tweets.extend(self.get_user_timeline(username, **kwargs))
def belongs_to_conversation(status):
for username in mentioned:
if username in status.text:
return True
return filter(belongs_to_conversation, tweets)
@to_status_from_search
#.........这里部分代码省略.........
示例2: FaveRetweeter
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
class FaveRetweeter(object):
def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.access_token = access_token
self.access_token_secret = access_token_secret
self._authorize()
def _authorize(self):
oauth_handler = OAuthHandler(self.consumer_key, self.consumer_secret)
oauth_handler.set_access_token(self.access_token, self.access_token_secret)
self.tweepy = API(oauth_handler)
def retweet_fave(self):
me = self.tweepy.me()
favorite_count = me.favourites_count
page = randrange(favorite_count)
favorites = self.tweepy.favorites(count=1, page=page)
favorite = favorites[0]
_retweet(favorite, me)
示例3: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
class TweepyApi(BaseTweepyApi, ApiAdapter):
"""
A :class:`turses.api.ApiAdapter` implementation using `tweepy` library.
http://github.com/tweepy/tweepy/
"""
def __init__(self, *args, **kwargs):
ApiAdapter.__init__(self, *args, **kwargs)
# from `turses.api.base.ApiAdapter`
def init_api(self):
oauth_handler = TweepyOAuthHandler(self._consumer_key,
self._consumer_secret,
secure=configuration.twitter['use_https'])
oauth_handler.set_access_token(self._access_token_key,
self._access_token_secret)
self._api = BaseTweepyApi(oauth_handler, secure=configuration.twitter['use_https'])
@to_user
def verify_credentials(self):
return self._api.me()
@to_user
@include_entities
def get_user(self, screen_name, **kwargs):
return self._api.get_user(screen_name=screen_name, **kwargs)
# timelines
@to_status
@include_entities
def get_status(self, status_id, **kwargs):
return self._api.get_status(status_id, **kwargs)
@to_status
@include_entities
def get_home_timeline(self, **kwargs):
tweets = self._api.home_timeline(**kwargs)
retweets = self._api.retweeted_to_me(**kwargs)
tweets.extend(retweets)
return tweets
@to_status
@include_entities
def get_user_timeline(self, screen_name, **kwargs):
return self._api.user_timeline(screen_name, **kwargs)
@to_status
@include_entities
def get_own_timeline(self, **kwargs):
me = self.verify_credentials()
tweets = self._api.user_timeline(screen_name=me.screen_name,
**kwargs)
retweets = self._api.retweeted_by_me(**kwargs)
tweets.extend(retweets)
return tweets
@to_status
@include_entities
def get_mentions(self, **kwargs):
return self._api.mentions(**kwargs)
@to_status
@include_entities
def get_favorites(self, **kwargs):
return self._api.favorites(**kwargs)
@to_direct_message
@include_entities
def get_direct_messages(self, **kwargs):
dms = self._api.direct_messages(**kwargs)
sent = self._api.sent_direct_messages(**kwargs)
dms.extend(sent)
return dms
@include_entities
def get_thread(self, status, **kwargs):
"""
Get the conversation to which `status` belongs.
"""
users_in_conversation = [status.authors_username]
# Save the users that are mentioned
for user in status.mentioned_usernames:
if user not in users_in_conversation:
users_in_conversation.append(user)
# Fetch the tweets from participants before and after `status`
# was published
tweets_from_participants = []
for user in users_in_conversation:
user_tweets = self._get_older_and_newer_tweets(user, status.id)
tweets_from_participants.extend(user_tweets)
def belongs_to_conversation(tweet):
for user in users_in_conversation:
if user in tweet.text:
return True
#.........这里部分代码省略.........
示例4: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
#.........这里部分代码省略.........
self.assertEqual(updated.profile_background_color, '000')
self.assertEqual(updated.profile_text_color, '000')
self.assertEqual(updated.profile_link_color, '000')
self.assertEqual(updated.profile_sidebar_fill_color, '000')
self.assertEqual(updated.profile_sidebar_border_color, '000')
"""
def testupateprofileimage(self):
self.api.update_profile_image('examples/profile.png')
def testupdateprofilebg(self):
self.api.update_profile_background_image('examples/bg.png')
"""
def testupdateprofile(self):
original = self.api.me()
profile = {
'name': 'Tweepy test 123',
'url': 'http://www.example.com',
'location': 'pytopia',
'description': 'just testing things out'
}
updated = self.api.update_profile(**profile)
self.api.update_profile(
name = original.name, url = original.url,
location = original.location, description = original.description
)
for k,v in profile.items():
if k == 'email': continue
self.assertEqual(getattr(updated, k), v)
def testfavorites(self):
self.api.favorites()
def testcreatedestroyfavorite(self):
self.api.create_favorite(4901062372)
self.api.destroy_favorite(4901062372)
def testenabledisablenotifications(self):
self.api.enable_notifications('twitter')
self.api.disable_notifications('twitter')
def testcreatedestroyblock(self):
self.api.create_block('twitter')
self.assertEqual(self.api.exists_block('twitter'), True)
self.api.destroy_block('twitter')
self.assertEqual(self.api.exists_block('twitter'), False)
self.api.create_friendship('twitter') # restore
def testblocks(self):
self.api.blocks()
def testblocksids(self):
self.api.blocks_ids()
def testcreateupdatedestroylist(self):
self.api.create_list('tweeps')
# XXX: right now twitter throws a 500 here, issue is being looked into by twitter.
#self.api.update_list('tweeps', mode='private')
self.api.destroy_list('tweeps')
def testlists(self):
self.api.lists()
示例5: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
#.........这里部分代码省略.........
self._api = BaseTweepyApi(oauth_handler)
def verify_credentials(self):
def to_user(user):
kwargs = {
'screen_name': user.screen_name,
}
return User(**kwargs)
return to_user(self._api.me())
# timelines
def get_home_timeline(self, **kwargs):
tweets = self._api.home_timeline(**kwargs)
retweets = self._api.retweeted_to_me(**kwargs)
tweets.extend(retweets)
return self._to_status(tweets)
def get_user_timeline(self, screen_name, **kwargs):
return self._to_status(self._api.user_timeline(screen_name,
**kwargs))
def get_own_timeline(self, **kwargs):
me = self.verify_credentials()
tweets = self._api.user_timeline(screen_name=me.screen_name,
**kwargs)
retweets = self._api.retweeted_by_me(**kwargs)
tweets.extend(retweets)
return self._to_status(tweets)
def get_mentions(self, **kwargs):
return self._to_status(self._api.mentions(**kwargs))
def get_favorites(self, **kwargs):
return self._to_status(self._api.favorites(**kwargs))
def get_direct_messages(self, **kwargs):
dms = self._api.direct_messages(**kwargs)
sent = self._api.sent_direct_messages(**kwargs)
dms.extend(sent)
return self._to_direct_message(dms)
def get_thread(self, status, **kwargs):
author = get_authors_username(status)
mentioned = get_mentioned_usernames(status)
if author not in mentioned:
mentioned.append(author)
tweets = []
for username in mentioned:
tweets.extend(self.get_user_timeline(username, **kwargs))
def belongs_to_conversation(status):
for username in mentioned:
if username in status.text:
return True
return filter(belongs_to_conversation, tweets)
def get_search(self, text, **kwargs):
# `tweepy.API.search` returns `tweepy.models.SearchResult` objects instead
# `tweepy.models.Status` so we have to convert them differently
def to_status(status):
kwargs = {
'id': status.id,
'created_at': status.created_at,
示例6: OAuthHandler
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
from __future__ import absolute_import, print_function
import config as settings
from tweepy import OAuthHandler
from tweepy import API
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of authenticating with Twitter.
auth = OAuthHandler(settings.consumer_key, settings.consumer_secret)
auth.secure = True
auth.set_access_token(settings.access_token, settings.access_token_secret)
api = API(auth)
# print('Hi, %s!' % api.me().name)
tweets = api.favorites(page=1)
print('Loaded %d tweets ... ' % len(tweets))
for tweet in tweets:
print('%d by %s: %s' % (tweet.id, tweet.author.screen_name, tweet.text.replace('\n', ' ')))
示例7: Twitter
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
#.........这里部分代码省略.........
"""Returns the requested user."""
try:
user = self.api.get_user(user, include_entities=True)
except TweepError as error:
raise TwitterError("Failed to get user: %s" % error)
return user
def get_followed(self):
"""Returns an array of screen_names that you follow."""
try:
followed = []
for user in Cursor(self.api.friends).items(200):
followed.append(user.screen_name)
except TweepError as error:
raise TwitterError("Faled to get followed: %s" % error)
return followed
def get_trend_places(self):
"""
Returns a dict of dicts, first by country then by place.
Every country has a special 'woeid' key that holds the woeid of the
country itself and all the places of the country pointing to their
respective woeids.
A special exception is the 'Worldwide' "country" which only has a
woeid entry.
"""
try:
trend_places = self.api.trends_available()
except TweepError as error:
raise TwitterError("Falied to get available places: %s." % error)
places = defaultdict(dict)
for place in trend_places:
if not place['country']:
places['Worldwide'] = {'woeid': place['woeid']}
else:
if place['country'] == place['name']:
places[place['country']]['woeid'] = place['woeid']
else:
places[place['country']][place['name']] = place['woeid']
return places
def get_trends(self, woeid):
"""
Gets the current trends for the location represented by woeid.
Returns a list of trends with element 0 representing the location name.
"""
try:
trend_response = self.api.trends_place(woeid)
except TweepError as error:
raise TwitterError("Failed to get trends: %s" % error)
trends = []
trends.append(trend_response[0]['locations'][0]['name'])
for trend in trend_response[0]['trends']:
trends.append(trend['name'])
return trends
def get_favorites(self):
"""Get your favourite tweets."""
try:
favorites = self.api.favorites(include_entities=True)
except TweepError as error:
raise TwitterError("Failed to get favourites: %s" % error)
return favorites
def status_count(self, message):
"""
Replaces the URLs and returns the length how twitter would count it.
"""
message = self.__replace_urls(message)
return(len(message))
def __is_sane(self, message):
"""Does sanity checks to see if the status is valid."""
if self.status_count(message) > 140:
return False
return True
def __replace_urls(self, message):
"""Replace URLs with placeholders, 20 for http URLs, 21 for https."""
# regexes to match URLs
octet = r'(?:2(?:[0-4]\d|5[0-5])|1\d\d|\d{1,2})'
ip_addr = r'%s(?:\.%s){3}' % (octet, octet)
# Base domain regex off RFC 1034 and 1738
label = r'[0-9a-z][-0-9a-z]*[0-9a-z]?'
domain = r'%s(?:\.%s)*\.[a-z][-0-9a-z]*[a-z]?' % (label, label)
url_re = re.compile(r'(\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?)' %
(domain, ip_addr), re.I)
new_message = message
for url in url_re.findall(message):
short_url = 'x' * 20
if url.startswith('https'):
short_url = 'x' * 21
new_message = new_message.replace(url, short_url)
return new_message
示例8: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import favorites [as 别名]
#.........这里部分代码省略.........
self.assertEqual(updated.profile_background_color, "000000")
self.assertEqual(updated.profile_text_color, "000000")
self.assertEqual(updated.profile_link_color, "000000")
self.assertEqual(updated.profile_sidebar_fill_color, "000000")
self.assertEqual(updated.profile_sidebar_border_color, "000000")
"""
def testupateprofileimage(self):
self.api.update_profile_image('examples/profile.png')
def testupdateprofilebg(self):
self.api.update_profile_background_image('examples/bg.png')
"""
def testupdateprofile(self):
original = self.api.me()
profile = {
"name": "Tweepy test 123",
"url": "http://www.example.com",
"location": "pytopia",
"description": "just testing things out",
}
updated = self.api.update_profile(**profile)
self.api.update_profile(
name=original.name, url=original.url, location=original.location, description=original.description
)
for k, v in profile.items():
if k == "email":
continue
self.assertEqual(getattr(updated, k), v)
def testfavorites(self):
self.api.favorites()
def testcreatedestroyfavorite(self):
self.api.create_favorite(4901062372)
self.api.destroy_favorite(4901062372)
def testcreatedestroyblock(self):
self.api.create_block("twitter")
self.api.destroy_block("twitter")
self.api.create_friendship("twitter") # restore
def testblocks(self):
self.api.blocks()
def testblocksids(self):
self.api.blocks_ids()
def testcreateupdatedestroylist(self):
params = {"owner_screen_name": username, "slug": "tweeps"}
l = self.api.create_list(name=params["slug"], **params)
l = self.api.update_list(list_id=l.id, description="updated!")
self.assertEqual(l.description, "updated!")
self.api.destroy_list(list_id=l.id)
def testlistsall(self):
self.api.lists_all()
def testlistsmemberships(self):
self.api.lists_memberships()
def testlistssubscriptions(self):
self.api.lists_subscriptions()