当前位置: 首页>>代码示例>>Python>>正文


Python Twython.get_lastfunction_header方法代码示例

本文整理汇总了Python中twython.Twython.get_lastfunction_header方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.get_lastfunction_header方法的具体用法?Python Twython.get_lastfunction_header怎么用?Python Twython.get_lastfunction_header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twython.Twython的用法示例。


在下文中一共展示了Twython.get_lastfunction_header方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Questions

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
class Questions(object):
    
    def __init__(self, appKey, appKeySecret, accessToken, accessTokenSecret):
        
        self.questions = {}
        self.handle = Twython(app_key=appKey, app_secret=appKeySecret, oauth_token=accessToken, oauth_token_secret=accessTokenSecret)
        self.handle.get_home_timeline()
        print "Remaining API calls: ", self.handle.get_lastfunction_header('x-rate-limit-remaining')

        
    def getTweet(self, tweetId):
        status = self.handle.show_status(id=tweetId)
        tweetText = self.unescape(status['text'])
        tweetText = re.sub(r'([ \t]*[#]+[\w]+[ \t]*|[ \t]*[#]+[ \t]*|[ \t]+$|[ \t]*[@]\w+[ \t]*)', '', tweetText)
        return tweetText
    
    def exprValidator(self, tweetId):
        
        text = self.getTweet(tweetId)
        
        print "validation: " + text
        
        if text[-1] in ['>', '<']:
            text = text[:-1]
        elif text[-2] in ['>','<','=','!']:
            text = text[:-2]
        else:
            return False
        
        try:
            exec("r = " + text)
            if r == None:
                return False
            return True
        except:
            return False

    def refresh(self, channel):
        search = self.handle.search(q=channel, count=25)
        tweets = search['statuses']
        for tweet in tweets:
            # Not a retweet
            if tweet['text'][:2] != 'RT' and self.exprValidator(tweet['id']):
                #db.addTweetToDB(channel, tweet['id'])
                # If channel exists
                if channel in self.questions:
                    # If ID is not on the list
                    if tweet['id'] not in self.questions[channel]:
                        self.questions[channel].append(tweet['id'])
                # Channel doesn't exist, create it
                else:
                    self.questions[channel] = [ tweet['id'] ]
    
    def unescape(self, text):
        text = text.replace("&lt;", "<")
        text = text.replace("&gt;", ">")
        text = text.replace("&amp;", "&")
        return text
开发者ID:CattleOfRa,项目名称:unicode,代码行数:60,代码来源:Questions.py

示例2: main

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
def main():
    if len(sys.argv) != 6:
        print("not enough arguments.")
        os.sys.exit(1)

    consumer_key = sys.argv[1]
    consumer_secret = sys.argv[2]
    access_key = sys.argv[3]
    access_secret = sys.argv[4]
    image_file = sys.argv[5]

    status = ("{d.year}年{d.month}月{d.day}日{d.hour}時{d.minute:02}分頃のちくらん"
              .format(d=dt.now()))
    media = open(image_file, 'rb')

    retry_count = 0
    while True:
        try:
            # raise Exception("retry test")
            twitter = Twython(consumer_key, consumer_secret, access_key, access_secret)
            response = twitter.update_status_with_media(status=status, media=media)
            # print(response)
            break
        except Exception as e:
            print("caught exception: {}".format(e))
            if retry_count == MAX_RETRY_COUNT:
                print("retried over.")
                os.sys.exit(1)
            retry_count += 1
            print("retrying({}/{})...".format(retry_count, MAX_RETRY_COUNT))
            sys.stdout.flush()
            time.sleep(SLEEP_WHEN_RETRY)

    limit = twitter.get_lastfunction_header('X-MediaRateLimit-Limit')
    remaining = twitter.get_lastfunction_header('X-MediaRateLimit-Remaining')
    reset = twitter.get_lastfunction_header('X-MediaRateLimit-Reset')
    print("rate limit, limit: {} remaining: {} reset: {}".format(limit, remaining, reset))
