3ef13d42257d83b60bdae54f374583697b077648
2 Colorful user's timeline stream
4 from __future__
import print_function
5 from multiprocessing
import Process
6 from dateutil
import parser
16 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
17 from twitter
.api
import *
18 from twitter
.oauth
import OAuth
, read_token_file
19 from twitter
.oauth_dance
import oauth_dance
20 from twitter
.util
import printNicely
24 from .interactive
import *
45 def draw(t
, keyword
=None):
52 screen_name
= t
['user']['screen_name']
53 name
= t
['user']['name']
54 created_at
= t
['created_at']
55 date
= parser
.parse(created_at
)
56 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
57 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
59 print('before search')
60 res
= db
.tweet_query(tid
)
63 res
= db
.tweet_query(tid
)
64 rid
= res
[0].rainbow_id
67 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
68 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + ']')
71 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
72 # Highlight screen_name
73 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
75 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
76 # Highlight search keyword
79 lambda x
: on_yellow(x
) if
80 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
84 tweet
= ' '.join(tweet
)
87 line1
= u
"{u:>{uw}}:".format(
91 line2
= u
"{c:>{cw}}".format(
103 def parse_arguments():
107 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
111 help='Timeout for the stream (seconds).')
114 '--heartbeat-timeout',
115 help='Set heartbeat timeout.',
121 help='Set stream to non-blocking.')
125 help='Search the stream for specific text.')
126 return parser
.parse_args()
131 Authenticate with Twitter OAuth
133 # When using rainbow stream you must authorize.
134 twitter_credential
= os
.environ
.get(
138 '')) + os
.sep
+ '.rainbow_oauth'
139 if not os
.path
.exists(twitter_credential
):
140 oauth_dance("Rainbow Stream",
144 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
152 def get_decorated_name():
154 Beginning of every line
156 t
= Twitter(auth
=authen())
157 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
158 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
165 t
= Twitter(auth
=authen())
167 if g
['stuff'].isdigit():
169 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
178 t
= Twitter(auth
=authen())
179 user
= g
['stuff'].split()[0]
182 num
= int(g
['stuff'].split()[1])
185 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
189 print(red('A name should begin with a \'@\''))
196 t
= Twitter(auth
=authen())
197 t
.statuses
.update(status
=g
['stuff'])
205 t
= Twitter(auth
=authen())
207 id = int(g
['stuff'].split()[0])
208 tid
= db
.rainbow_query(id)[0].tweet_id
209 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
211 print(red('Sorry I can\'t retweet for you.'))
219 t
= Twitter(auth
=authen())
221 id = int(g
['stuff'].split()[0])
222 tid
= db
.rainbow_query(id)[0].tweet_id
223 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
224 status
= ' '.join(g
['stuff'].split()[1:])
225 status
= '@' + user
+ ' ' + status
.decode('utf-8')
226 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
228 print(red('Sorry I can\'t understand.'))
236 t
= Twitter(auth
=authen())
238 id = int(g
['stuff'].split()[0])
239 tid
= db
.rainbow_query(id)[0].tweet_id
240 t
.statuses
.destroy(id=tid
)
241 print(green('Okay it\'s gone.'))
243 print(red('Sorry I can\'t delete this tweet for you.'))
250 t
= Twitter(auth
=authen())
252 if g
['stuff'][0] == '#':
253 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
254 print('Newest', SEARCH_MAX_RECORD
, 'tweet:')
256 draw(t
=rel
[i
], keyword
=g
['stuff'].strip()[1:])
259 print(red('A keyword should be a hashtag (like \'#AKB48\')'))
261 print(red('Sorry I can\'t understand.'))
266 List of friend (following)
268 t
= Twitter(auth
=authen())
269 g
['friends'] = t
.friends
.ids()['ids']
270 for i
in g
['friends']:
271 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
272 user
= cycle_color('@' + screen_name
)
281 t
= Twitter(auth
=authen())
282 g
['followers'] = t
.followers
.ids()['ids']
283 for i
in g
['followers']:
284 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
285 user
= cycle_color('@' + screen_name
)
295 Hi boss! I'm ready to serve you right now!
296 -------------------------------------------------------------
297 "home" will show your timeline. "home 7" will show 7 tweet.
298 "view @bob" will show your friend @bob's home.
299 "t oops" will tweet "oops" immediately.
300 "rt 12345" will retweet to tweet with id "12345".
301 "rep 12345 oops" will reply "oops" to tweet with id "12345".
302 "del 12345" will delete tweet with id "12345".
303 "s #AKB48" will search for "AKB48" and return 5 newest tweet.
304 "fr" will list out your following people.
305 "fl" will list out your followers.
306 "h" will show this help again.
307 "c" will clear the terminal.
309 -------------------------------------------------------------
310 Have fun and hang tight!
327 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
362 init_interactive_shell(cmdset
)
365 if g
['prefix'] and not first
:
366 line
= raw_input(g
['decorated_name'])
370 cmd
= line
.split()[0]
373 # Save cmd to global variable and call process
374 g
['stuff'] = ' '.join(line
.split()[1:])
383 args
= parse_arguments()
387 # These arguments are optional:
389 timeout
=args
.timeout
,
390 block
=not args
.no_block
,
391 heartbeat_timeout
=args
.heartbeat_timeout
)
395 if args
.track_keywords
:
396 query_args
['track'] = args
.track_keywords
399 stream
= TwitterStream(
403 tweet_iter
= stream
.user(**query_args
)
405 # Iterate over the sample stream.
406 for tweet
in tweet_iter
:
408 printNicely("-- None --")
409 elif tweet
is Timeout
:
410 printNicely("-- Timeout --")
411 elif tweet
is HeartbeatTimeout
:
412 printNicely("-- Heartbeat Timeout --")
413 elif tweet
is Hangup
:
414 printNicely("-- Hangup --")
415 elif tweet
.get('text'):
425 p
= Process(target
=stream
)
427 g
['stream_pid'] = p
.pid