2 Colorful user's timeline stream
5 from __future__
import print_function
6 from multiprocessing
import Process
14 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
15 from twitter
.api
import *
16 from twitter
.oauth
import OAuth
, read_token_file
17 from twitter
.oauth_dance
import oauth_dance
18 from twitter
.util
import printNicely
19 from dateutil
import parser
28 def draw(t
, keyword
=None):
35 screen_name
= t
['user']['screen_name']
36 name
= t
['user']['name']
37 created_at
= t
['created_at']
38 date
= parser
.parse(created_at
)
39 time
= date
.strftime('%Y/%m/%d %H:%M:%S')
41 res
= db
.tweet_query(tid
)
44 res
= db
.tweet_query(tid
)
45 rid
= res
[0].rainbow_id
48 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
49 meta
= grey('[' + time
+ '] [id=' + str(rid
) + ']')
52 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
53 # Highlight screen_name
54 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
56 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
57 # Highlight search keyword
60 lambda x
: on_yellow(x
) if
61 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
65 tweet
= ' '.join(tweet
)
68 line1
= u
"{u:>{uw}}:".format(
72 line2
= u
"{c:>{cw}}".format(
84 def parse_arguments():
88 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
92 help='Timeout for the stream (seconds).')
95 '--heartbeat-timeout',
96 help='Set heartbeat timeout.',
102 help='Set stream to non-blocking.')
106 help='Search the stream for specific text.')
107 return parser
.parse_args()
112 Authenticate with Twitter OAuth
114 # When using rainbow stream you must authorize.
115 twitter_credential
= os
.environ
.get(
119 '')) + os
.sep
+ '.rainbow_oauth'
120 if not os
.path
.exists(twitter_credential
):
121 oauth_dance("Rainbow Stream",
125 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
133 def get_decorated_name():
135 Beginning of every line
137 t
= Twitter(auth
=authen())
138 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
139 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
146 t
= Twitter(auth
=authen())
147 count
= HOME_TWEET_NUM
148 if g
['stuff'].isdigit():
150 for tweet
in reversed(t
.statuses
.home_timeline(count
=count
)):
158 t
= Twitter(auth
=authen())
159 user
= g
['stuff'].split()[0]
162 count
= int(g
['stuff'].split()[1])
164 count
= HOME_TWEET_NUM
165 for tweet
in reversed(t
.statuses
.user_timeline(count
=count
, screen_name
=user
[1:])):
168 print(red('A name should begin with a \'@\''))
169 sys
.stdout
.write(g
['decorated_name'])
176 t
= Twitter(auth
=authen())
177 t
.statuses
.update(status
=g
['stuff'])
184 t
= Twitter(auth
=authen())
186 id = int(g
['stuff'].split()[0])
187 tid
= db
.rainbow_query(id)[0].tweet_id
188 t
.statuses
.retweet(id=tid
,include_entities
=False,trim_user
=True)
190 print(red('Sorry I can\'t retweet for you.'))
191 sys
.stdout
.write(g
['decorated_name'])
198 t
= Twitter(auth
=authen())
200 id = int(g
['stuff'].split()[0])
201 tid
= db
.rainbow_query(id)[0].tweet_id
202 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
203 status
= ' '.join(g
['stuff'].split()[1:])
204 status
= '@' + user
+ ' ' + status
.decode('utf-8')
205 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
207 print(red('Sorry I can\'t understand.'))
208 sys
.stdout
.write(g
['decorated_name'])
215 t
= Twitter(auth
=authen())
217 id = int(g
['stuff'].split()[0])
218 tid
= db
.rainbow_query(id)[0].tweet_id
219 t
.statuses
.destroy(id=tid
)
220 print(green('Okay it\'s gone.'))
222 print(red('Sorry I can\'t delete this tweet for you.'))
223 sys
.stdout
.write(g
['decorated_name'])
230 t
= Twitter(auth
=authen())
231 h
, w
= os
.popen('stty size', 'r').read().split()
232 if g
['stuff'][0] == '#':
233 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
234 printNicely(grey('*' * int(w
) + '\n'))
235 print('Newest', SEARCH_MAX_RECORD
, 'tweet: \n')
237 draw(t
=rel
[i
], keyword
=g
['stuff'].strip())
238 printNicely(grey('*' * int(w
) + '\n'))
240 print(red('A keyword should be a hashtag (like \'#AKB48\')'))
241 sys
.stdout
.write(g
['decorated_name'])
246 List of friend (following)
248 t
= Twitter(auth
=authen())
249 g
['friends'] = t
.friends
.ids()['ids']
250 for i
in g
['friends']:
251 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
252 user
= cycle_color('@' + screen_name
)
261 t
= Twitter(auth
=authen())
262 g
['followers'] = t
.followers
.ids()['ids']
263 for i
in g
['followers']:
264 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
265 user
= cycle_color('@' + screen_name
)
275 Hi boss! I'm ready to serve you right now!
276 ----------------------------------------------------
277 "home" will show your timeline. "home 7" will show 7 tweet.
278 "view @bob" will show your friend @bob's home.
279 "t oops" will tweet "oops" immediately.
280 "rt 12345" will retweet to tweet with id "12345".
281 "rep 12345 oops" will reply "oops" to tweet with id "12345".
282 "del 12345" will delete tweet with id "12345".
283 "s #AKB48" will search for "AKB48" and return 5 newest tweet.
284 "fr" will list out your following people.
285 "fl" will list out your followers.
286 "h" will show this help again.
287 "c" will clear the terminal.
289 ----------------------------------------------------
290 Have fun and hang tight!
293 sys
.stdout
.write(g
['decorated_name'])
307 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
328 }.get(cmd
, lambda: sys
.stdout
.write(g
['decorated_name']))
333 Listen to user's input
335 for line
in iter(stdin
.readline
, ''):
337 cmd
= line
.split()[0]
340 # Save cmd to global variable and call process
341 g
['stuff'] = ' '.join(line
.split()[1:])
350 args
= parse_arguments()
354 # These arguments are optional:
356 timeout
=args
.timeout
,
357 block
=not args
.no_block
,
358 heartbeat_timeout
=args
.heartbeat_timeout
)
362 if args
.track_keywords
:
363 query_args
['track'] = args
.track_keywords
366 stream
= TwitterStream(
370 tweet_iter
= stream
.user(**query_args
)
372 # Iterate over the sample stream.
373 for tweet
in tweet_iter
:
375 printNicely("-- None --")
376 elif tweet
is Timeout
:
377 printNicely("-- Timeout --")
378 elif tweet
is HeartbeatTimeout
:
379 printNicely("-- Heartbeat Timeout --")
380 elif tweet
is Hangup
:
381 printNicely("-- Hangup --")
382 elif tweet
.get('text'):
392 p
= Process(target
=stream
)
394 g
['stream_pid'] = p
.pid