本文整理汇总了Python中tweepy.API.mentions_timeline方法的典型用法代码示例。如果您正苦于以下问题:Python API.mentions_timeline方法的具体用法?Python API.mentions_timeline怎么用?Python API.mentions_timeline使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tweepy.API
的用法示例。
在下文中一共展示了API.mentions_timeline方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import mentions_timeline [as 别名]
def get(self):
#-------------MAIN SCRIPT-----------------------
#app_status = state.load()
client = memcache.Client()
print client
#logName = app_status.get('log_name', 'logs/app_log.log')
#logger = self.set_up_logging(logName)
#Create and train markov chain
chainTrainingFile = './data/fortunes.txt'
fortuneChain = MarkovChain(1)
fortuneChain.learn(chainTrainingFile)
#lastChainUpdate = datetime.datetime.now()
#updateFrequency = 2*60*60 #in seconds
#logger.info('Markov Chain Initial Trained on '+ chainTrainingFile + ' at ' + str(lastChainUpdate))
#Authenticate twitter account
#Note: Only do this when ready to go live!
auth = OAuthHandler(secrets['CONSUMER_KEY'], secrets['CONSUMER_SECRET'])
auth.set_access_token(secrets['ACCESS_TOKEN'], secrets['ACCESS_TOKEN_SECRET'])
api = API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
#logger.info('Authentication Successful')
#mostRecentReply = app_status.get('recent_reply', 0)
mostRecentReply = client.gets('recent_reply')
if mostRecentReply is None:
mostRecentReply = 0
memcache.add(key='recent_reply', value=0)
print "MOST RECENT", mostRecentReply
#waitTime = 1 * 60 # In Seconds
#logger.info('Wait time set to ' + str(waitTime) + ' seconds')
#Run forever
#while True:
#If we're on startup, fastforward to current tweet
if mostRecentReply is 0:
#Grab all mentions
mentions = api.mentions_timeline()
#Do not reply to these tweets (as they are old)
if len(mentions) > 0:
mostRecentReply = mentions[0].id
#logger.info('Fast-forwarding most recent reply to ' + str(mostRecentReply))
#Check if we need to retrain the chain (do once per hour)
#if (datetime.datetime.now() - lastChainUpdate).total_seconds() > updateFrequency:
#Retrain chain
# fortuneChain.learn(chainTrainingFile)
# lastChainUpdate = datetime.datetime.now()
# logger.info('Markov chain retrained at ' + str(lastChainUpdate))
print mostRecentReply
#Get tweets directed at account since last check
mentions = api.mentions_timeline(since_id = mostRecentReply)
mentions.reverse()
print len(mentions)
for mention in mentions:
#print mention.text
#print mention.author.screen_name
#logger.info(str(mention))
#Generate a fortune
fortune = self.generateFortune(fortuneChain)
#logger.info(str(fortune))
#Send that user a reply with their fortune
statusRet = api.update_status(status='@' + mention.author.screen_name +
' ' + fortune, in_reply_to_status_id = mention.id)
#logger.info('Replied to ' + mention.author.screen_name)
#Update most recent reply if there's something newer
if len(mentions) > 0:
mostRecentReply = mentions[-1].id
#logger.info('Updating most recent reply to ' + str(mostRecentReply))
#Set the value of the current tweet in the memcache.
tries = 40
print "SETTING REPLY", mostRecentReply
print "TRIES", tries
while tries > 0:
tries -= 1
reply = client.gets('recent_reply')
print reply
if client.cas('recent_reply', mostRecentReply):
break
print tries
#app_status['recent_reply'] = mostRecentReply
#Wait for a period before looping again
#time.sleep(waitTime)
#state.save(app_status)
#logging.shutdown()
#.........这里部分代码省略.........
示例2: handle
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import mentions_timeline [as 别名]
def handle(text, mic, profile):
consumer_key = profile['twitter']["TW_CONSUMER_KEY"]
consumer_secret = profile['twitter']["TW_CONSUMER_SECRET"]
access_token = profile['twitter']["TW_ACCESS_TOKEN"]
access_token_secret = profile['twitter']["TW_ACCESS_TOKEN_SECRET"]
woeid = int(profile['twitter']["WOEID"])
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
myTwitterID = api.me().id
except Exception as e:
print e
mic.say("Connection Error. Twitter service is offline.")
return
directMessages = api.direct_messages(count=1)
latestRetweet = 0
latestMention = 0
latestDirectMessage = 0
try:
directMessageIDFile = open(jasperpath.data('twitter', 'directMessageID.txt'),'r')
directMessageID = directMessageIDFile.readline()
latestDirectMessage = int(directMessageID)
directMessageIDFile.close()
except IOError:
if len(directMessages) > 0:
for directMessage in directMessages:
latestDirectMessage = directMessage.id
directMessageIDFile = open(jasperpath.data('twitter', 'directMessageID.txt'),'w')
directMessageIDFile.write(str(latestDirectMessage))
directMessageIDFile.close()
mentions = api.mentions_timeline(count=1)
try:
mentionIDFile = open(jasperpath.data('twitter', 'mentionIDFile.txt'),'r')
latestMentionID = mentionIDFile.readline()
latestMention = int(latestMentionID)
mentionIDFile.close()
except IOError:
if len(mentions) > 0:
mentionIDFile = open(jasperpath.data('twitter', 'mentionIDFile.txt'),'w')
for mention in mentions:
latestMention = mention.id
mentionIDFile.write(str(latestMention))
mentionIDFile.close()
retweets = api.retweets_of_me(count=1)
try:
retweetsIDFile = open(jasperpath.data('twitter', 'retweetsIDFile.txt'),'r')
retweetsID = retweetsIDFile.readline()
latestRetweet = int(retweetsID)
retweetsIDFile.close()
except IOError:
if len(retweets) > 0:
retweetsIDFile = open(jasperpath.data('twitter', 'retweetsIDFile.txt'),'w')
for retweet in retweets:
latestRetweet = retweet.id
retweetsIDFile.write(str(latestRetweet))
retweetsIDFile.close()
if bool(re.search(r'\bTWEET\b', text, re.IGNORECASE)):
sendTweet(mic, api)
if bool(re.search(r'\bNOTIFICATIONS\b', text, re.IGNORECASE)):
getNotifications(mic,latestRetweet,latestMention,latestDirectMessage, api)
if bool(re.search(r'\bTRENDING\b', text, re.IGNORECASE)):
getWhatsTrending(mic, api, woeid)
if bool(re.search(r'\bTWEETS\b', text, re.IGNORECASE)):
getPublicTweets(mic, api)
示例3: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import mentions_timeline [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)
oauth_handler.secure = configuration.twitter['use_https']
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_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)
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()
return self._api.user_timeline(screen_name=me.screen_name, **kwargs)
@to_status
@include_entities
def get_mentions(self, **kwargs):
return self._api.mentions_timeline(**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
return filter(belongs_to_conversation, tweets_from_participants)
#.........这里部分代码省略.........
示例4: import
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import mentions_timeline [as 别名]
from tweepy import (API, BasicAuthHandler, OAuthHandler, Friendship, Cursor,
MemoryCache, FileCache)
username = os.environ.get('TWITTER_USERNAME', 'replace-with-your-own')
oauth_consumer_key = os.environ.get('CONSUMER_KEY', 'replace-with-your-own')
oauth_consumer_secret = os.environ.get('CONSUMER_SECRET', 'replace-with-your-own')
oauth_token = os.environ.get('ACCESS_KEY', 'replace-with-your-own')
oauth_token_secret = os.environ.get('ACCESS_SECRET', 'replace-with-your-own')
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
auth.set_access_token(oauth_token, oauth_token_secret)
api = API(auth)
api.retry_count = 2
api.retry_delay = 5
file=open('mentions.txt', 'w')
file_timestamp=open('last_mention.txt', 'r+')
timestamp = file_timestamp.readline()
last_showed_mention_date = time.strptime(timestamp, "%b %d %Y %H:%M:%S")
file_timestamp.close()
#read latest mentions, store them in a file, then the C program will read them from the file
#store the date of the last showed message
mentions = api.mentions_timeline()
for status in reversed(mentions):
mention_date = time.strptime(status.created_at.strftime("%b %d %Y %H:%M:%S"), "%b %d %Y %H:%M:%S")
if (last_showed_mention_date<mention_date) and (status.user.screen_name!='dp_table'):
print >>file, 'from @' + status.user.screen_name + ': ' + status.text
file_timestamp=open('last_mention.txt', 'w')
file_timestamp.write(status.created_at.strftime("%b %d %Y %H:%M:%S"))
file_timestamp.close()
示例5: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import mentions_timeline [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 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')
# Wait 5 seconds to allow Twitter time
# to process the friendship destroy request.
sleep(5)
friend = self.api.create_friendship('twitter')
self.assertEqual(friend.screen_name, 'twitter')
#.........这里部分代码省略.........
示例6: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import mentions_timeline [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")
#.........这里部分代码省略.........