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


Python Twython.get_home_timeline方法代码示例

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


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

示例1: get_timeline

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
	def get_timeline(self, testdata = False):
		if testdata:
			with open('timeline.tweets', 'r') as f:
				try:
					timeline = json.load(f)
				except:
					timeline = {}
					print("empty data file exception")
			f.close()
			return timeline

		accounts = self.get_accounts()
		tweets = {}
		i = 0
		for account in accounts:
			if 'oauth_token' in accounts[account] and 'oauth_token_secret' in accounts[account]:
				api = Twython(config.APP_KEY, config.APP_SECRET, accounts[account]['oauth_token'], accounts[account]['oauth_token_secret'])
				tweetcount = 10;
				if self.since:
					timeline = api.get_home_timeline(count=tweetcount, since_id=self.since)
				else:
					timeline = api.get_home_timeline(count=tweetcount)
				for tweet in timeline:
					tweets.update({i:tweet})
					i += 1
					self.since = tweet['id']
		return timeline
开发者ID:danielvalentin,项目名称:omnify,代码行数:29,代码来源:Twitter.py

示例2: get

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
    def get(self):
        tweets = Tweet.query.order_by(Tweet.tweetId.asc()).limit(1).all()
        oldest = tweets[0] if len(tweets) > 0 else None
        twitter = Twython(s.CONSUMER_KEY, s.CONSUMER_SECRET, 
                          s.ACCESS_TOKEN, s.ACCESS_TOKEN_SECRET)
        data = []
        try:
            if oldest:
                logging.info('\n\nOldest tweetId = {0}\n\n'.format(oldest.tweetId))
                data = twitter.get_home_timeline(count=50, max_id=oldest.tweetId)
            else:
                data = twitter.get_home_timeline(count=200)
        except TwythonError as e:
            logging.error('{0}'.format(e))
        else:
            logging.info(str(data))
            for tweet in data:
                if len(tweet.get('entities').get('urls')) > 0:
                    logging.info("\n\nFound urls!\n\n")
                    process_link(tweet, s.USER_ID)
                else:
                    logging.info("\n\nNo urls :(\n\n")

                
            return "OK"
开发者ID:c11z,项目名称:sqrl-server,代码行数:27,代码来源:api.py

示例3: Questions

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [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

示例4: tweet_tack

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def tweet_tack(request):
        if not 'tack' in request.POST or not request.POST['tack']:
                errors.append('could not locate tack')
        this_tack=Tack.objects.get(pk=request.POST['tack'])
        this_user = this_tack.author
        APP_KEY = "f0wDo5a57mSLYIuaIU4nZA"
        APP_SECRET = "XKgYeEng2G1qhVNhH3xae4r5LbDzcGD0QzRQp7nc"
        twitter = Twython(APP_KEY, APP_SECRET ,this_user.oauth_token, this_user.oauth_secret)
        twitter.verify_credentials()
        twitter.get_home_timeline()
        if not this_tack.image:
                twitter.update_status(status=this_tack.description)
        else:
                photo = this_tack.image.file
                twitter.update_status_with_media(status=this_tack.description, media=photo)
        return render(request, 'tackd/corkboard_template.html', {})
开发者ID:thedrick,项目名称:HerokuTackd,代码行数:18,代码来源:tackd_twitter.py

示例5: get_tweets_per_user

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def get_tweets_per_user(self, user_id):
    user = User.query.get(user_id)
    if not user or not user.twitter_authorized:
        logger.info('User number {} did not authorize twitter (or does not exist) not fetching any tweets'.format(user_id))
        return
    tweets = []
    try:
        twitter_auth = TwitterAuth.query.filter_by(user_id=user_id).first()
        twitter = Twython(current_app.config['TWITTER_API_KEY'],current_app.config['TWITTER_API_SECRET'],
                          twitter_auth.oauth_token, twitter_auth.oauth_token_secret)
        tweets = twitter.get_home_timeline(count=200, tweet_mode='extended')
    except:
        logger.error('There was an error fetching  twitter timeline from user {}'.format(user_id))

    posts_added = 0
    commits_failed = 0
    commits_succeeded = 0
    for tweet in tweets:
        result = _add_post(user, tweet, 'twitter')
        posts_added += result['added_new']
        commits_succeeded += result['success']
        commits_failed += not result['success']

    logger.info('Done getting tweets for user {}, total {} tweets added to db. {} commits succeeded. '
               '{} commits failed.'.format(user_id, posts_added, commits_succeeded, commits_failed))
开发者ID:Dragonriver1990,项目名称:gobo,代码行数:27,代码来源:tasks.py

示例6: user_timeline

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def user_timeline(request):
    """An example view with Twython/OAuth hooks/calls to fetch data about the user in question."""
    user = request.user.twitterprofile
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET,
                      user.oauth_token, user.oauth_secret)
    user_tweets = twitter.get_home_timeline()
    return render_to_response('tweets.html', {'tweets': user_tweets})
