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


Python Twython.getUserTimeline方法代码示例

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


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

示例1: verTwitter

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def verTwitter(request):
    twitter = Twython()
    recorretwiter = []
    for page in range(1, 4):
        user_timeline = twitter.getUserTimeline(screen_name="cvander", count="200", page=page, include_entities = "true")
        for t in user_timeline:
            if t['text'].find("http") >= 0:
                recorretwiter.append({
                    'text': t['text'],
                    'user': "cvander",
                    'retwits': t['retweet_count'],
                    'url': t['entities']['urls'][0]['expanded_url'],
                    'fecha': t['created_at']})
        user_timeline2 = twitter.getUserTimeline(screen_name="freddier", count="200", page=page, include_entities = "true")
        for t2 in user_timeline2:
            if t2['text'].find("http") >= 0:
                recorretwiter.append({
                    'text': t2['text'],
                    'user': "freddier",
                    'retwits': t2['retweet_count'],
                    'url': t2['entities']['urls'][0]['expanded_url'],
                    'fecha': t2['created_at']})

    t = get_template('twitter.html')
    c = RequestContext(request, {'user_timeline': recorretwiter})
    html = t.render(c)
    return HttpResponse(html)
开发者ID:fitsto,项目名称:TrabajoConTwitter,代码行数:29,代码来源:views.py

示例2: agent

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

	keystone = client.Client(token=ca.creds['token'], tenant_id=ca.creds['tenantId'],
							auth_url=ca.creds['identity_url'])
	
	object_store_catalog = keystone.service_catalog.get_endpoints()['object-store']
	
	region_endpoints = None
	
	for endpoints in object_store_catalog:
		if endpoints['region'] == ca.conf['region']:
			region_endpoints = endpoints
	
	if not region_endpoints:
		ca.log_fail("Failing, region not found in endpoint list.")
		exit()

	t = Twython()
	
	
	# Figure out what files already exist, and what our latest tweet is.
	
	files = []
	
	try:
		(headers,files) = swiftclient.get_container(region_endpoints['publicURL'],ca.creds['token'],
												ca.conf['container'],full_listing=True, prefix=ca.conf['path'])
	
	except swiftclient.client.ClientException:
		pass
	
	files = sorted(files, key=itemgetter('name')) 

	last_tweet = 0
	last_file = ''
	tweet_list = []
	
	if files:
		(headers,last_file) = swiftclient.get_object(region_endpoints['publicURL'],ca.creds['token'],
												ca.conf['container'],files[-1]['name'])
		headers = swiftclient.head_object(region_endpoints['publicURL'],ca.creds['token'],
												ca.conf['container'],files[-1]['name'])
		last_tweet = headers.get('x-object-meta-last-tweet-id',0)
		tweet_list = json.loads(last_file)
	
	# Grab our tweet list (tweets since last tweet up to 3200), optimized for
	# fewest requests.

	try:
		if last_tweet:
			tweets = t.getUserTimeline(screen_name=ca.conf['screen_name'], count=200, since_id=last_tweet, include_rts=True)
		else:
			tweets = t.getUserTimeline(screen_name=ca.conf['screen_name'], count=200, include_rts=True)

	except TwythonError, e:
		ca.log_fail("Error accessing twitter stream.  User not found or twitter down.")
		exit()
开发者ID:hpcloud,项目名称:CloudAgents,代码行数:59,代码来源:twitter-backup.py

