2 Colorful user's timeline stream
5 from __future__
import print_function
6 from multiprocessing
import Process
15 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
16 from twitter
.api
import *
17 from twitter
.oauth
import OAuth
, read_token_file
18 from twitter
.oauth_dance
import oauth_dance
19 from twitter
.util
import printNicely
20 from dateutil
import parser
28 def draw(t
, keyword
=None):
34 screen_name
= t
['user']['screen_name']
35 name
= t
['user']['name']
36 created_at
= t
['created_at']
37 date
= parser
.parse(created_at
)
38 time
= date
.strftime('%Y/%m/%d %H:%M:%S')
41 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
42 clock
= grey('[' + time
+ ']')
45 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
46 # Highlight screen_name
47 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
49 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
50 # Highlight search keyword
53 lambda x
: on_yellow(x
) if
54 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
58 tweet
= ' '.join(tweet
)
61 line1
= u
"{u:>{uw}}:".format(
65 line2
= u
"{c:>{cw}}".format(
78 def parse_arguments():
82 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
86 help='Timeout for the stream (seconds).')
89 '--heartbeat-timeout',
90 help='Set heartbeat timeout.',
96 help='Set stream to non-blocking.')
100 help='Search the stream for specific text.')
101 return parser
.parse_args()
106 authenticate with Twitter OAuth
108 # When using rainbow stream you must authorize.
109 twitter_credential
= os
.environ
.get(
113 '')) + os
.sep
+ '.rainbow_oauth'
114 if not os
.path
.exists(twitter_credential
):
115 oauth_dance("Rainbow Stream",
119 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
127 def get_decorated_name():
129 Beginning of every line
131 t
= Twitter(auth
=authen())
132 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
133 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
140 t
= Twitter(auth
=authen())
141 t
.statuses
.update(status
=g
['stuff'])
148 t
= Twitter(auth
=authen())
149 rel
= t
.search
.tweets(q
='#' + g
['stuff'])['statuses']
150 h
, w
= os
.popen('stty size', 'r').read().split()
152 printNicely(grey('*' * int(w
) + '\n'))
153 print('Newest', SEARCH_MAX_RECORD
, 'tweet: \n')
155 draw(t
=rel
[i
], keyword
=g
['stuff'].strip())
156 printNicely(grey('*' * int(w
) + '\n'))
161 List of friend (following)
163 t
= Twitter(auth
=authen())
164 g
['friends'] = t
.friends
.ids()['ids']
165 for i
in g
['friends']:
166 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
167 user
= cycle_color('@' + screen_name
)
176 t
= Twitter(auth
=authen())
177 g
['followers'] = t
.followers
.ids()['ids']
178 for i
in g
['followers']:
179 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
180 user
= cycle_color('@' + screen_name
)
190 Hi boss! I'm ready to serve you right now!
191 ----------------------------------------------------
192 "tweet" at the beginning will tweet immediately
193 "s" and follow by any word will search and return 5 newest tweet
194 "fr" will list out your following people
195 "fl" will list out your followers
196 "h" will print this help once again
197 "c" will clear the terminal
199 ----------------------------------------------------
200 Have fun and hang tight!
203 sys
.stdout
.write(g
['decorated_name'])
217 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
223 Process switch by start of line
233 }.get(cmd
, lambda: sys
.stdout
.write(g
['decorated_name']))
238 Listen to user's input
240 for line
in iter(stdin
.readline
, ''):
242 cmd
= line
.split()[0]
245 # Save cmd to global variable and call process
246 g
['stuff'] = ' '.join(line
.split()[1:])
255 args
= parse_arguments()
259 # These arguments are optional:
261 timeout
=args
.timeout
,
262 block
=not args
.no_block
,
263 heartbeat_timeout
=args
.heartbeat_timeout
)
267 if args
.track_keywords
:
268 query_args
['track'] = args
.track_keywords
271 stream
= TwitterStream(
273 domain
='userstream.twitter.com',
275 tweet_iter
= stream
.user(**query_args
)
277 # Iterate over the sample stream.
278 for tweet
in tweet_iter
:
280 printNicely("-- None --")
281 elif tweet
is Timeout
:
282 printNicely("-- Timeout --")
283 elif tweet
is HeartbeatTimeout
:
284 printNicely("-- Heartbeat Timeout --")
285 elif tweet
is Hangup
:
286 printNicely("-- Hangup --")
287 elif tweet
.get('text'):
296 p
= Process(target
=stream
)
298 g
['stream_pid'] = p
.pid