开发者ID:honishi,项目名称:chikuranbot,代码行数:39,代码来源:tweet.py

示例3: print

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
            # store document
            tweets.insert_one(item)
        else:
            # update the record
            res = db.tweets.replace_one( {'user_id':id}, item )
            if res.matched_count == 0:
                print("no match for id: ",id)
            else:
                if res.modified_count == 0:
                    print("no modification for id: ",id)
                else:
                    print("replaced id ",tl[0]['user']['screen_name'],
                            id,len(tl), tl[0]['lang'] )
    except TwythonRateLimitError as e:
        # Wait if we hit the Rate limit
        reset = int(twitter.get_lastfunction_header('x-rate-limit-reset'))
        wait = max(reset - time.time(), 0) + 10 # addding 10 second pad
        print("[Exception Raised] Rate limit exceeded waiting: %s", wait)
        time.sleep(wait)
    except:
        print(" FAILED:", id)
        print("Unexpected error:", sys.exc_info()[0])
        pass

# ---------------------------------------------------------
#  check how many documents we now have in the Database
# ---------------------------------------------------------
follower_docs = db.tweets.find()
documents    = [tw['raw_text']  for tw in follower_docs]
print("We have " + str(len(documents)) + " documents ")
开发者ID:ashwatthaman,项目名称:datatalks,代码行数:32,代码来源:twitter_data.py

示例4: Search

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
    def Search(self, **kwargs):
        """
        Returns tweets of given search query.  This does not save tweets to file.
        You must provide at least one search query and the argument name has to be
        given (e.g. Search(q = "obama", ...))

        Arguments:
            :param dataPath [string] - path where you want the data fils stored
            :param fileNamePrefix [string] - this is added to the front of the file name
            :param entriesPerFile [int] - number of tweets to save per file
            and standard search parameters *

        Return:
            Nothing
            
        * https://dev.twitter.com/docs/api/1.1/get/search/tweets
        
        """
        
        searchParameterKeyList = ['q', 'geocode', 'result_type', 'until', 'max_id', 'count', 'lang', 'locale', 'since_id', 'include_entities']
        
        # Set default wait time between queries if no specified
        if 'waitTime' in kwargs.keys():
            waitTime = kwargs['waitTime']
        else:
            waitTime = 5.0
        # Set default number of tweets to retrieve
        if 'count' not in kwargs.keys():
            kwargs['count'] = 100
        
        twitter = Twython(self.authen['consumer_key'], self.authen['consumer_secret'], \
            self.authen['access_token_key'], self.authen['access_token_secret'])
        
        # Container for all search statuses
        search_statuses = []
        search_metadata = []
    
        while (kwargs['count'] > 0):
            
            # Bulid the query string
            paramString = ""
            for (index, searchParameterKey) in enumerate(searchParameterKeyList):
                if searchParameterKey in kwargs.keys() and kwargs[searchParameterKey] != None:
                    paramString = paramString + '%s = "%s",' %(searchParameterKey, kwargs[searchParameterKey])
            # Removing the trailing comma
            if (paramString[-1] == ','):
                paramString = paramString[0:-1]
    
            # Generate eval string
            evalStr = 'twitter.search(%s)' % paramString
            
            # Keep trying until get a result
            tries = 0
            while (tries < self.MAXTRIES):
                try:
                    search_results = eval(evalStr)
                    if search_results != []:
                        break
                except TwythonError as e:
                    tries += 1
                    print e
                    time.sleep(waitTime*2)
            
            # Break if no results were returned
            if (search_results['statuses'] == []):
                break
                
            # Append to list
            for n in search_results['statuses']:
                search_statuses.append(n)
            search_metadata.append(search_results['search_metadata'])
            
            # Display the first message every time we receive a block of messages
            if (search_results['statuses'] != []):
                tweet = search_results['statuses'][0]
                if ('text' in tweet.keys()):
                    print('Tweet from @%s Date: %s' % (tweet['user']['screen_name'].encode('utf-8'), tweet['created_at']))
                    print('Tweet text: %s' %tweet['text'].encode('utf-8'))
            # Print status report
            print('Requests left: %s, reset time: %s' %(twitter.get_lastfunction_header('X-Rate-Limit-Remaining'), \
                twitter.get_lastfunction_header('X-Rate-Limit-Reset')))
            
            # decrement the count; twitter API limits number of returned tweets to 100
            kwargs['count'] -= 100
    
            # Set new max_id so that don't get the same results again
            kwargs['max_id'] = search_results['statuses'][-1]['id']-1
    
            # Wait so we don't get the 420 error by making too many queries
            time.sleep(waitTime)
            
        return(search_statuses, search_metadata)