示例3: listUrl

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def listUrl(request):
    twitter = Twython()
    listaTwitter = []
    contador = 0
    for page in range(1, 4):

        user_timeline = twitter.getUserTimeline(screen_name="cvander", count="200", page=page, include_entities = "true")
        for t in user_timeline:
            if t['text'].find("http") >= 0:
                if contador > 0:
                    contadorIgualdad = 0
                    for posicion in range(0, len(listaTwitter)):
                        if listaTwitter[posicion]['url'] == t['entities']['urls'][0]['expanded_url']:
                            contadorIgualdad += 1
                            auxPosicion = posicion

                    if contadorIgualdad > 0:
                        listaTwitter[auxPosicion]['retwits'] += t['retweet_count']
                    else:
                        listaTwitter.append({
                            'retwits': t['retweet_count'],
                            'url': t['entities']['urls'][0]['expanded_url']})
                else:
                    listaTwitter.append({
                        'retwits': t['retweet_count'],
                        'url': t['entities']['urls'][0]['expanded_url']})
                    contador += 1

        user_timeline2 = twitter.getUserTimeline(screen_name="freddier", count="200", page=page, include_entities = "true")
        for t2 in user_timeline2:
            if t2['text'].find("http") >= 0:
                if contador > 0:
                    contadorIgualdad = 0
                    for posicion in range(0, len(listaTwitter)):
                        if listaTwitter[posicion]['url'] == t2['entities']['urls'][0]['expanded_url']:
                            contadorIgualdad += 1
                            auxPosicion = posicion

                    if contadorIgualdad > 0:
                        listaTwitter[auxPosicion]['retwits'] += t2['retweet_count']
                    else:
                        listaTwitter.append({
                            'retwits': t2['retweet_count'],
                            'url': t2['entities']['urls'][0]['expanded_url']})
                else:
                    listaTwitter.append({
                        'retwits': t2['retweet_count'],
                        'url': t2['entities']['urls'][0]['expanded_url']})
                    contador += 1
    listaOrdenada = quicksort(listaTwitter, 0, len(listaTwitter) - 1, 'desc')
    #assert False
    t = get_template('lista_url.html')
    c = RequestContext(request, {'twits': listaOrdenada})
    html = t.render(c)
    return HttpResponse(html)
开发者ID:fitsto,项目名称:TrabajoConTwitter,代码行数:57,代码来源:views.py

示例4: handle

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
    def handle(self, *args, **options):
        twython = Twython(
            app_key=settings.TWITTER_APP_KEY,
            app_secret=settings.TWITTER_APP_SECRET,
            oauth_token=settings.TWITTER_OAUTH_TOKEN,
            oauth_token_secret=settings.TWITTER_OAUTH_SECRET,
        )

        legs = Officials.objects.filter(active="True").exclude(twitter="").only("legid", "fullname", "twitter")
        print "Downloading new tweets for legislators."
        for counter, o in enumerate(legs):
            try:
                timeline = twython.getUserTimeline(screen_name=o.twitter)[:30]
            except:
                print "Could not download tweets for {0} (id: {1}, handle: {2})".format(o.fullname, o.legid, o.twitter)
                continue
            for t in timeline:
                if OfficialTweets.objects.filter(tweet_id=t["id_str"]).exists():
                    continue
                else:

                    new_tweet = OfficialTweets.objects.create(
                        legid=o.legid, tweet=t["text"], tweet_id=t["id_str"], timestamp=dp.parse(t["created_at"])
                    )
                    new_tweet.save()

        print "Downloading Twitter Oembed HTML for tweets"
        for tweet in OfficialTweets.objects.filter(oembed="").order_by("-timestamp"):
            oembed_dict = twython.getOembedTweet(id=tweet.tweet_id)
            tweet.oembed = oembed_dict["html"]
            tweet.save()
开发者ID:staterepme,项目名称:State-Gov-Tracker,代码行数:33,代码来源:update_tweets.py

示例5: parseTweets

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def parseTweets(username, hashtag):
	try:
		from twython import Twython
		twitter = Twython()
		if(username is not None):
			tweets = twitter.getUserTimeline( screen_name = username )
			for t in tweets:
				it = Item(title=texto2Unicode(t["text"]),
					desc=texto2Unicode(t["text"]),
					author=texto2Unicode(t["user"]["screen_name"]),
					category=texto2Unicode("twitter"),
					link="",
					img=texto2Unicode(t["user"]["profile_image_url_https"]),
					pub_date=texto2Unicode(t["created_at"]))
				checkAndSaveEntry(it)
		if(hashtag is not None):
			twhash = twitter.search(q = hashtag)
			for t in twhash["results"]:
				it = Item(title=texto2Unicode(t["text"]),
					desc=texto2Unicode(t["text"]),
					author=texto2Unicode(t["from_user"]),
					category=texto2Unicode("twitter"),
					link="",
					img=texto2Unicode(t["profile_image_url_https"]),
					pub_date=texto2Unicode(t["created_at"]))
				checkAndSaveEntry(it)
	except Exception, e:
		print("ExceptionTW: %s" %e)
		return 0
