class twSource(twBlock): ''' Return the home timeline ''' def __init__(self, twitter_token, twitter_secret, oauth_token, oauth_secret, count = 20, nbrPage = 1, tlInput = []): self.twitter = Twython(twitter_token, twitter_secret, oauth_token, oauth_secret) self.nbrInput = 0 self.nbrOutput = 1 self.count = count self.nbrPage = nbrPage self.timeLine = tlInput def setInput(self,tlInput): self.timeLine = tlInput def __add__(self,Other): ''' Overload the add operator. Mux two twSource if we have two twSource instance ''' if isinstance(Other,twSource): return twMux([self,Other]) else: Other.setInput(self.output) return Other def output(self): outputTl = self.timeLine for i in range(self.nbrPage): tl = self.twitter.getHomeTimeline(count=self.count, page=i) outputTl += tl return outputTl
def twitter_timeline(request): user = request.user.get_profile() twitter = Twython( twitter_token = CONSUMER_KEY, twitter_secret = CONSUMER_SECRET, oauth_token = user.oauth_token, oauth_token_secret = user.oauth_secret ) my_tweets = twitter.getHomeTimeline() print my_tweets return render_to_response('tweets.html', {'tweets': my_tweets})
def user_timeline(request): """ An example view with Twython/OAuth hooks/calls to fetch data about the user in question. Pretty self explanatory if you read through it... """ user = request.user.twitterprofile twitter = Twython(twitter_token=settings.TWITTER_KEY, twitter_secret=settings.TWITTER_SECRET, oauth_token=user.oauth_token, oauth_token_secret=user.oauth_secret) user_tweets = twitter.getHomeTimeline() return render_to_response('tweets.html', {'tweets': user_tweets})
def user_timeline(request): """ An example view with Twython/OAuth hooks/calls to fetch data about the user in question. Pretty self explanatory if you read through it... """ user = request.user.twitterprofile twitter = Twython( twitter_token = settings.TWITTER_KEY, twitter_secret = settings.TWITTER_SECRET, oauth_token = user.oauth_token, oauth_token_secret = user.oauth_secret ) user_tweets = twitter.getHomeTimeline() return render_to_response('tweets.html', {'tweets': user_tweets})
def index(): screen_name = session.get('screen_name') if screen_name != None: token = session.get('request_token') oauth_token = token[0] oauth_token_secret = token[1] entry = {} t = Twython(app_key=app_key, app_secret=app_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) tweets = t.getHomeTimeline(count=200) return render_template('index.html', tweets=tweets) else: return render_template('index.html')
def get(self, request): if('authorization_token' not in request.session.keys()): twitter_link = self.link_to_twitter(request) context = { 'body': 'Hello Dan', 'twitter_link': twitter_link, } template = "home.html" return render(request, template, context) # else oauth_token = request.session['authorization_token'] oauth_token_secret = request.session['authorization_token_secret'] t2 = Twython(settings.APP_KEY, settings.APP_SECRET, oauth_token, oauth_token_secret) home_timeline = t2.getHomeTimeline() context = { 'auth_tokens': {'oauth_token': oauth_token, 'oauth_token_secret': oauth_token_secret}, 'home_timeline': home_timeline, } template = "logged_in_success.html" return render(request, template, context)
from twython import Twython from format_timeline import * import os oauth_tokens = open('oauth_tokens','r') app_key = oauth_tokens.readline() app_secret = oauth_tokens.readline() oauth_token = oauth_tokens.readline() oauth_token_secret = oauth_tokens.readline() t = Twython(app_key = app_key.strip('\n'), app_secret = app_secret.strip('\n'), callback_url = 'http://google.com') auth_props = t.get_authentication_tokens() print 'Connect to Twitter via: %s' % auth_props['auth_url'] t = Twython(app_key = app_key.strip('\n'), app_secret = app_secret.strip('\n'), oauth_token = oauth_token.strip('\n'), oauth_token_secret = oauth_token_secret.strip('\n')) homeTimeline = format_timeline(t.getHomeTimeline()) #print homeTimeline #update = raw_input('>' ) t.updateStatus(status = update)
te = datetime.utcnow() - dt days = te.seconds / 60 / 60 / 24 hours = te.seconds / 60 / 60 % 24 mins = te.seconds / 60 % 60 secs = te.seconds % 60 retstr = '' if days > 0: retstr = str(days) + " days " elif hours > 0: retstr = str(hours) + " hours " elif mins > 0: retstr = str(mins) + " minutes " else: retstr = str(secs) + " seconds " retstr = retstr + "ago." return retstr timeline = t.getHomeTimeline() def debug(x): print '-------------------------------------------' for i in range(0, x): name = uToString(timeline[i][u'user'][u'name']) dt = uToString(timeline[i][u'created_at']) te = timeElapsed(dt) text = uToString(timeline[i][u'text']) print name + ': ' + te print text print '-------------------------------------------' time.sleep(2)
class Tweeterator(object): """Iterator over the entries in a user's twitter home timeline. This uses the Twython interface to the twitter API to get the most recent tweets from your home screen and feed them out as an iterator. Additionally, we use some simple disk-based persistence to store the tweet ids in a file. This way, when you rerun this code, you won't keep getting the same tweets from the top of your feed. """ def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret, tweet_id_fn): """Create the object Parameters ---------- app_key : str app_secret : str oauth_token : str oauth_token_secret : str You need to get these to connect to the twitter API tweed_id_fn : str Filename for the flat text file that's going to hold the ids of the tweets that have been dispensed. """ self.t = Twython(app_key=app_key, app_secret=app_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) self.tweet_id_fn = tweet_id_fn self.seen_ids = [] self.buffer = [] if os.path.exists(self.tweet_id_fn): self.seen_ids = np.loadtxt(self.tweet_id_fn, dtype=int, ndmin=1).tolist() def pull(self, count=20): """Fetch some tweets The iterator will invoke this method automatically if you ask for the next tweet and it doesn't have any available, but for efficiency if you know exactly how many you want, you can 'preload' the buffer by asking for the right amount Parameters ---------- count : int How many to fetch """ min_id = None if len(self.seen_ids) > 0: min_id = min(self.seen_ids) - 1 buf = self.t.getHomeTimeline(count=count, include_rts=False, max_id=min_id) if len(buf) == 0: raise RuntimeError( 'Zero tweets sucessfully pulled from twitter API. :(') # add new tweets to old buffer self.buffer.extend([{ 'id': b['id'], 'text': sanitize(b['text']) } for b in buf]) logging.info('pulled %d tweets', count) def __iter__(self): """Part of the iterator API""" return self def next(self): """Get the next tweet Returns ------- text : str The text of the tweet, after being sanitized """ if len(self.buffer) <= 0: self.pull() tweet = self.buffer.pop(0) self.seen_ids.append(tweet['id']) with open(self.tweet_id_fn, 'a') as f: print >> f, tweet['id'] return tweet['text']
class Tweeterator(object): """Iterator over the entries in a user's twitter home timeline. This uses the Twython interface to the twitter API to get the most recent tweets from your home screen and feed them out as an iterator. Additionally, we use some simple disk-based persistence to store the tweet ids in a file. This way, when you rerun this code, you won't keep getting the same tweets from the top of your feed. """ def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret, tweet_id_fn): """Create the object Parameters ---------- app_key : str app_secret : str oauth_token : str oauth_token_secret : str You need to get these to connect to the twitter API tweed_id_fn : str Filename for the flat text file that's going to hold the ids of the tweets that have been dispensed. """ self.t = Twython(app_key=app_key, app_secret=app_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) self.tweet_id_fn = tweet_id_fn self.seen_ids = [] self.buffer = [] if os.path.exists(self.tweet_id_fn): self.seen_ids = np.loadtxt(self.tweet_id_fn, dtype=int, ndmin=1).tolist() def pull(self, count=20): """Fetch some tweets The iterator will invoke this method automatically if you ask for the next tweet and it doesn't have any available, but for efficiency if you know exactly how many you want, you can 'preload' the buffer by asking for the right amount Parameters ---------- count : int How many to fetch """ min_id = None if len(self.seen_ids) > 0: min_id = min(self.seen_ids) - 1 buf = self.t.getHomeTimeline(count=count, include_rts=False, max_id=min_id) if len(buf) == 0: raise RuntimeError('Zero tweets sucessfully pulled from twitter API. :(') # add new tweets to old buffer self.buffer.extend([{'id': b['id'], 'text': sanitize(b['text'])} for b in buf]) logging.info('pulled %d tweets', count) def __iter__(self): """Part of the iterator API""" return self def next(self): """Get the next tweet Returns ------- text : str The text of the tweet, after being sanitized """ if len(self.buffer) <= 0: self.pull() tweet = self.buffer.pop(0) self.seen_ids.append(tweet['id']) with open(self.tweet_id_fn, 'a') as f: print >> f, tweet['id'] return tweet['text']