开发者ID:mojo00,项目名称:TwitterDownloader,代码行数:94,代码来源:TwitterDownloader.py

示例5: TwythonAPITestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]

#.........这里部分代码省略.........

    @responses.activate
    def test_request_should_handle_401(self):
        """Test that Twython raises an auth error on 401 error"""
        endpoint = 'statuses/home_timeline'
        url = self.get_url(endpoint)
        self.register_response(responses.GET, url, body='{"errors":[{"message":"Error"}]}', status=401)

        self.assertRaises(TwythonAuthError, self.api.request, endpoint)

    @responses.activate
    def test_request_should_handle_400_for_missing_auth_data(self):
        """Test that Twython raises an auth error on 400 error when no oauth data sent"""
        endpoint = 'statuses/home_timeline'
        url = self.get_url(endpoint)
        self.register_response(responses.GET, url,
                               body='{"errors":[{"message":"Bad Authentication data"}]}', status=400)

        self.assertRaises(TwythonAuthError, self.api.request, endpoint)

    @responses.activate
    def test_request_should_handle_400_that_is_not_auth_related(self):
        """Test that Twython raises a normal error on 400 error when unrelated to authorization"""
        endpoint = 'statuses/home_timeline'
        url = self.get_url(endpoint)
        self.register_response(responses.GET, url,
                               body='{"errors":[{"message":"Bad request"}]}', status=400)

        self.assertRaises(TwythonError, self.api.request, endpoint)

    @responses.activate
    def test_request_should_handle_rate_limit(self):
        """Test that Twython raises an rate limit error on 429"""
        endpoint = 'statuses/home_timeline'
        url = self.get_url(endpoint)
        self.register_response(responses.GET, url,
                               body='{"errors":[{"message":"Rate Limit"}]}', status=429)

        self.assertRaises(TwythonRateLimitError, self.api.request, endpoint)

    @responses.activate
    def test_get_lastfunction_header_should_return_header(self):
        """Test getting last specific header of the last API call works"""
        endpoint = 'statuses/home_timeline'
        url = self.get_url(endpoint)
        self.register_response(responses.GET, url, adding_headers={'x-rate-limit-remaining': 37})

        self.api.get(endpoint)

        value = self.api.get_lastfunction_header('x-rate-limit-remaining')
        self.assertEqual(37, value)
        value2 = self.api.get_lastfunction_header('does-not-exist')
        self.assertIsNone(value2)
        value3 = self.api.get_lastfunction_header('not-there-either', 96)
        self.assertEqual(96, value3)

    def test_get_lastfunction_header_should_raise_error_when_no_previous_call(self):
        """Test attempting to get a header when no API call was made raises a TwythonError"""
        self.assertRaises(TwythonError, self.api.get_lastfunction_header, 'no-api-call-was-made')

    @responses.activate
    def test_sends_correct_accept_encoding_header(self):
        """Test that Twython accepts compressed data."""
        endpoint = 'statuses/home_timeline'
        url = self.get_url(endpoint)
        self.register_response(responses.GET, url)

        self.api.get(endpoint)

        self.assertEqual(b'gzip, deflate, compress', responses.calls[0].request.headers['Accept-Encoding'])

    # Static methods
    def test_construct_api_url(self):
        """Test constructing a Twitter API url works as we expect"""
        url = 'https://api.twitter.com/1.1/search/tweets.json'
        constructed_url = self.api.construct_api_url(url, q='#twitter')
        self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter')

    def test_encode(self):
        """Test encoding UTF-8 works"""
        self.api.encode('Twython is awesome!')

    def test_html_for_tweet(self):
        """Test HTML for Tweet returns what we want"""
        tweet_text = self.api.html_for_tweet(test_tweet_object)
        self.assertEqual(test_tweet_html, tweet_text)

    def test_html_for_tweet_expanded_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object,
                                             use_expanded_url=True)
        # Make sure full url is in HTML
        self.assertTrue('http://google.com' in tweet_text)

    def test_html_for_tweet_short_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object, False)
        # Make sure HTML doesn't contain the display OR expanded url
        self.assertTrue('http://google.com' not in tweet_text)
        self.assertTrue('google.com' not in tweet_text)
