本文整理汇总了Python中tweepy.API.me方法的典型用法代码示例。如果您正苦于以下问题:Python API.me方法的具体用法?Python API.me怎么用?Python API.me使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tweepy.API
的用法示例。
在下文中一共展示了API.me方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [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: TwitterHandler
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
class TwitterHandler( StreamListener ):
def __init__( self ):
self.logger = logging.getLogger(__name__)
try:
self.auth = OAuthHandler(twitter_secrets.APP_KEY, twitter_secrets.APP_SECRET)
self.auth.secure = True
self.auth.set_access_token(twitter_secrets.OAUTH_TOKEN, twitter_secrets.OAUTH_TOKEN_SECRET)
self.api = API(self.auth)
# If the authentication was successful, you should
# see the name of the account self.logger.info out
self.logger.info(self.api.me().name)
self.stream = Stream(self.auth, self)
self.stream.userstream(async = True)
except BaseException as e:
self.logger.info("Error in __init__", e)
def on_connect( self ):
self.logger.info("Connection established!!")
def on_disconnect( self, notice ):
self.logger.info("Connection lost!! : ", notice)
def on_data( self, status ):
self.logger.info("Entered on_data()")
data = json.loads(status)
if 'direct_message' in data:
name = data['direct_message']['sender_screen_name']
text = data['direct_message']['text']
m = models.Message(source = "twitter", name = name, message = text, rec_by = "", response = "")
m.save()
self.logger.info("Name: " + name + " Text: " + text)
return True
def on_error( self, status ):
self.logger.info(status)
def sendMessage( self, name, message):
if(self.api.me().screen_name != name):
self.api.send_direct_message(screen_name = name, text = message)
self.logger.info("successfully sent " + message + " to " + name)
else:
self.logger.info("Cannot send message to yourself")
示例3: FaveRetweeter
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [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)
示例4: main
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
def main():
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
print(api.me().name)
stream = Stream(auth, StdOutListener())
stream.userstream()
except BaseException as e:
print("Error in main()", e)
示例5: TwitterAccount
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
class TwitterAccount(object):
'''
Represents an authenticated Twitter account.
'''
__MAX_NUMBER_OF_IDS = 100
__MAX_NUMBER_ERRORS = 10
def __init__(self, twitter_auth_params):
'''
Constructor
'''
auth = OAuthHandler(twitter_auth_params.getConsumerKey(), twitter_auth_params.getConsumerSecret())
auth.secure = True
auth.set_access_token(twitter_auth_params.getAccessTokenKey(), twitter_auth_params.getAccessTokenSecret())
self.__twitterApi = API(auth)
def getAuthenticatedUserId(self):
return self.__twitterApi.me().id
def getListOfFriendsFromId(self, user_id):
friends_ids_list = []
error_count = 0
sending_requests = True
while (sending_requests):
try:
for friend_id in Cursor(self.__twitterApi.friends_ids, user_id=user_id, monitor_rate_limit=True, wait_on_rate_limit=True).items():
friends_ids_list.append(friend_id)
sending_requests = False
except (TweepError, ConnectionResetError) as exception:
print("An error occurred while sending the request to Twitter, trying again...")
print(exception)
error_count += 1
if error_count == TwitterAccount.__MAX_NUMBER_ERRORS:
print("Skipping user ID '"+user_id+"' because there were more than "+TwitterAccount.__MAX_NUMBER_ERRORS+" trials to get neighbors.")
return friends_ids_list
# print("It's been "+str(TwitterAccount.__MAX_NUMBER_ERRORS)+" times in a row that we were enable to send requests to Twitter. Raising exception.")
# raise exception
return friends_ids_list
def convertIdsToScreenName(self, id_list):
if len(id_list) > TwitterAccount.__MAX_NUMBER_OF_IDS:
raise ValueError("The number of IDs to be converted is more than "+TwitterAccount.__MAX_NUMBER_OF_IDS, "len(list of IDs)="+str(len(id_list)))
print("converted!")
示例6: authenticate
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
def authenticate(self, access_token):
"""
Twitterから取得したアクセストークンをもとに認証を行う。
:param access_token: アクセストークン
:type access_token: tuple
:return: ユーザー情報
:rtype: django.contrib.auth.models.User
"""
# APIオブジェクトを構築する
oauth_handler = OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
oauth_handler.set_access_token(access_token[0], access_token[1])
api = API(oauth_handler)
# ログインユーザーのTwitter情報を取得する
try:
twitter_user = api.me()
except TweepError:
return None
# Profile/Userを取得/作成する
try:
profile = Profile.objects.get(twitter_id=twitter_user.id)
user = profile.user
except Profile.DoesNotExist:
# Userを作成する
user = User()
user.username = twitter_user.id
user.first_name = twitter_user.screen_name
user.last_name = twitter_user.name
user.set_unusable_password()
user.save()
# Profileを作成する
profile = Profile()
profile.twitter_id = twitter_user.id
profile.screen_name = twitter_user.screen_name
profile.name = twitter_user.name
profile.description = twitter_user.description
profile.url = twitter_user.url
profile.profile_image_url = twitter_user.profile_image_url
profile.user = user
profile.save()
# 有効なユーザーであるかチェックする
if user.is_active:
return user
else:
return None
示例7: Test
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
class Test():
def __init__(self, oauth):
self.api = API(auth_handler = oauth)
print "[DEBUG] Testing mode initiated."
def credentials(self):
print "[DEBUG] Testing OAuth keys..."
try:
me = self.api.me()
except error.TweepError, e:
print "[EMERG] " + e
print "[EMERG] Re-authentication required!"
SanchanOAuthHandler(self.config).request()
print "[INFO] Successfully authenticated as %s!" % me.screen_name
示例8: get_user
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
def get_user(self):
'''
Returns the user using the Graph API.
'''
user = None
auth = self.accessToken()
if not auth:
return None;
api = API(auth)
try:
user = api.me()
except TweepError, e:
self.session.access_token = None
self.session.token = None
return None
示例9: main
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
def main():
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token_key, access_token_secret)
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream = Stream(auth, Listener())
stream.userstream()
except BaseException as e:
print("Error in main()", e)
示例10: get_user
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
def get_user():
api = API(auth_handler = auth)
return api.me()
示例11: Twitter
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
class Twitter(object):
"""A class that does all interactions with twitter."""
def __init__(self, storage_dir=False, db=False):
"""Initialise the API."""
if not db and not storage_dir:
raise TypeError(
"Twitter() needs either a storage_dir or a db argument."
)
if not db:
db = DB(storage_dir)
self.db = db
ck = self.db.get_config('consumer_key')
cs = self.db.get_config('consumer_secret')
at = self.db.get_config('access_token')
ats = self.db.get_config('access_token_secret')
mf = wtModelFactory()
pr = ModelParser(model_factory=mf)
self.auth = OAuthHandler(ck, cs)
self.auth.set_access_token(at, ats)
self.api = API(self.auth, parser=pr)
try:
self.api.me().name
except TweepError as error:
raise TwitterError("Could not connect to Twitter: %s" % error)
except TypeError as error:
raise TwitterError("Your keys haven't been set correctly!")
def update_status(self, message, reply_id=False):
"""Posts text to twitter."""
if self.__is_sane(message):
try:
self.api.update_status(status=message, in_reply_to_status_id=reply_id)
except TweepError as error:
raise TwitterError("Failed to post status: %s" % error)
return "Status updated."
else:
raise TwitterError("Status too long!")
def get_tweet(self, identification):
"""Return a tweet from either an integer or cached screen name."""
tid = False
try:
int(identification)
tid = identification
except ValueError:
identification = identification.lstrip("@")
tid = self.db.get_last_tid(identification)
if not tid:
raise TwitterError("ID %s not cached." % identification)
try:
return self.api.get_status(tid, include_entities=True)
except TweepError as error:
raise TwitterError("Failed to get tweet: %s" % error)
def get_user(self, user):
"""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):
"""
#.........这里部分代码省略.........
示例12: open
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
from __future__ import absolute_import, print_function
import json
from pprint import pprint
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API
if __name__ == '__main__':
with open('api_secret_token.json') as data_file:
authdata = json.load(data_file)
#pprint(authdata)
auth = OAuthHandler(authdata['consumer_key'], authdata['consumer_secret'])
auth.set_access_token(authdata['access_token'], authdata['access_token_secret'])
api = API(auth)
print(api.me().name)
# If the application settings are set for "Read and Write" then
# this line should tweet out a direct message
# The "Read and Write" setting is on https://dev.twitter.com/apps
api.send_direct_message(user="hrishikesh_date", text="Hello From Pi :)")
示例13: OAuthHandler
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
sys.path.insert(0, os.path.join(os.path.dirname(__file__),
"../tweethandler"))
from tweethandler import TweetHandler
LOG_FORMAT = "%(message)s"
# auth info from environment variables
ckey = os.environ['TH_CONSUMER_KEY']
csecret = os.environ['TH_CONSUMER_SECRET']
akey = os.environ['TH_ACCESS_KEY']
asecret = os.environ['TH_ACCESS_TOKEN']
# storage setup
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(akey, asecret)
storage = API(auth)
me = storage.me()
class TestTweetHandler(unittest.TestCase):
def setUp(self):
self.storage = storage
self.me = me
# logger setup
self.logger = logging.getLogger()
self.formatter = logging.Formatter(LOG_FORMAT)
self.logger.setLevel(logging.DEBUG)
self.setUpHandler()
def setUpHandler(self,
dm_threshold = logging.ERROR,
dm_to = [],
示例14: Twitter_DH
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [as 别名]
class Twitter_DH(object):
def __init__(self, alice, bob):
self.alice = alice
self.bob = bob
self.key = None
self.twitter = None
self.api = None
self.stream = None
self.listener = None
self.my_id = None
self.other_id = None
self.lock = Condition()
self.should_run = True
self.is_bob = False
self.get_key_func = None
def _get_aes(self, key):
return AES.new(key, AES.MODE_CBC)
def modExp(self, a, b, m) :
"""
Computes a to the power b, modulo m, using binary exponentiation
this function taken from source at: http://numericalrecipes.wordpress.com/tag/modular-arithmetic/
"""
a %= m
ret = None
if b == 0:
ret = 1
elif b % 2:
ret = a * self.modExp(a, b - 1, m)
else :
ret = self.modExp(a, b // 2 , m)
ret *= ret
return ret % m
def _get_random_pool(self):
pool = RandomPool()
pool.randomize()
return pool
def _get_dh_secret(self, pool):
return getRandomNumber(16, pool.get_bytes)
def write_twitter_message(self, dst, msg):
print 'sending: %s' % msg
dst = '@' + dst
dst_len = len(dst)
chunk_size = TWEET_LEN - (dst_len + 1 + 2 + 1 + 2 + 1) # 1 for space, 2 for num chunks, 1 for space, 2 for index, 1 for space
msg_len = len(msg)
num_chunks = int(math.ceil(float(msg_len) / float(chunk_size)))
assert num_chunks * chunk_size >= msg_len
assert num_chunks <= MAX_CHUNKS
done = False
i = 0
while not done:
offset = i * chunk_size
end_point = min([offset + chunk_size, msg_len])
if end_point == msg_len:
done = True
tweet = '%s %02d %02d %s' % (dst, num_chunks, i, msg[offset:end_point])
i = i + 1
self.api.update_status(tweet)
time.sleep(0.5)
def _write_encrypted_twitter_message(self, dst, plain_text):
aes = self._get_aes(self.key)
text_len = len(plain_text)
mod = 16 - (text_len % 16)
if mod != 0:
plain_text = plain_text.ljust(text_len + mod, '\0')
cipher_text = b64encode(aes.encrypt(plain_text))
self.write_twitter_message(dst, cipher_text)
def _decrypt_twitter_message(self, cipher_text):
cipher_text = b64decode(cipher_text)
aes = self._get_aes(self.key)
plain_text = aes.decrypt(cipher_text).strip('\0')
print plain_text
def _dh_key(self, secret, prime, public):
'''
key = public ^ secret mod prime
'''
key = self.modExp(public, secret, prime)
key = hex(key)
key = key[2:-1]
key = binascii.unhexlify(key[:64])
self.key = key
def _bob_dh_values(self, A, g, p):
pool = self._get_random_pool()
b = self._get_dh_secret(pool)
B = self.modExp(g, b, p)
return (b, B)
def _do_dh_bob(self, A, g, p):
(b, B) = self._bob_dh_values(A, g, p)
return (B, partial(self._dh_key, b, p))
#.........这里部分代码省略.........
示例15: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import me [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
#.........这里部分代码省略.........