本文整理汇总了Python中tweepy.API.get_user方法的典型用法代码示例。如果您正苦于以下问题:Python API.get_user方法的具体用法?Python API.get_user怎么用?Python API.get_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tweepy.API
的用法示例。
在下文中一共展示了API.get_user方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [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: on_data
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
def on_data(self, data):
all_data = json.loads(data)
print data.encode('utf-8')
# tweet = all_data['text']
# username = all_data['user']['screen_name']
userId = all_data['user']['id']
userprofile(userId)
user = API.get_user(userId)
print user.screen_name
示例3: get_all_user_friends
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
def get_all_user_friends(name, auth):
api = API(auth)
# get ids for all of the user followers
ids = []
for friend in Cursor(api.friends, screen_name=name).items():
ids.append(friend.id_str)
# time.sleep(1)
# get information about each user
for key in range(len(ids)):
user = api.get_user(ids[key])
temp_array = [user.id_str, user.screen_name]
write_to_csv(user_friends_file_name, temp_array)
# time.sleep(1)
print "Exported: " + str(len(ids)) + " users."
示例4: print
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
Config.read(path)
# Parse the configuration
try:
c_key = Config.get('twitter', 'Ckey')
c_secret = Config.get('twitter', 'CSecret')
a_token = Config.get('twitter', 'AToken')
a_secret = Config.get('twitter', 'ASecret')
user = Config.get('twitter', 'User')
bot = Config.get('mattermost', 'Name')
avatar = Config.get('mattermost', 'AvatarURL')
hook = Config.get('mattermost', 'Hook')
except ConfigParser.NoOptionError as exception:
print(exception)
exit(1)
# Get an http manager
http = urllib3.PoolManager()
# Create Twitter OAuth tokens
auth = OAuthHandler(c_key, c_secret)
auth.set_access_token(a_token, a_secret)
# Get the user object
api = API(auth)
target = api.get_user(user)
# Create Twitter stream
twitterStream = Stream(auth, listener(target))
twitterStream.filter(follow=[user])
示例5: open
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
log.write(user+"\n")
added.append(user)
f = open("added.txt", "a");
f.write(user);
f.write('\n');
f.close();
'''
for i in Cursor(api.followers, id=user).items():
print "adding " + i.screen_name;
f.write("\t"+i.screen_name+"\n");
to_be_networked.append(i.screen_name);
'''
while True:
try:
temp_user = api.get_user(user);
temp_ratio = float(temp_user.followers_count) / float(temp_user.friends_count);
base_node = graph.find_one("regular", "screen_name", user);
if not base_node:
base_node = graph.find_one("verified", "screen_name", user);
if not base_node:
base_node = graph.find_one("cautious", "screen_name", user);
if not base_node:
if temp_user.verified:
base_node = Node("verified", screen_name=user, ratio=temp_ratio, tweets=temp_user.statuses_count, created=temp_user.created_at, followers=temp_user.followers_count, following=temp_user.friends_count, location=temp_user.location);
else:
if temp_ratio < 0.01:
示例6: Twitter_DH
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
#.........这里部分代码省略.........
def __init__(self, api, my_user_id, cv):
super(Twitter_DH.Listener, self).__init__(api)
self.my_user_id = my_user_id
self.buffer = None
self.queue = []
self.cv = cv
self.timed_out = False
def _process_text(self, text):
parts = text.split(' ') # note: change upper layer delimiter
total_tweets = int(parts[1])
index = int(parts[2])
msg = parts[3]
assert len(parts) == 4
if not self.buffer:
self.buffer = [None] * total_tweets
self.buffer[index] = msg
try:
self.buffer.index(None)
return True
except ValueError:
# we've filled the buffer
to_fill = ''.join(self.buffer)
self.cv.acquire()
self.queue.append(to_fill)
self.buffer = ''
self.cv.notify()
self.cv.release()
def on_status(self, status):
if hasattr(status, 'entities'):
entities = status.entities
if 'user_mentions' in entities:
# Make sure it's from the user we expect
user_mentions = entities['user_mentions']
for mention in user_mentions:
if mention['id'] == self.my_user_id:
return self._process_text(status.text)
def on_timeout(self):
self.cv.acquire()
self.timed_out = True
self.cv.notify()
self.cv.release()
return False
def on_error(self, status):
print 'Got error status: %s' % str(status)
return False
def _run_loop(self):
self.lock.acquire()
self._listen()
if not self.is_bob:
(A, g, p, self.get_key_func) = self._do_dh_alice()
msg = '%s:%s:%s' % (str(A), str(g), str(p))
self.write_twitter_message(self.bob, msg)
while self.should_run:
if len(self.listener.queue) == 0:
self.lock.wait()
if self.listener.timed_out:
self.should_run = False
print 'stopping for timeout'
else:
msg = self.listener.queue.pop(0)
if self.key:
self._decrypt_twitter_message(msg)
self.should_run = False
else:
if self.is_bob:
parts = map(long, msg.strip().split(':'))
(B, self.get_key_func) = self._do_dh_bob(parts[0], parts[1], parts[2])
self.get_key_func(parts[0])
self.write_twitter_message(self.alice, str(B))
else:
B = long(msg.strip())
self.get_key_func(B)
self._write_encrypted_twitter_message(self.bob, 'secret twitter message')
self.should_run = False
self.lock.release()
if self.should_run:
self.lock.acquire()
def _listen(self):
self.listener = Twitter_DH.Listener(self.api, self.my_id, self.lock)
self.stream = Stream(self.twitter, self.listener, timeout=15, headers={'User-Agent': USER_AGENT})
self.stream.filter(follow=[self.other_id], async=True)
def run_alice(self):
self._setup_twitter(self.alice)
self.other_id = self.api.get_user(bob).id
self._run_loop()
def run_bob(self):
self.is_bob = True
self._setup_twitter(self.bob)
self.other_id = self.api.get_user(self.alice).id
self._run_loop()
示例7: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [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
#.........这里部分代码省略.........
示例8: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
class TweepyAPITests(unittest.TestCase):
def setUp(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
auth.set_access_token(oauth_token, oauth_token_secret)
self.api = API(auth)
self.api.retry_count = 2
self.api.retry_delay = 5
def testhometimeline(self):
self.api.home_timeline()
def testfriendstimeline(self):
self.api.friends_timeline()
def testusertimeline(self):
self.api.user_timeline()
self.api.user_timeline('twitter')
def testmentions(self):
self.api.mentions()
def testretweetedbyme(self):
self.api.retweeted_by_me()
def testretweetedbyuser(self):
self.api.retweeted_by_user('twitter')
def testretweetedtome(self):
self.api.retweeted_to_me()
def testretweetsofme(self):
self.api.retweets_of_me()
def testretweet(self):
s = self.api.retweet(test_tweet_id)
s.destroy()
def testretweets(self):
self.api.retweets(test_tweet_id)
def testgetstatus(self):
self.api.get_status(id=test_tweet_id)
def testupdateanddestroystatus(self):
# test update
text = 'testing %i' % random.randint(0, 1000)
update = self.api.update_status(status=text)
self.assertEqual(update.text, text)
# test destroy
deleted = self.api.destroy_status(id=update.id)
self.assertEqual(deleted.id, update.id)
def testgetuser(self):
u = self.api.get_user('twitter')
self.assertEqual(u.screen_name, 'twitter')
u = self.api.get_user(783214)
self.assertEqual(u.screen_name, 'twitter')
def testsearchusers(self):
self.api.search_users('twitter')
def testme(self):
me = self.api.me()
self.assertEqual(me.screen_name, username)
def testfriends(self):
self.api.friends()
def testfollowers(self):
self.api.followers()
def testdirectmessages(self):
self.api.direct_messages()
def testsentdirectmessages(self):
self.api.sent_direct_messages()
def testsendanddestroydirectmessage(self):
# send
sent_dm = self.api.send_direct_message(username, text='test message')
self.assertEqual(sent_dm.text, 'test message')
self.assertEqual(sent_dm.sender.screen_name, username)
self.assertEqual(sent_dm.recipient.screen_name, username)
# destroy
destroyed_dm = self.api.destroy_direct_message(sent_dm.id)
self.assertEqual(destroyed_dm.text, sent_dm.text)
self.assertEqual(destroyed_dm.id, sent_dm.id)
self.assertEqual(destroyed_dm.sender.screen_name, username)
self.assertEqual(destroyed_dm.recipient.screen_name, username)
def testcreatedestroyfriendship(self):
enemy = self.api.destroy_friendship('twitter')
self.assertEqual(enemy.screen_name, 'twitter')
# Wait 5 seconds to allow Twitter time
# to process the friendship destroy request.
#.........这里部分代码省略.........
示例9: screen_name
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
def screen_name(data):
api = API(oauth)
user = api.get_user(data.split(',"screen_name":"')[1].split('","location')[0])
return user.screen_name
示例10: RuleListener
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
class RuleListener(StreamListener):
"""
A twitter stream listener. Given credentials and a ruleset will listen to twitter indefinitely
and get a set of filtered tweets.
"""
def listen(self, rules, consumer_key, consumer_secret, access_token, access_token_secret):
self._ruleset = rules
auth_handler = OAuthHandler(consumer_key, consumer_secret)
auth_handler.set_access_token(access_token, access_token_secret)
self.stream = Stream(auth_handler, self, timeout=None)
follow_list = []
track_list = []
location_list = []
self.api = API(auth_handler)
for rule in self.ruleset:
rule.set_api(self.get_api())
if rule.follow:
for user in rule.follow:
follow_list.append(self.api.get_user(user).id)
if rule.track:
track_list += rule.track
if rule.location:
location_list += rule.location
if rule.historical:
for phrase in track_list:
for i in range(1, 100):
try:
results = self.api.search(phrase, rpp=100, page=i)
rule.send_tweets_to_callback(results, self.api)
except TweepError:
break
try:
signal.signal(signal.SIGTERM, self.disconnect)
self.stream.filter(follow=follow_list, track=track_list, locations=location_list)
except KeyboardInterrupt:
self.stream.disconnect()
def disconnect(self):
self.stream.disconnect()
@property
def ruleset(self):
"""
Return the set of rules for this listener, sorted by priority
"""
return sorted(self._ruleset, key=attrgetter("priority"))
def on_status(self, status):
"""
Callback triggered when we receive a matching tweet.
Print the text and post the tweet's id to the endpoint specified by the given rule.y
"""
for rule in self.ruleset:
if rule.match(status):
requests.post(rule.callback_url, data={"tweet_id": status.id})
rule.send_tweets_to_callback([status], self.get_api())
return
def on_error(self, status_code):
"""
Error callback. Returns True so the stream doesn't get closed.
"""
return True
def get_api(self):
return self.api
示例11: OAuthHandler
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
access_token = "2768450545-t7s0uiSKZ8E82zqzxIL1PDy0L0a0FqqOzcLcO5k"
access_token_secret = "5DimJ3PzYYjXUDcKBeB9r6BQptwfDcxNycsE6mehozSCU"
consumer_key = "UpbIPbjpN6bjlFRLOA7OPRAg4"
consumer_secret = "jxUBvjL8UheS977wnAutaROcF6rBfRG9gq0VhM2OQKIEdMcs0l"
if __name__ == '__main__':
user = "neo4j"
password = "stupdi"
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
temp = api.get_user("razorbacks_ben")
print temp
print temp.created_at
print temp.location
""""
authenticate("localhost:7474", user, password)
graph = Graph("http://localhost:7474/db/data/");
a = Node("regular", screen_name="a")
b = Node("regular", screen_name="b")
graph.create(a)
graph.create(b)
c = graph.find_one("regular", "screen_name", "a")
print c
示例12: TweetStream
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
class TweetStream(StreamListener):
def __init__(self, api, cfg):
super(TweetStream, self).__init__()
self.gsession = FuturesSession(max_workers=10)
self.mapi = api
self.cfg = cfg
self.install_hooks()
self.auth = authenticate(cfg)
self.twapi = API(auth_handler=self.auth)
self.id_cache = {}
self.load_following()
self.database = connect_db()
self.db_lock = threading.RLock()
self.sthread = None
self.filter_others = 1
self.restart_stream()
def install_hooks(self):
self.mapi.hook_raw("KICK", self.on_kick)
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_follow,
predicate=lambda cmd: cmd.message.startswith("*follow"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_unfollow,
predicate=lambda cmd: cmd.message.startswith("*ufollow"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_silence,
predicate=lambda cmd: cmd.message.startswith("*silence"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_usilence,
predicate=lambda cmd: cmd.message.startswith("*usilence"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_spamon,
predicate=lambda cmd: cmd.message.startswith("*nofilter"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_spamoff,
predicate=lambda cmd: cmd.message.startswith("*yesfilter"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_arc,
predicate=lambda cmd: cmd.message.startswith("*arc"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_disgnostic,
predicate=lambda cmd: cmd.message.startswith("*diagnostics"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_helpinfo,
predicate=lambda cmd: cmd.message.startswith("*help"))
self.mapi.hook_command(midori.CONTEXT_CHANNEL, self.api_get_tweet)
def load_following(self):
try:
with open("follows.json", "r") as f:
self.follow_ids = json.load(f)
except:
print("No following.")
self.follow_ids = []
try:
with open("silence.json", "r") as f:
self.silenced_ids = json.load(f)
except:
print("No silenced.")
self.silenced_ids = []
def save_follows(self):
with open("follows.json", "w") as f:
json.dump(self.follow_ids, f)
with open("silence.json", "w") as f:
json.dump(self.silenced_ids, f)
def restart_stream(self):
if self.sthread:
self.sthread.stop()
self.sthread = StreamThread(self)
self.sthread.daemon = 1
self.sthread.start()
def api_helpinfo(self, cmd):
self.mapi.privmsg(cmd.channel, "To show twitter user's tweets: *follow user | Top stop showing twitter user's tweets *ufollow user | To archive.today (and attempt waybacking behind the scenes ) something *arc URL")
def api_follow(self, cmd):
user = self.m_get_userid(cmd.message[8:].strip())
if not user: #or cmd.channel.name != "#nasa_surveilance_van_no.7":
self.mapi.privmsg(cmd.channel, "An argument is required (*follow user)")
else:
self.follow_ids.append(user)
self.save_follows()
self.mapi.privmsg(cmd.channel, "Added to the stalking list. Restarting stream...")
self.restart_stream()
def api_unfollow(self, cmd):
user = self.m_get_userid(cmd.message[9:].strip())
if not user: #or cmd.channel.name != "#nasa_surveilance_van_no.7":
self.mapi.privmsg(cmd.channel, "An argument is required (*ufollow user)")
else:
try:
int(user)
self.follow_ids.remove(user)
except ValueError:
self.mapi.privmsg(cmd.channel, "Not in list.")
else:
self.save_follows()
self.mapi.privmsg(cmd.channel, "Removed from the stalking list. Restarting stream...")
self.restart_stream()
def api_silence(self, cmd):
#.........这里部分代码省略.........
示例13: process_tweet
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
# the page.
if process_tweet(status):
compile_page()
return True
def on_error(self, status):
print status
if __name__ == '__main__':
l = StdOutListener()
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = API(auth, wait_on_rate_limit = True)
user = api.get_user(USERNAME_TO_WATCH)
oldest = None
tweets_list = []
first_run = True
downloaded = 0
print("Starting fetch of old tweets")
while len(tweets_list) > 0 or first_run:
if first_run:
tweets_list = api.user_timeline(screen_name = USERNAME_TO_WATCH,
count = 200, include_rts = False)
first_run = False
else:
#all subsiquent requests use the max_id param to prevent duplicates
tweets_list = api.user_timeline(screen_name = USERNAME_TO_WATCH,
count = 200, max_id = oldest,
示例14: Twitter
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [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):
"""
#.........这里部分代码省略.........
示例15: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_user [as 别名]
class TweepyAPITests(unittest.TestCase):
def setUp(self):
auths = []
for consumer_key, consumer_secret, access_key, access_secret in oauth_keys:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
auths.append(auth)
self.api = API(auths)
self.api.retry_count = 2
self.api.retry_delay = 5
# TODO: Actually have some sort of better assertion
def testgetoembed(self):
data = self.api.get_oembed(test_tweet_id)
self.assertEqual(data["author_name"], "Twitter")
def testhometimeline(self):
self.api.home_timeline()
def testusertimeline(self):
self.api.user_timeline()
self.api.user_timeline("twitter")
def testmentionstimeline(self):
self.api.mentions_timeline()
def testretweetsofme(self):
self.api.retweets_of_me()
def testretweet(self):
# TODO(josh): Need a way to get random tweets to retweet.
raise SkipTest()
def testretweets(self):
self.api.retweets(test_tweet_id)
def testgetstatus(self):
self.api.get_status(id=test_tweet_id)
def testupdateanddestroystatus(self):
# test update
text = "testing %i" % random.randint(0, 1000)
update = self.api.update_status(status=text)
self.assertEqual(update.text, text)
# test destroy
deleted = self.api.destroy_status(id=update.id)
self.assertEqual(deleted.id, update.id)
def testgetuser(self):
u = self.api.get_user("twitter")
self.assertEqual(u.screen_name, "twitter")
u = self.api.get_user(783214)
self.assertEqual(u.screen_name, "twitter")
def testsearchusers(self):
self.api.search_users("twitter")
def testsuggestedcategories(self):
self.api.suggested_categories()
def testsuggestedusers(self):
categories = self.api.suggested_categories()
if len(categories) != 0:
self.api.suggested_users(categories[0].slug)
def testsuggesteduserstweets(self):
categories = self.api.suggested_categories()
if len(categories) != 0:
self.api.suggested_users_tweets(categories[0].slug)
def testme(self):
me = self.api.me()
self.assertEqual(me.screen_name, username)
def testdirectmessages(self):
self.api.direct_messages()
def testsentdirectmessages(self):
self.api.sent_direct_messages()
def testsendanddestroydirectmessage(self):
# send
sent_dm = self.api.send_direct_message(username, text="test message")
self.assertEqual(sent_dm.text, "test message")
self.assertEqual(sent_dm.sender.screen_name, username)
self.assertEqual(sent_dm.recipient.screen_name, username)
# destroy
destroyed_dm = self.api.destroy_direct_message(sent_dm.id)
self.assertEqual(destroyed_dm.text, sent_dm.text)
self.assertEqual(destroyed_dm.id, sent_dm.id)
self.assertEqual(destroyed_dm.sender.screen_name, username)
self.assertEqual(destroyed_dm.recipient.screen_name, username)
def testcreatedestroyfriendship(self):
enemy = self.api.destroy_friendship("twitter")
self.assertEqual(enemy.screen_name, "twitter")
#.........这里部分代码省略.........