开发者ID:Alandey,项目名称:twython,代码行数:104,代码来源:test_core.py

示例6: main

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]

#.........这里部分代码省略.........
                    logger.error("Some other error occured, taking a break for half a minute: "+str(err))
                    sleep(30)
                    continue
                return results

        def save_tweets(statuses,current_since_id):
            for status in statuses:
                status['created_at']=parse_datetime(status['created_at'])
                try:
                    status['user']['created_at']=parse_datetime(status['user']['created_at'])
                except:
                    pass
                tweets.update({'id':status['id']},status,upsert=True)
                current_id = longtype(status['id'])
                if current_id>current_since_id:
                    current_since_id = current_id

            if len(statuses)==0:
                logger.debug("No new tweets. Taking a break for 10 seconds...")
                sleep(10)
            else:
                logger.debug("Received "+str(len(statuses))+" tweets.")
            return current_since_id

        logger.info("Collecting tweets from the search API...")

        while True:
            results = perform_query(q=query,geocode=geocode,lang=lang,count=100,since_id=since_id,result_type=result_type)

            refresh_url = results['search_metadata'].get('refresh_url')
            p = urlparse.urlparse(refresh_url)
            # we will now compute the new since_id as the maximum of all returned ids
            #new_since_id = dict(urlparse.parse_qsl(p.query))['since_id']
            logger.debug("Rate limit for current window: "+str(twitter.get_lastfunction_header(header="x-rate-limit-remaining")))
            if since_id:
                current_since_id = longtype(since_id)
            else:
                current_since_id = 0
            new_since_id = save_tweets(results['statuses'],current_since_id)

            next_results = results['search_metadata'].get('next_results')
            while next_results:
                p = urlparse.urlparse(next_results)
                next_results_max_id = dict(urlparse.parse_qsl(p.query))['max_id']
                results = perform_query(q=query,geocode=geocode,lang=lang,count=100,since_id=since_id,max_id=next_results_max_id,result_type=result_type)
                next_results = results['search_metadata'].get('next_results')
                logger.debug("Rate limit for current window: "+str(twitter.get_lastfunction_header(header="x-rate-limit-remaining")))
                new_since_id = save_tweets(results['statuses'],new_since_id)

            new_since_id = str(new_since_id)
            queries.update({'query':query,'geocode':geocode,'lang':lang},{"$set":{'since_id':new_since_id}},upsert=True)
            since_id = new_since_id

    if args.subcommand=='stream':
        from twython import TwythonStreamer

        loglevel = args.loglevel

        logging.basicConfig(format=FORMAT,level=logging_dict[loglevel],stream=sys.stdout)
        logger = logging.getLogger('twitter')

        if args.consumer_key is None or args.consumer_secret is None or args.access_token is None or args.access_token_secret is None:
            logger.fatal("Consumer key, consumer secret, access token and access token secret are all required when using the streaming API.")
            sys.exit(1)

        try:
开发者ID:johnkordonis14,项目名称:twitter-tap,代码行数:70,代码来源:tap.py