开发者ID:jnoga,项目名称:iTxoko-backend,代码行数:31,代码来源:utils.py

示例6: handle

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
    def handle(self, *args, **options):
        api = Twython()
        cached_statuses = {}
        cached_user_since_ids = {}
        cached_user_max_ids = {}
        statuses = (Status.objects.filter(text__isnull=True) |
                    Status.objects.filter(user__isnull=True) |
                    Status.objects.filter(created_at__isnull=True))
        self.stdout.write("Broken statuses: {0}\n".format(len(statuses)))
        for s in statuses:
            if s.id in cached_statuses: 
                status = cached_statuses[s.id]
            else:
                try: status = Status.construct_from_dict(api.showStatus(id=s.id))
                except APILimit:
                    self.stdout.write('Rate limit exceeded\n')
                    break
                except TwythonError:
                    continue
                try: max_id = cached_user_max_ids[status.user.id]
                except KeyError: max_id = None
                try: 
                    userstatuses = Status.construct_from_dicts(
                        api.getUserTimeline(user_id=status.user.id, 
                                            count=200, max_id=max_id))
                    for us in userstatuses:
                        cached_statuses[us.id] = us
                    cached_user_since_ids[status.user.id] = min([s.id for s in userstatuses])
                except ValueError: pass
            status.save()

            self.stdout.write('Repaired Status id {0}\n'.format(status.id))
开发者ID:yesimon,项目名称:classiwhale,代码行数:34,代码来源:repair_statuses.py

示例7: ajax_user_timeline

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def ajax_user_timeline(request):
    if not request.user.is_authenticated() or 'twitter_tokens' not in request.session:
        return HttpResponse("")

    results = {'success': 'False'}
    if request.method != u'GET':
        return HttpResponseBadRequest('Must be GET request')
    if not request.GET.has_key(u'screenname'):
        return HttpResponseBadRequest('screenname missing')
    if not request.GET.has_key(u'max_id'):
        return HttpResponseBadRequest('start id missing')
    if not request.GET.has_key(u'page'):
        return HttpResponseBadRequest('page number missing')
    screenname = request.GET[u'screenname']
    max_id = request.GET[u'max_id']
    page = request.GET[u'page']

    if 'twitter_tokens' in request.session:
        twitter_tokens = request.session['twitter_tokens']
        api = get_authorized_twython(twitter_tokens)
    else: # Get public api if no authentication possible
        api = Twython()

    results['statuses'] = api.getUserTimeline(screen_name=screenname, max_id=max_id, page=page)
    t = get_template('twitter/status_list.html')
    results['success'] = 'True'
    html = t.render(RequestContext(request, results))
    return HttpResponse(html)
开发者ID:yesimon,项目名称:classiwhale,代码行数:30,代码来源:views.py

示例8: userTL

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def userTL(user=''):
	twitter = Twython()
	user_timeline = twitter.getUserTimeline(screen_name=user, count='200')
	all_tweets=''
	for tweet in user_timeline:
		text = tweet['text'].encode('ascii', 'replace')
		all_tweets +=' ' + text
	return tokenize(all_tweets)
开发者ID:alvarofaundez,项目名称:SmartboxTv,代码行数:10,代码来源:server.py

示例9: get_tweets_by_user

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def get_tweets_by_user(request, username):
    oauth_token = request.session['authorization_token']
    oauth_token_secret = request.session['authorization_token_secret']

    twython = Twython(settings.APP_KEY, settings.APP_SECRET, oauth_token, oauth_token_secret)

    raw_tweets = twython.getUserTimeline(screen_name=username, count=20)

    return save_tweets(raw_tweets)