开发者ID:Mondego,项目名称:pyreco,代码行数:9,代码来源:allPythonContent.py

示例7: user_timeline

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def user_timeline(request):

    user = request.user.profile
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET,
                      user.oauth_token, user.oauth_secret)
    user_tweets = twitter.get_home_timeline()
    
    return render_to_response('tweets.html', {'tweets': user_tweets})
开发者ID:jparicka,项目名称:twitter-tools,代码行数:10,代码来源:views.py

示例8: wsTwitter_view

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def wsTwitter_view(request):
	APP_KEY = 'IfZu2KyFrUENObWRRb4rEQ'
	APP_SECRET = 'ZOw3Y9BoMpiZaaoqaL1OH3tH3BNHr2YoBQ4IF2JYu4s'
	OAUTH_TOKEN = '56143706-DqNvSdocUyKQsSkk6vweW66vtv9ovSfRDECmfzdk'
	OAUTH_TOKEN_SECRET = 'xZ6sIyxeoKcxcV5OchdjTDXJLXhnzrfu6zf6bUzJg7c'
	twitter = Twython(APP_KEY, APP_SECRET,
                  OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
	tweets = twitter.get_home_timeline()
	return HttpResponse(tweets,mimetype='application/json')
开发者ID:juan2ramos,项目名称:salvo-patria-dj,代码行数:11,代码来源:views.py

示例9: _main

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
    def _main(self):
        APP_KEY = self._get_config_option("APP_KEY")

        APP_SECRET = self._get_config_option("APP_SECRET")

        OAUTH_TOKEN = self._get_config_option("OAUTH_TOKEN")

        OAUTH_TOKEN_SECRET = self._get_config_option("OAUTH_TOKEN_SECRET")

        screen_name = self._get_config_option("screen_name")

        count = self._get_config_option("count")

        twitter = Twython(
            APP_KEY,
            APP_SECRET,
            OAUTH_TOKEN,
            OAUTH_TOKEN_SECRET
            )
        try:
            home_timeline = twitter.get_home_timeline(screenname=screen_name, count=count)

        except TwythonError as e:
            logging.error(e)
            sys.exit(1)

        for tweet in home_timeline:
            # strptime doesn't support timezone info, so we are using dateutils.
            date_object = parser.parse(tweet['created_at'])

            timestamp = OrgFormat.datetime(date_object)
            try:
                # Data is already Unicode, so don't try to re-encode it.
                output = tweet['text']
            except:
               logging.error(sys.exc_info()[0])
               print "Error: ", sys.exc_info()[0]

            data_for_hashing = output + timestamp + output
            properties = OrgProperties(data_for_hashing=data_for_hashing)

            properties.add("name", tweet['user']['name'])
            properties.add("twitter_id", tweet['id'])
            properties.add("contributors", tweet['contributors'])
            properties.add("truncated", tweet['truncated'])
            properties.add("in_reply_to_status_id", tweet['in_reply_to_status_id'])
            properties.add("favorite_count", tweet['favorite_count'])
            properties.add("source", tweet['source'])
            properties.add("retweeted", tweet['retweeted'])
            properties.add("coordinates", tweet['coordinates'])
            properties.add("entities", tweet['entities'])

            self._writer.write_org_subitem(timestamp=timestamp,
                                          output = output,
                                          properties = properties)
开发者ID:andrewjss,项目名称:Memacs,代码行数:57,代码来源:twitter.py

示例10: getHomeTimeline

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
    def getHomeTimeline(count_to_get=800, overwrite=1):
        conn = sqlite3.connect(DBPath)
        cur = conn.cursor()
        cur.execute("PRAGMA foreign_keys = ON;")
        if Util.__checkInterval__(UPDATE_INTERVAL, 'UPDATE'):
            if count_to_get > 800:
                count_to_get = 800

            print('Authorizing application..')
            try:
                if not AuthApp.checkTokenExist(oauthMode=1):
                    AuthApp.authApp()
                twHandler = Twython(AuthApp.getAppKey(), AuthApp.getAppSecret(), AuthApp.getOauthToken(),
                                    AuthApp.getOauthTokenSecret())
            except TwythonError as e:
                print(e.args[0])
                conn.close()
                return -1

            min_id_get = MAX_STATUS_ID
            max_id_get = 0
            total_count_get = 0
            run = 1
            sleep(5.1)

            while count_to_get > 0:
                print(count_to_get)
                print(min_id_get)
                if count_to_get // 200 > 0:
                    this_count = 200
                else:
                    this_count = count_to_get % 200
                try:
                    resultsList = twHandler.get_home_timeline(max_id=min_id_get - 1, count=this_count)
                except TwythonError as e:
                    print(e.args[0])
                    continue


                for results in resultsList:
                    if run == 1:
                        sleep(random.uniform(-0.4, 1.6) + 5.5)
                    min_id_get, max_id_get, total_count_get, run = Crawler.db_write_tweet(results, twHandler, conn, cur, min_id_get, max_id_get, total_count_get, overwrite, update_user=True)
                count_to_get -= total_count_get

                sleep(random.uniform(-0.4, 1.6) + 5.5)

            conn.commit()
        Util.__updateLastTime__(conn, 'UPDATE')
        conn.close()
        return 0
开发者ID:wchen342,项目名称:cratwer,代码行数:53,代码来源:Crawler.py

示例11: PokeyTwit

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
class PokeyTwit():

    def __init__(
            self,
            lib_path=resource_path(resources.__file__,'twit_lib.txt'),
            conf_path='bots.cfg'
            ):

        self.lib_path = lib_path
        self.c = c = PokeyConfig(conf_path, PokeyConfig.encoded, True)

        try:
            print "Initializing twitter bot"
            self.twitter = Twython(c.APP_KEY, c.APP_SECRET,
                                    c.OAUTH, c.OAUTH_SECRET)

            print "Verifying credentials"
            self.twitter.verify_credentials()

            while True:
                msg = self.get_message().rstrip()
                if len(msg)!=0 and len(msg) < 140:
                    break

            print msg
            print "length: {}".format(len(msg))
            self.twitter.update_status(status=msg)
            msg=''
            self.exit_status=0

        except TwythonError:
            self.exit_status=1

    def get_timeline(self):
        try:
            self.timeline = self.twitter.get_home_timeline()
        except:
            raise

    def get_message(self):
        # If the lib_path is passed, use this path (does no path validation)
        if self.lib_path is None:
            # Otherwise, inspect the directory of the calling script and pull from that path
            self.lib_path = resource_path(inspect.stack()[-1][1],"twit_lib.txt")
        with open(self.lib_path, 'rb') as txt:
            twit_list = txt.readlines()

        msg = twit_list[random.randint(0,len(twit_list)-1)]
        return msg
开发者ID:wnormandin,项目名称:social_media_bots,代码行数:51,代码来源:pokeybots.py

示例12: timelineback

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def timelineback(request):

	if request.is_ajax():
		twitter 	= Twython( KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"] )
		home_timeline_back = twitter.get_home_timeline( max_id = request.session['max_id'] , count = 10 )
		request.session['max_id'] =  home_timeline_back[ len( home_timeline_back ) -1 ]['id']  

		#elimino la primera
		del home_timeline_back[0]

		return HttpResponse(
			json.dumps({'timeline': home_timeline_back}),
			content_type = 'application/json; charset=utf8')

	return HttpResponseRedirect('/')
开发者ID:calosth,项目名称:TrackTweet,代码行数:17,代码来源:views.py

示例13: get_feed_twitter

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def get_feed_twitter():
    feed_name = 'Twitter'
    if debug:
        print 'TWITTER_APP_TOKEN:' + TWITTER_APP_TOKEN
        print 'TWITTER_APP_SECRET:' + TWITTER_APP_SECRET
        print 'TWITTER_ACCESS_TOKEN: ' + TWITTER_ACCESS_TOKEN
        print 'TWITTER_ACCESS_SECRET: ' + TWITTER_ACCESS_SECRET

    twitter = Twython(TWITTER_APP_TOKEN, TWITTER_APP_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET)
    
    searchResults = twitter.get_home_timeline()

    if debug:
        for item in searchResults:
            print item
开发者ID:froi,项目名称:flask_twitter_appdotnet_example,代码行数:17,代码来源:twitter_appNet_test.py

示例14: get_feed_twitter

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def get_feed_twitter():
    
    if debug:
        print 'Feed Name: Twitter'
        print 'TWITTER_APP_TOKEN:' + TWITTER_APP_TOKEN
        print 'TWITTER_APP_SECRET:' + TWITTER_APP_SECRET
        print 'TWITTER_ACCESS_TOKEN: ' + TWITTER_ACCESS_TOKEN
        print 'TWITTER_ACCESS_SECRET: ' + TWITTER_ACCESS_SECRET

    twitter = Twython(TWITTER_APP_TOKEN, TWITTER_APP_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET)
    streamResults = twitter.get_home_timeline()

    if debug:
        for item in streamResults:
            print json.dumps(item, indent=4, separators=[',', ':'])

    return streamResults
开发者ID:froi,项目名称:flask_twitter_appdotnet_example,代码行数:19,代码来源:feeds.py

示例15: get_tweets

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_home_timeline [as 别名]
def get_tweets(request):

	if request.is_ajax():
		t = Twython( KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"])
		home_timeline = t.get_home_timeline( since_id = request.session['ultimo_id']	)	
		request.session['ultimo_id'] = int ( home_timeline[0]['id'] -4 )

		#Validar si hay nuevos tweets
		if len(home_timeline) > 1:
			home_timeline.reverse()	
			del home_timeline[0]
		else:
			home_timeline = ''

		return HttpResponse(
			json.dumps({'timeline': home_timeline}),
			content_type = 'application/json; charset=utf8')
	return HttpResponseRedirect('/')
开发者ID:calosth,项目名称:TrackTweet,代码行数:20,代码来源:views.py


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