示例7: TwythonAPITestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
class TwythonAPITestCase(unittest.TestCase):
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__twython__ Test'
            },
            'allow_redirects': False
        }

        oauth2_client_args = {
            'headers': {}  # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied
        }

        self.api = Twython(app_key, app_secret,
                           oauth_token, oauth_token_secret,
                           client_args=client_args)

        self.oauth2_api = Twython(app_key, access_token=access_token,
                                  client_args=oauth2_client_args)

    def test_construct_api_url(self):
        """Test constructing a Twitter API url works as we expect"""
        url = 'https://api.twitter.com/1.1/search/tweets.json'
        constructed_url = self.api.construct_api_url(url, q='#twitter')
        self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter')

    def test_get(self):
        """Test Twython generic GET request works"""
        self.api.get('account/verify_credentials')

    def test_post(self):
        """Test Twython generic POST request works, with a full url and
        with just an endpoint"""
        update_url = 'https://api.twitter.com/1.1/statuses/update.json'
        status = self.api.post(update_url, params={'status': 'I love Twython!'})
        self.api.post('statuses/destroy/%s' % status['id_str'])

    def test_get_lastfunction_header(self):
        """Test getting last specific header of the last API call works"""
        self.api.get('statuses/home_timeline')
        self.api.get_lastfunction_header('x-rate-limit-remaining')

    def test_get_lastfunction_header_not_present(self):
        """Test getting specific header that does not exist from the last call returns None"""
        self.api.get('statuses/home_timeline')
        header = self.api.get_lastfunction_header('does-not-exist')
        self.assertEqual(header, None)

    def test_get_lastfunction_header_no_last_api_call(self):
        """Test attempting to get a header when no API call was made raises a TwythonError"""
        self.assertRaises(TwythonError, self.api.get_lastfunction_header,
                          'no-api-call-was-made')

    def test_search_gen(self):
        """Test looping through the generator results works, at least once that is"""
        search = self.api.search_gen('twitter', count=1)
        counter = 0
        while counter < 2:
            counter += 1
            result = next(search)
            new_id_str = int(result['id_str'])
            if counter == 1:
                prev_id_str = new_id_str
                time.sleep(1)  # Give time for another tweet to come into search
            if counter == 2:
                self.assertTrue(new_id_str > prev_id_str)

    def test_encode(self):
        """Test encoding UTF-8 works"""
        self.api.encode('Twython is awesome!')

    def test_html_for_tweet(self):
        """Test HTML for Tweet returns what we want"""
        tweet_text = self.api.html_for_tweet(test_tweet_object)
        self.assertEqual(test_tweet_html, tweet_text)

    def test_html_for_tweet_expanded_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object,
                                             use_expanded_url=True)
        # Make sure full url is in HTML
        self.assertTrue('http://google.com' in tweet_text)

    def test_html_for_tweet_short_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object, False)
        # Make sure HTML doesn't contain the display OR exapanded url
        self.assertTrue(not 'http://google.com' in tweet_text)
        self.assertTrue(not 'google.com' in tweet_text)

    def test_raise_error_on_bad_ssl_cert(self):
        """Test TwythonError is raised by a RequestException when an actual HTTP happens"""
        self.assertRaises(TwythonError, self.api.get, 'https://example.com')

    # Timelines
    def test_get_mentions_timeline(self):
        """Test returning mentions timeline for authenticated user succeeds"""
        self.api.get_mentions_timeline()

#.........这里部分代码省略.........
开发者ID:hungtrv,项目名称:twython,代码行数:103,代码来源:test_core.py

示例8: int

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
                                print 'Mentioned ID: %s' % mention.get('id_str')
                        for hashtag in message['entities']['hashtags']:
                                print 'Hashtag: %s' % hashtag.get('text')
                        for url in message['entities']['urls']:
                                print 'URL: %s' % url.get('expanded_url')
                        print 'Timestamp: %s' % message.get('created_at')
			print 'Coordinates: %s' % message.get('coordinates')
			print 'Retweeted: %s' % message.get('retweeted')
			print 'Retweet Count: %s' % message.get('retweet_count')

			lookup_user += message['user'].get('id_str') + ","

		if int(message.get('id')) > newest_tweet:
			newest_tweet = message.get('id')

	print twitter.get_lastfunction_header('x-rate-limit-remaining')