开发者ID:ajyang818,项目名称:pylon,代码行数:11,代码来源:utils.py

示例10: get_opta_tweet

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def get_opta_tweet():
	print "getting latest opta tweets"
	print "Does tweet dict exist?"
	print r.exists('opta_tweet')
	if not r.exists('opta_tweet'):
		t = Twython(app_key='nfxOwOrDiKuyG4AQzT3iSw',
		            app_secret='6ogL1EZ7qNDmwvgz7zSCEe8b9AZ9pyjtEMB2ebwUWQs',
		            oauth_token='32849299-qCdJK4y9uaDw03NWeVWuInydqYospWCSCQOfvxhjc',
		            oauth_token_secret='ReLXHkrwrKIdyqSAbjAOMXbJ8CmsNZS9dvvYJ5q4')
		auth_tokens = t.get_authorized_tokens()
		opta_timeline = t.getUserTimeline(screen_name="optajoe",count="50")
		for tweet in opta_timeline:
			text = unicodedata.normalize('NFKD', tweet['text']).encode('ascii','ignore')
			tweet_url = "http://twitter.com/Optajoe/status/%s"%tweet['id_str']
			r.hset('opta_tweet',tweet_url,text)
			r.expire('opta_tweet', 86400)
开发者ID:sylg,项目名称:liveFPL,代码行数:18,代码来源:tasks.py

示例11: GetTweets

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def GetTweets(file, USERS=None, COUNT_DEFAULT=50, COUNT={}, **kwargs):
    """
    COUNT_DEFAULT is the default number of tweets to get for each
    user, which falls back on 50. COUNT is a dictionary with with keys
    as tweeters and value the number of tweets to get. Falls back on
    COUNT_DEFAULT
    """
    api = Twython()
    t = {'statuses': {}, 'users': {}}
    for u in USERS:
        try: n = COUNT[u]
        except: n = COUNT_DEFAULT
        try:
            user=api.showUser(u)
            timeline = api.getUserTimeline(id=u, count=n)
            t['users'][user['id']] = user
            t['statuses'][user['id']] = timeline
        except:
            print "User: '{0}' has protected tweets".format(u)
    pickle.dump(t, file)
开发者ID:yesimon,项目名称:classiwhale,代码行数:22,代码来源:import_tweets.py

示例12: gnius

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import getUserTimeline [as 别名]
def gnius(user='rafalopezpo'):
	nltk.data.load('tokenizers/punkt/spanish.pickle')
	stops_es=stopwords.words('spanish')
	stops_en=stopwords.words('english')

	twitter = Twython()
	#user=raw_input('user: ')
	print '\nUser Description\n\n'
	lookup = twitter.lookupUser(screen_name=user)
	lookup = lookup[0]['description'].encode('ascii', 'replace')
	lookup_t = nltk.word_tokenize(lookup)
	stops_custom = ['http']
	cleaned_lookup = [word.lower() for word in lookup_t if word not in stops_es and word not in stops_custom and word not in stops_en and word.isalpha() and len(word)>2]
	print cleaned_lookup
	print '\nUser Timeline\n\n'
	# We won't authenticate for this, but sometimes it's necessary
	user_timeline = twitter.getUserTimeline(screen_name=user, count='200')
	all_tweets=''
	for tweet in user_timeline:
		text = tweet['text'].encode('ascii', 'replace')
		all_tweets +=' ' + text 
	#print '\nTexto\n\n%s' % (all_tweets)
	all_tweets_t = nltk.word_tokenize(all_tweets)
	cleaned_tweets = [word.lower() for word in all_tweets_t if word not in stops_es and word not in stops_custom and word not in stops_en and word.isalpha() and len(word)>2]
	print '\nTokens\n'
	print cleaned_tweets
	c = Counter(cleaned_tweets)
	print '\nCommon terms\n'
	t=c.most_common(5)
	d={}
	for x in t:
		d[]
	j=json.dumps(d)
	print j
	#t=nltk.Text(cleaned_tweets)
	#t=({'user':user})
	return j
