2 Colorful user's timeline stream
4 from multiprocessing
import Process
5 from dateutil
import parser
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
23 from .interactive
import *
45 def draw(t
, keyword
=None, fil
=[], ig
=[]):
53 screen_name
= t
['user']['screen_name']
54 name
= t
['user']['name']
55 created_at
= t
['created_at']
56 date
= parser
.parse(created_at
)
57 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
58 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
61 screen_name
= '@' + screen_name
62 if fil
and screen_name
not in fil
:
64 if ig
and screen_name
in ig
:
67 res
= db
.tweet_query(tid
)
70 res
= db
.tweet_query(tid
)
71 rid
= res
[0].rainbow_id
74 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
75 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + ']')
78 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
79 # Highlight screen_name
80 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
82 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
83 # Highlight search keyword
86 lambda x
: on_yellow(x
) if
87 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
91 tweet
= ' '.join(tweet
)
94 line1
= u
"{u:>{uw}}:".format(
98 line2
= u
"{c:>{cw}}".format(
110 def parse_arguments():
114 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
118 help='Timeout for the stream (seconds).')
121 '--heartbeat-timeout',
122 help='Set heartbeat timeout.',
128 help='Set stream to non-blocking.')
132 help='Search the stream for specific text.')
136 help='Filter specific screen_name.')
140 help='Ignore specific screen_name.')
141 return parser
.parse_args()
146 Authenticate with Twitter OAuth
148 # When using rainbow stream you must authorize.
149 twitter_credential
= os
.environ
.get(
153 '')) + os
.sep
+ '.rainbow_oauth'
154 if not os
.path
.exists(twitter_credential
):
155 oauth_dance("Rainbow Stream",
159 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
167 def get_decorated_name():
169 Beginning of every line
171 t
= Twitter(auth
=authen())
172 name
= '@' + t
.account
.verify_credentials()['screen_name']
173 g
['original_name'] = name
[1:]
174 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
182 target
= g
['stuff'].split()[0]
185 args
= parse_arguments()
187 if g
['stuff'].split()[-1] == '-f':
188 only
= raw_input('Only nicks: ')
189 ignore
= raw_input('Ignore nicks: ')
190 args
.filter = filter(None,only
.split(','))
191 args
.ignore
= filter(None,ignore
.split(','))
192 elif g
['stuff'].split()[-1] == '-d':
193 args
.filter = ONLY_LIST
194 args
.ignore
= IGNORE_LIST
196 printNicely(red('Sorry, wrong format.'))
200 if target
== 'public':
201 keyword
= g
['stuff'].split()[1]
202 if keyword
[0] == '#':
203 keyword
= keyword
[1:]
205 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
206 args
.track_keywords
= keyword
214 g
['stream_pid'] = p
.pid
217 elif target
== 'mine':
219 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
228 g
['stream_pid'] = p
.pid
230 printNicely(green('Stream switched.'))
232 printNicely(cyan('Only: ' + str(args
.filter)))
234 printNicely(red('Ignore: ' + str(args
.ignore
)))
237 printNicely(red('Sorry I can\'t understand.'))
244 t
= Twitter(auth
=authen())
246 if g
['stuff'].isdigit():
248 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
257 t
= Twitter(auth
=authen())
258 user
= g
['stuff'].split()[0]
261 num
= int(g
['stuff'].split()[1])
264 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
268 printNicely(red('A name should begin with a \'@\''))
275 t
= Twitter(auth
=authen())
276 t
.statuses
.update(status
=g
['stuff'])
283 t
= Twitter(auth
=authen())
285 id = int(g
['stuff'].split()[0])
286 tid
= db
.rainbow_query(id)[0].tweet_id
287 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
289 printNicely(red('Sorry I can\'t retweet for you.'))
296 t
= Twitter(auth
=authen())
298 id = int(g
['stuff'].split()[0])
299 tid
= db
.rainbow_query(id)[0].tweet_id
300 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
301 status
= ' '.join(g
['stuff'].split()[1:])
302 status
= '@' + user
+ ' ' + status
.decode('utf-8')
303 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
305 printNicely(red('Sorry I can\'t understand.'))
312 t
= Twitter(auth
=authen())
314 id = int(g
['stuff'].split()[0])
315 tid
= db
.rainbow_query(id)[0].tweet_id
316 t
.statuses
.destroy(id=tid
)
317 printNicely(green('Okay it\'s gone.'))
319 printNicely(red('Sorry I can\'t delete this tweet for you.'))
326 t
= Twitter(auth
=authen())
328 if g
['stuff'][0] == '#':
329 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
331 printNicely('Newest tweets:')
332 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
333 draw(t
=rel
[i
], keyword
=g
['stuff'].strip()[1:])
336 printNicely(magenta('I\'m afraid there is no result'))
338 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
340 printNicely(red('Sorry I can\'t understand.'))
345 List of friend (following)
347 t
= Twitter(auth
=authen())
348 g
['friends'] = t
.friends
.ids()['ids']
349 for i
in g
['friends']:
350 name
= t
.users
.lookup(user_id
=i
)[0]['name']
351 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
352 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
360 t
= Twitter(auth
=authen())
361 g
['followers'] = t
.followers
.ids()['ids']
362 for i
in g
['followers']:
363 name
= t
.users
.lookup(user_id
=i
)[0]['name']
364 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
365 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
376 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
377 usage
+= s
+ '-'*70 + '\n'
379 usage
+= s
+ 'You are ' + yellow('already') +' on your personal stream.\n'
380 usage
+= s
*2 + green('switch public #AKB') + ' will switch to public stream and follow "' + yellow('AKB') + '" keyword.\n'
381 usage
+= s
*2 + green('switch mine') + ' will switch to your personal stream.\n'
382 usage
+= s
*2 + green('switch mine -f ') + ' will prompt to enter the filter.\n'
383 usage
+= s
*3 + yellow('Only nicks') + ' filter will decide nicks will be INCLUDE ONLY.\n'
384 usage
+= s
*3 + yellow('Ignore nicks') + ' filter will decide nicks will be EXCLUDE.\n'
385 usage
+= s
*2 + green('switch mine -d') + ' will use the config\'s ONLY_LIST and IGNORE_LIST\n'
386 usage
+= s
*3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
388 usage
+= s
+ 'For more action: \n'
389 usage
+= s
*2 + green('home') + ' will show your timeline. ' + green('home 7') + ' will show 7 tweet.\n'
390 usage
+= s
*2 + green('view @mdo') + ' will show @mdo\'s home.\n'
391 usage
+= s
*2 + green('t oops ') + 'will tweet "' + yellow('oops') + '"" immediately.\n'
392 usage
+= s
*2 + green('rt 12 ') + ' will retweet to tweet with '+ yellow('[id=12]') + '.\n'
393 usage
+= s
*2 + green('rep 12 oops') + ' will reply "' + yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
394 usage
+= s
*2 + green('del 12 ') + ' will delete tweet with ' + yellow('[id=12]') + '.\n'
395 usage
+= s
*2 + green('s #AKB48') + ' will search for "'+yellow('AKB48') + '" and return 5 newest tweet.\n'
396 usage
+= s
*2 + green('fr') + ' will list out your following people.\n'
397 usage
+= s
*2 + green('fl') + ' will list out your follower.\n'
398 usage
+= s
*2 + green('h') + ' will show this help again.\n'
399 usage
+= s
*2 + green('c') + ' will clear the screen.\n'
400 usage
+= s
*2 + green('q') + ' will quit.\n'
402 usage
+= s
+ '-'*70 + '\n'
403 usage
+= s
+ 'Have fun and hang tight!\n'
418 os
.system('rm -rf rainbow.db')
419 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
428 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
458 Listen to user's input
463 ['public #','mine'], # switch
478 init_interactive_shell(d
)
482 line
= raw_input(g
['decorated_name'])
486 cmd
= line
.split()[0]
489 # Save cmd to global variable and call process
490 g
['stuff'] = ' '.join(line
.split()[1:])
492 if cmd
in ['switch','t','rt','rep']:
498 def stream(domain
, args
, name
='Rainbow Stream'):
506 PUBLIC_DOMAIN
: args
.track_keywords
,
507 SITE_DOMAIN
: 'Site Stream',
509 ascii_art(art_dict
[domain
])
511 # These arguments are optional:
513 timeout
=args
.timeout
,
514 block
=not args
.no_block
,
515 heartbeat_timeout
=args
.heartbeat_timeout
)
519 if args
.track_keywords
:
520 query_args
['track'] = args
.track_keywords
523 stream
= TwitterStream(
528 if domain
== USER_DOMAIN
:
529 tweet_iter
= stream
.user(**query_args
)
530 elif domain
== SITE_DOMAIN
:
531 tweet_iter
= stream
.site(**query_args
)
533 if args
.track_keywords
:
534 tweet_iter
= stream
.statuses
.filter(**query_args
)
536 tweet_iter
= stream
.statuses
.sample()
538 # Iterate over the stream.
539 for tweet
in tweet_iter
:
541 printNicely("-- None --")
542 elif tweet
is Timeout
:
543 printNicely("-- Timeout --")
544 elif tweet
is HeartbeatTimeout
:
545 printNicely("-- Heartbeat Timeout --")
546 elif tweet
is Hangup
:
547 printNicely("-- Hangup --")
548 elif tweet
.get('text'):
549 draw(t
=tweet
, keyword
=args
.track_keywords
, fil
=args
.filter, ig
=args
.ignore
)
556 # Spawn stream process
557 args
= parse_arguments()
559 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
562 # Start listen process
566 g
['stream_pid'] = p
.pid