if lookup_user:
	lookup_user = twitter.lookup_user(user_id=lookup_user)
	for user in lookup_user:
		print 'User: %s' % user.get('id_str')
		print 'Name: %s' % user.get('name')
		print 'Screen Name: %s' % user.get('screen_name')
		print 'Profile Image: %s' % user.get('profile_image_url')
		print 'User Location: %s' % user.get('location')
		print 'Created: %s' % user.get('created_at')
		print 'URL: %s' % user.get('url')
		print 'Follower Count: %s' % user.get('followers_count')
		print 'Description: %s' % user.get('description')
		print 'Verified: %s' % user.get('verified')
开发者ID:eightzerobits,项目名称:osint-tool,代码行数:32,代码来源:TwitterSearch.py

示例9: __init__

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
class TweetBot:
	def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret):
		self.account = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
		self.step = 15 

	def verify_credentials(self):
		# https://dev.twitter.com/rest/reference/get/account/verify_credentials
		info = self.account.verify_credentials(include_entities=False, skip_status=True, include_email=False)
		name = info.get('name', None)
		if name is None:
			log.error('Could not verify credentials')
		else:
			log.info('Logged in as @{name}, tweets: {tweets}, followers: {followers}'.format(
				name = name,
				tweets = info['statuses_count'],
				followers = info['followers_count']))
		return info

	def upload_twitter_picture(self, picture_path):
		photo = open(picture_path, 'rb')
		log.debug("Uploading '{}'".format(picture_path))
		response = self.account.upload_media(media=photo)
		return response['media_id']

	def reply_media_tweet(self, status, reply_id, media_path):
		media_id = self.upload_twitter_picture(media_path)
		tweet = self.account.update_status(status=status, media_ids=[media_id], in_reply_to_status_id=reply_id)
		return tweet

	def reply_text_tweet(self, status, reply_id):
		tweet = self.account.update_status(status=status, in_reply_to_status_id=reply_id)
		log.info('Responded with text to {}'.format(reply_id))
		return tweet

	def rate_limit_remaining(self):
		rate_limit = self.account.get_lastfunction_header('x-rate-limit-remaining')
		log.info('Rate limit remaining: {}'.format(rate_limit))
		return rate_limit

	def favorite(self, status_id):
		tweet = self.account.create_favorite(id=status_id)
		log.debug('Favorited tweet {}'.format(status_id))
		return tweet

	# Find first tweet mentioning any element of query_list_OR
	# in the tweet text (excluding user names).
	# Only tweets for which predicate_func(tweet) is truthy are returned.
	# Returns a tuple of the found status/tweet and what element of
	# the query_list_OR was identified.
	# Returns (None, None) if no matching tweets were found.
	def find_single_tweet(self, query_list_OR, predicate_func):
		counter = 0
		while counter <= len(query_list_OR):
			current_query = query_list_OR[counter:counter+self.step]
			log.debug("Searching for '{}'".format(', '.join(current_query)))
			statuses = self.account.search(q=' OR '.join(current_query), count=50)['statuses']
			log.debug("Found {} matching tweets".format(len(statuses)))
			self.rate_limit_remaining()
			counter += self.step
			for status in statuses:
				# Should be able to identify which part of the query list was mentioned
				text = status['text'].lower()
				found = None
				for query_item in current_query:
					if text.rfind(query_item.lower()) > -1:
						found = query_item
						break
				if found is None:
					continue
				# Identified query part should not be part of tweeting user's name
				if found.lower() in status['user']['screen_name'].lower():
					continue
				# Identified query part should not be part of a mentioned user's name
				mentions = status['entities'].get('user_mentions')
				for m in mentions:
					if found.lower() in m['screen_name'].lower():
						continue
				# Identified query part should not be in user name being replied to
				if found.lower() in (status['in_reply_to_screen_name'] or '').lower():
					continue
				# Should return True for the passed predicate_func
				if not predicate_func(status):
					continue
				log.info(TWITTER_STATUS_URL_TEMPLATE.format(id=status['id']))
				log.info(status['text'].replace('\n',' '))
				return (status, found)
		log.warn("No tweets matching '{}' were found".format(query_list_OR))
		return (None, None)