开发者ID:alvarofaundez,项目名称:SmartboxTv,代码行数:39,代码来源:nlp.py

示例13: Twython

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

# We won't authenticate for this, but sometimes it's necessary
twitter = Twython()
user_timeline = twitter.getUserTimeline(screen_name="ryanmcgrath")

print user_timeline
开发者ID:0077cc,项目名称:twython,代码行数:9,代码来源:get_user_timeline.py

示例14: __init__

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

#.........这里部分代码省略.........
                    if self.t.get_lastfunction_header('status') != '200 OK':
                        return None

                os.system('rm -rf ' + path)
                # Return the id of the last DM posted.
                return DirectMessageResponse(id = result['id'])
            else:
                status = '@' + req.user + ' ' + req.text
                # Many images ---> postimage.org
                if len(req.images) != 0:
                    status +=  upload( req.images )

            for tweet in self.split_tweet( status ):
                result = self.t.updateStatus( status = tweet )
                if self.t.get_lastfunction_header('status') != '200 OK':
                    return None
            # Return the id of the last DM posted.
            return DirectMessageResponse(id = result['id'])

        # CASE 3: If can't.
        else:
            rospy.logwarn("You can't send a direct message to " + req.user)
            return None

    def destroy_cb(self, req):
        result = self.t.destroyDirectMessage( id = req.id )

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

    def user_timeline_cb(self, req):
        result = self.t.getUserTimeline( screen_name = req.user )
        if self.t.get_lastfunction_header('status') != '200 OK':
            return None
        else: 
            msg = self.process_tweets( result )
            if msg:
                return TimelineResponse( tweets = msg )
            else:
                rospy.logwarn(req.user + " has no tweets in its timeline.")
        return TimelineResponse( )

    # Split a long text into 140 chars tweets
    def split_tweet(self, text):
        tweet = ""
        tweets = []

        words =  text.split(' ')
        for word in words:
            if len(tweet + word + " ") > 137:
                tweets.append(tweet.strip() + "...")
                # If tweets is intended to a user, begin all tweets with @user
                if text.startswith('@'):
                    tweet = words[0] + " " + word + " "
                else:
                    tweet = "..."
            else:
                tweet = tweet + word + " "

        tweets.append( tweet.strip() )
        return tweets

    # Upload array of sensor_msgs/Image to postimage.org and return link.
    # Link is shortened if possible.
开发者ID:namimi,项目名称:twitros,代码行数:70,代码来源:twitter.py

示例15: open

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

numTweetsPerQuery = 15

handleToInfo = {}
fin = open('venueID_twitterHandle.txt', 'r')
for line in fin:
    (venueID, twitterHandle, venueName, venueDesc, venueAddr, venueLat, venueLon, numEvents) = line.split('\t')
    handleToInfo[twitterHandle] = {'id': int(venueID), 'twitterHandle': twitterHandle, 'name': venueName, 'description': venueDesc, 'address': venueAddr, 'lat': float(venueLat), 'lon': float(venueLon), 'numEvents': int(numEvents)}

# We won't authenticate for this, but sometimes it's necessary
twitter = Twython()

venues = []
for twitterHandle in handleToInfo.keys():
    user_timeline = twitter.getUserTimeline(screen_name=twitterHandle, rpp=numTweetsPerQuery)
    search_results = twitter.searchTwitter(q=twitterHandle, rpp=numTweetsPerQuery, lang="en")
    venue = handleToInfo[twitterHandle]
    tweetsTimeline = []
    tweetsSearch = []
    for tweet in user_timeline:
        tweetsTimeline.append(tweet)
    for tweet in search_results["results"]:
        tweetsSearch.append(tweet)
    venue['tweetsTimeline'] = tweetsTimeline
    venue['tweetsSearch'] = tweetsSearch
    venues.append(venue)
    
print json.dumps(venues, sort_keys=True)

开发者ID:mudblood007,项目名称:RocData,代码行数:31,代码来源:getUserTimeline.py


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