本文整理汇总了Python中tweepy.API.get_status方法的典型用法代码示例。如果您正苦于以下问题:Python API.get_status方法的具体用法?Python API.get_status怎么用?Python API.get_status使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tweepy.API
的用法示例。
在下文中一共展示了API.get_status方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [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
#.........这里部分代码省略.........
示例2: DataStream
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [as 别名]
class DataStream(StreamListener):
def __init__(self):
super(DataStream, self).__init__()
self.consumer_key = os.environ['HACKCU_APP_KEY']
self.consumer_secret = os.environ['HACKCU_KEY_SECRET']
self.oauth_key = os.environ['HACKCU_OAUTH_TOKEN']
self.oauth_secret = os.environ['HACKCU_OAUTH_SECRET']
self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
self.auth.set_access_token(self.oauth_key, self.oauth_secret)
self.api = API(self.auth)
self.list_of_words = ['en', 'entre', 'calle', 'interior',
'carretera', 'rumbo', 'evite']
self.words_re = re.compile("|".join(self.list_of_words))
self.reportaje_re = re.compile("|".join(['@CrimeCrow']))
self.last_id = '1'
self.firebase = FirebaseInteraction()
self.tweet_analyzer = TweetReportAnalyzer()
def get_user_from_status(self, id):
status = self.api.get_status(id)
json_string = json.dumps(status._json)
json_string = json.loads(json_string)
return json_string['user']['screen_name']
def on_status(self, status):
status.text = status.text.encode('utf8')
status.text = self.remove_emoji(status.text)
status.text = self.replace_hashtag_with_word(status.text)
status.text = self.replace_hashtag_with_word(status.text)
username = self.get_user_from_status(status.id)
# status.text = self.lowercase_tweets(status.text)
if self.analyze_if_tweet_is_at_us(status.text):
# DO STUFF WITH TWEET AT US
print 'Tweet at us.'
print status.text
if self.tweet_analyzer.analyze_tweet_for_keywords(tweet=status.text):
# FIND KEY WORDS
word_string = str(status.text)
location_result = self.tweet_analyzer.get_location(tweet=word_string)
if location_result:
self.firebase.post_new_report(username=username, tweet_id=status.id, title='', tweet=status.text,
location_title=word_string, lat=location_result['lat'],
lon=location_result['lng'])
try:
self.tweet(status.text)
except TweepError:
print 'Duplicate'
else:
print status.text
self.firebase.post_new_report(username=username, tweet_id=status.id, title='', tweet=status.text,
location_title='', lat='', lon='')
try:
self.tweet(status.text)
except TweepError:
print 'Duplicate'
else:
print 'Tweet not at us.'
print status.text
if self.analyze_tweet_for_keywords(status.text):
# FIND KEY WORDS
word_string = str(status.text)
location_result = self.tweet_analyzer.get_location(word_string)
if location_result:
print status.text
self.firebase.post_new_tweet(username=username, tweet_id=status.id, title='', tweet=status.text,
location_title=word_string, lat=location_result['lat'],
lon=location_result['lng'])
if status.coordinates:
print 'coords:', status.coordinates
if status.place:
print 'place:', status.place.full_name
else:
print status.text
self.firebase.post_new_tweet(username=username, tweet_id=status.id, title='', tweet=status.text,
location_title='', lat='', lon='')
@staticmethod
def on_error(status_code):
print status_code
return False
def tweet(self, tweet):
self.api.update_status(tweet)
def start_stream(self):
stream = Stream(self.auth, self)
stream.filter(track=['balacera', '@CrimeCrow'], async=False)
@staticmethod
def lowercase_tweets(tweet):
return tweet.lower()
def analyze_tweet_for_keywords(self, tweet):
if self.words_re.search(tweet):
return True
else:
return False
def analyze_if_tweet_is_at_us(self, tweet):
#.........这里部分代码省略.........
示例3: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [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.
#.........这里部分代码省略.........
示例4: str
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [as 别名]
for tweet in data:
# Search for tweet in JSON
if search:
if tweet['id'] == start_at:
search = False
print "Found tweet " + str(start_at) + ", starting here...\n"
continue
continue
try:
if update_list:
if tweet['id'] in tweet_list:
counter += 1
counter_break += 1
status = api.get_status(tweet['id'])
tweet['retweet_count'] = status.retweet_count
time.sleep(wait_per_request)
else:
counter_skip += 1
counter_skip_break += 1
if counter_skip_break == 100:
counter_skip_break = 0
print "Skipped a " + str(counter_skip) + "..."
else:
counter += 1
counter_break += 1
status = api.get_status(tweet['id'])
tweet['retweet_count'] = status.retweet_count
time.sleep(wait_per_request)
except TweepError as e:
示例5: TweetStream
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [as 别名]
#.........这里部分代码省略.........
self.mapi.privmsg(cmd.channel, "Silenced. Use '*usilence <name>' to un-silence later.")
self.restart_stream()
def api_usilence(self, cmd):
user = self.m_get_userid(cmd.message[10:].strip())
if not user: #or cmd.channel.name != "#nasa_surveilance_van_no.7":
self.mapi.privmsg(cmd.channel, "An argument is required (*usilence user)")
else:
try:
int(user)
self.silenced_ids.remove(user)
except ValueError:
self.mapi.privmsg(cmd.channel, "Not in list.")
else:
self.save_follows()
self.mapi.privmsg(cmd.channel, "Un-silenced.")
self.restart_stream()
def api_spamon(self, cmd):
self.filter_others = 0
def api_spamoff(self, cmd):
self.filter_others = 1
def api_get_tweet(self, cmd):
statuses = re.findall("http(?:s)?://twitter.com/[a-z0-9\\-_]+/status(?:es)?/([0-9]+)",
cmd.message.lower())
if not statuses:
return
statuses = set(statuses)
for id_ in statuses:
try:
tweet = self.twapi.get_status(id=id_)
except:
continue
the_url = "https://twitter.com/{0}/status/{1}".format(tweet.author.screen_name, tweet.id_str)
urls = self.m_tweet_archive_sync(the_url)
self.midori_push(tweet, urls, cmd.channel)
def api_arc(self, cmd):
to_arc = cmd.message[4:].strip()
to_arc = to_arc.split(" ", 1)[0]
if re.match("http(?:s)?://twitter.com/[a-z0-9\\-_]+/status(?:es)?/([0-9]+)", to_arc):
self.mapi.privmsg(cmd.channel, "Simply linking a tweet is enough to get it archived.")
return
if not to_arc:
self.mapi.privmsg(cmd.channel, "An argument is required. (*arc https://example.com...)")
return
links = self.m_archive_sync(to_arc)
if links:
self.mapi.privmsg(cmd.channel, "{0}: {1}".format(cmd.sender.nick, ", ".join(links)))
else:
self.mapi.privmsg(cmd.channel, "Archive failed; probably an invalid URL.")
def api_disgnostic(self, cmd):
if cmd.sender.hostmask != self.cfg["owner_host"]:
self.mapi.notice(cmd.sender, "You need to authenticate with your NASA employee ID and passphrase before doing that.")
else:
self.mapi.notice(cmd.sender, "{0}".format(str(self.follow_ids)))
ul = self.m_convert_ids_to_users(self.follow_ids)
self.mapi.notice(cmd.sender, "{0}".format(str([u.screen_name for u in ul])))
示例6: Twitter
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [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):
"""
#.........这里部分代码省略.........
示例7: Supytwit
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [as 别名]
#.........这里部分代码省略.........
self.access_token_secret = self.registryValue('access_token_secret')
except AttributeError:
irc.error('Please ensure that all config values for Supytwit have been set')
return
if '' in [self.consumer_key, self.consumer_secret, self.access_token,
self.access_token_secret]:
irc.error('Please ensure that all the registry values are set for Supytwit')
return
self.auth = self._auth(self.consumer_key, self.consumer_secret, self.access_token,
self.access_token_secret)
self.api = API(self.auth)
self.streamListener = IRCStream()
self.streamListener.set_tweets(self)
self.e = threading.Event()
def status(self, irc, msg, args):
self.log.info(','.join([str(thread) for thread in
threading.enumerate()]))
def start(self, irc, msg, args):
"""Start the thread"""
self.log.info(', '.join([t.name for t in threading.enumerate()]))
if filter(lambda x: x.name == 'SupytwitMonitor',
threading.enumerate()):
return
self.e.clear()
self.t = threading.Thread(target=self._monitor, name='SupytwitMonitor')
self.t.start()
start = wrap(start)
def stop(self, irc, msg, args):
"""Stop the thread"""
try:
self.stream.disconnect()
except AttributeError:
pass
stop = wrap(stop)
def die(self):
self.stream.disconnect()
self.__parent.die()
def _monitor(self):
self.stream = Stream(self.auth, self.streamListener, async=True)
while True:
try:
self.stream.userstream()
except httplib.IncompleteRead:
pass
def _auth(self, c_key, c_secret, a_token, a_secret):
auth = OAuthHandler(c_key, c_secret)
auth.set_access_token(a_token, a_secret)
return auth
def _announce(self, status):
if hasattr(status, 'retweeted_status'):
rt = status.retweeted_status
text = 'RT @%s: %s' % (rt.author.screen_name, rt.text)
else:
text = status.text
msg = '@%s: %s' % (ircutils.bold(status.author.screen_name), text)
self.irc.queueMsg(ircmsgs.privmsg(self.announce_channel, unencode(msg)))
def _print(self, status):
self.log.info('@%s: %s' % (status.author.screen_name, status.text))
def parseStatusId(self, message):
for word in message.split(' '):
if word.find('//twitter.com/') != -1:
try:
id = filter(lambda x: x != '', urlparse.urlsplit(word).path.split('/'))[-1]
except IndexError:
return None
return id
def doPrivmsg(self, irc, msg):
if msg.args[1].find("//twitter.com/") != -1:
id = self.parseStatusId(msg.args[1])
self.log.info(id)
try:
status = self.api.get_status(id)
except tweepy.TweepError:
pass
author = status.author.screen_name
if hasattr(status, 'retweeted_status'):
rt = status.retweeted_status
text = 'RT @%s: %s' % (rt.author.screen_name, rt.text)
else:
text = status.text.replace('\n', ' ')
message = '@%s: %s' % (ircutils.bold(author), text)
self.log.info(message)
irc.queueMsg(ircmsgs.privmsg(msg.args[0], unencode(message)))
示例8: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import get_status [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")
#.........这里部分代码省略.........