开发者ID:chrisma,项目名称:yourpokedex,代码行数:90,代码来源:tweeter.py

示例10: __init__

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]

#.........这里部分代码省略.........
                rospy.Duration(1), self.timer_home_cb, oneshot = True )
        timer_mentions = rospy.Timer(
                rospy.Duration(2), self.timer_mentions_cb, oneshot = True )
        timer_dm = rospy.Timer(
                rospy.Duration(3), self.timer_dm_cb, oneshot = True )

    # Tweet callback
    def post_cb(self, req):
        txt = req.text
        rospy.logdebug("Received a tweet: " + txt)

        # If only one picture, use twitter upload
        if len(req.images) == 1:
            path = self.save_image( req.images[0] )

            first = True
            for tweet in self.split_tweet( txt ):
                if (req.reply_id == 0):
                    if first:
                        result = self.t.updateStatusWithMedia( 
                                file_ = path, status = tweet )
                        first = False
                    else:
                        result = self.t.updateStatus( status = tweet )
                else:
                    if first:
                        result = self.t.updateStatusWithMedia( file_ = path, 
                            status = tweet, in_reply_status_id = req.reply_id )
                        first = False
                    else:
                        result = self.t.updateStatus( status = tweet,
                                in_reply_to_status_id = req.reply_id )
                # Check response for each update.        
                if self.t.get_lastfunction_header('status') != '200 OK':
                    return None

            os.system('rm -f ' + path)

        elif len(req.images) != 0:
            txt +=  upload( req.images )

        # Publish after splitting.
        for tweet in self.split_tweet( txt ):
            if (req.reply_id == 0):
                result = self.t.updateStatus( status = tweet )
            else:
                result = self.t.updateStatus( 
                        status = tweet, in_reply_to_status_id = req.reply_id )

            if self.t.get_lastfunction_header('status') != '200 OK':
                return None

        return PostResponse(id = result['id'])

    def retweet_cb(self, req):
        result = self.t.retweet( id = req.id )
        if self.t.get_lastfunction_header('status') != '200 OK':
            return None
        else: 
            return IdResponse()

    # Does not raise an error if you are already following the user
    def follow_cb(self, req):
        rospy.logdebug("Asked to follow:" + req.user)
        result = self.t.createFriendship( screen_name = req.user )
        if self.t.get_lastfunction_header('status') != '200 OK':
开发者ID:namimi,项目名称:twitros,代码行数:70,代码来源:twitter.py

示例11: seek

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_lastfunction_header [as 别名]
# If you do not seek(0), the image will be at the end of th=e file and
# unable to be read
photo.seek(0)
print ("photo created rate limit is:" )
# x= twitter.get_home_timeline()
# # print(x)

try:
	image_ids = twitter.upload_media(media=photo)
	print (image_ids)
# except Twython.TwythonError as terr:
	# print "ERROR on twitter = ({0}): {1}".format(terr.errno, terr.strerror)
except TwythonRateLimitError as terr:
	print "ERROR on twitter rate = ({0}): {1}".format(terr1.errno, terr.strerror)
except Exception as err:
	print "ERROR on unknown = " + err
	
y=twitter.get_lastfunction_header('X-Rate-Limit-Reset')
print(y)
z=twitter.get_lastfunction_header('x-rate-limit-remaining')
print(z)

print ("media id = " + str(image_ids['media_id']) )

statusupdate=twitter.update_status(status= newStatus,media_ids=image_ids['media_id'])

print(statusupdate)

# https://pbs.twimg.com/media/CUgwTiUWwAAGGol.jpg

开发者ID:kmacpher67,项目名称:twitterpicyng,代码行数:31,代码来源:weathercap1.py


注:本文中的twython.Twython.get_lastfunction_header方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。