2 Colorful user's timeline stream
4 from multiprocessing
import Process
5 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
21 from StringIO
import StringIO
25 from .consumer
import *
26 from .interactive
import *
28 from .c_image
import *
52 def draw(t
, imgflg
= 0, keyword
=None, fil
=[], ig
=[]):
60 screen_name
= t
['user']['screen_name']
61 name
= t
['user']['name']
62 created_at
= t
['created_at']
63 favorited
= t
['favorited']
64 date
= parser
.parse(created_at
)
65 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
66 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
72 urls
= t
['entities']['urls']
74 expanded_url
.append(u
['expanded_url'])
83 media
= t
['entities']['media']
85 media_url
.append(m
['media_url'])
90 screen_name
= '@' + screen_name
91 if fil
and screen_name
not in fil
:
93 if ig
and screen_name
in ig
:
96 res
= db
.tweet_query(tid
)
99 res
= db
.tweet_query(tid
)
100 rid
= res
[0].rainbow_id
103 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
104 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
106 meta
= meta
+ green(u
'\u2605')
110 for index
in range(len(expanded_url
)):
112 lambda x
: expanded_url
[index
] if x
== url
[index
] else x
,
115 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
116 # Highlight screen_name
117 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
119 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
120 # Highlight search keyword
123 lambda x
: on_yellow(x
) if
124 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
129 tweet
= ' '.join(tweet
)
132 line1
= u
"{u:>{uw}}:".format(
136 line2
= u
"{c:>{cw}}".format(
148 if imgflg
and media_url
:
150 response
= requests
.get(mu
)
151 image_to_display(StringIO(response
.content
))
154 def parse_arguments():
158 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
162 help='Timeout for the stream (seconds).')
165 '--heartbeat-timeout',
166 help='Set heartbeat timeout.',
172 help='Set stream to non-blocking.')
176 help='Search the stream for specific text.')
180 help='Filter specific screen_name.')
184 help='Ignore specific screen_name.')
188 help='Display all photo on terminal.')
189 return parser
.parse_args()
194 Authenticate with Twitter OAuth
196 # When using rainbow stream you must authorize.
197 twitter_credential
= os
.environ
.get(
201 '')) + os
.sep
+ '.rainbow_oauth'
202 if not os
.path
.exists(twitter_credential
):
203 oauth_dance("Rainbow Stream",
207 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
215 def get_decorated_name():
217 Beginning of every line
219 t
= Twitter(auth
=authen())
220 name
= '@' + t
.account
.verify_credentials()['screen_name']
221 g
['original_name'] = name
[1:]
222 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
230 target
= g
['stuff'].split()[0]
233 args
= parse_arguments()
235 if g
['stuff'].split()[-1] == '-f':
236 only
= raw_input('Only nicks: ')
237 ignore
= raw_input('Ignore nicks: ')
238 args
.filter = filter(None, only
.split(','))
239 args
.ignore
= filter(None, ignore
.split(','))
240 elif g
['stuff'].split()[-1] == '-d':
241 args
.filter = ONLY_LIST
242 args
.ignore
= IGNORE_LIST
244 printNicely(red('Sorry, wrong format.'))
248 if target
== 'public':
249 keyword
= g
['stuff'].split()[1]
250 if keyword
[0] == '#':
251 keyword
= keyword
[1:]
253 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
254 args
.track_keywords
= keyword
262 g
['stream_pid'] = p
.pid
265 elif target
== 'mine':
267 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
276 g
['stream_pid'] = p
.pid
278 printNicely(green('Stream switched.'))
280 printNicely(cyan('Only: ' + str(args
.filter)))
282 printNicely(red('Ignore: ' + str(args
.ignore
)))
285 printNicely(red('Sorry I can\'t understand.'))
292 t
= Twitter(auth
=authen())
294 if g
['stuff'].isdigit():
296 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
297 draw(t
=tweet
, imgflg
=g
['image'])
305 t
= Twitter(auth
=authen())
306 user
= g
['stuff'].split()[0]
309 num
= int(g
['stuff'].split()[1])
312 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
313 draw(t
=tweet
, imgflg
=g
['image'])
316 printNicely(red('A name should begin with a \'@\''))
323 t
= Twitter(auth
=authen())
324 t
.statuses
.update(status
=g
['stuff'])
331 t
= Twitter(auth
=authen())
333 id = int(g
['stuff'].split()[0])
334 tid
= db
.rainbow_query(id)[0].tweet_id
335 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
337 printNicely(red('Sorry I can\'t retweet for you.'))
344 t
= Twitter(auth
=authen())
346 id = int(g
['stuff'].split()[0])
347 tid
= db
.rainbow_query(id)[0].tweet_id
348 t
.favorites
.create(_id
=tid
, include_entities
=False)
349 printNicely(green('Favorited.'))
350 draw(t
.statuses
.show(id=tid
), imgflg
=g
['image'])
352 printNicely(red('Omg some syntax is wrong.'))
359 t
= Twitter(auth
=authen())
361 id = int(g
['stuff'].split()[0])
362 tid
= db
.rainbow_query(id)[0].tweet_id
363 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
364 status
= ' '.join(g
['stuff'].split()[1:])
365 status
= '@' + user
+ ' ' + status
.decode('utf-8')
366 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
368 printNicely(red('Sorry I can\'t understand.'))
375 t
= Twitter(auth
=authen())
377 id = int(g
['stuff'].split()[0])
378 tid
= db
.rainbow_query(id)[0].tweet_id
379 t
.statuses
.destroy(id=tid
)
380 printNicely(green('Okay it\'s gone.'))
382 printNicely(red('Sorry I can\'t delete this tweet for you.'))
389 t
= Twitter(auth
=authen())
391 id = int(g
['stuff'].split()[0])
392 tid
= db
.rainbow_query(id)[0].tweet_id
393 t
.favorites
.destroy(_id
=tid
)
394 printNicely(green('Okay it\'s unfavorited.'))
395 draw(t
.statuses
.show(id=tid
), imgflg
=g
['image'])
397 printNicely(red('Sorry I can\'t unfavorite this tweet for you.'))
404 t
= Twitter(auth
=authen())
406 if g
['stuff'][0] == '#':
407 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
409 printNicely('Newest tweets:')
410 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
413 keyword
=g
['stuff'].strip()[1:])
416 printNicely(magenta('I\'m afraid there is no result'))
418 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
420 printNicely(red('Sorry I can\'t understand.'))
427 t
= Twitter(auth
=authen())
429 target
= g
['stuff'].split()[0]
430 if target
!= 'image':
432 id = int(g
['stuff'].split()[1])
433 tid
= db
.rainbow_query(id)[0].tweet_id
434 tweet
= t
.statuses
.show(id=tid
)
435 media
= tweet
['entities']['media']
437 res
= requests
.get(m
['media_url'])
438 img
= Image
.open(StringIO(res
.content
))
441 printNicely(red('Sorry I can\'t show this image.'))
448 t
= Twitter(auth
=authen())
449 screen_name
= g
['stuff'].split()[0]
450 if screen_name
[0] == '@':
452 t
.friendships
.create(screen_name
=screen_name
[1:],follow
=True)
453 printNicely(green('You are following ' + screen_name
+ ' now!'))
455 printNicely(red('Sorry can not follow at this time.'))
457 printNicely(red('Sorry I can\'t understand.'))
464 t
= Twitter(auth
=authen())
465 screen_name
= g
['stuff'].split()[0]
466 if screen_name
[0] == '@':
468 t
.friendships
.destroy(screen_name
=screen_name
[1:],include_entities
=False)
469 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
471 printNicely(red('Sorry can not unfollow at this time.'))
473 printNicely(red('Sorry I can\'t understand.'))
481 h
, w
= os
.popen('stty size', 'r').read().split()
484 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
485 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
487 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
488 usage
+= s
* 2 + green('switch public #AKB') + \
489 ' will switch to public stream and follow "' + \
490 yellow('AKB') + '" keyword.\n'
491 usage
+= s
* 2 + green('switch mine') + \
492 ' will switch to your personal stream.\n'
493 usage
+= s
* 2 + green('switch mine -f ') + \
494 ' will prompt to enter the filter.\n'
495 usage
+= s
* 3 + yellow('Only nicks') + \
496 ' filter will decide nicks will be INCLUDE ONLY.\n'
497 usage
+= s
* 3 + yellow('Ignore nicks') + \
498 ' filter will decide nicks will be EXCLUDE.\n'
499 usage
+= s
* 2 + green('switch mine -d') + \
500 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
501 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
503 usage
+= s
+ 'For more action: \n'
504 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
505 green('home 7') + ' will show 7 tweet.\n'
506 usage
+= s
* 2 + green('view @mdo') + \
507 ' will show ' + yellow('@mdo') + '\'s home.\n'
508 usage
+= s
* 2 + green('t oops ') + \
509 'will tweet "' + yellow('oops') + '" immediately.\n'
511 green('rt 12 ') + ' will retweet to tweet with ' + \
512 yellow('[id=12]') + '.\n'
514 green('fav 12 ') + ' will favorite the tweet with ' + \
515 yellow('[id=12]') + '.\n'
516 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
517 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
519 green('del 12 ') + ' will delete tweet with ' + \
520 yellow('[id=12]') + '.\n'
522 green('ufav 12 ') + ' will unfavorite tweet with ' + \
523 yellow('[id=12]') + '.\n'
524 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
525 yellow('AKB48') + '" and return 5 newest tweet.\n'
526 usage
+= s
* 2 + green('show image 12') + ' will show image in ' + \
527 yellow('[id=12]') + 'in your OS\'s image viewer.\n'
528 usage
+= s
* 2 + green('fl @dtvd88') + ' will follow ' + \
529 yellow('@dtvd88') + '.\n'
530 usage
+= s
* 2 + green('ufl @dtvd88') + ' will unfollow ' + \
531 yellow('@dtvd88') + '.\n'
532 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
533 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
534 usage
+= s
* 2 + green('q') + ' will quit.\n'
536 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
537 usage
+= s
+ 'Have fun and hang tight!\n'
553 os
.system('rm -rf rainbow.db')
554 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
563 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
596 Listen to user's input
601 ['public #', 'mine'], # switch
611 ['image'], # show image
619 init_interactive_shell(d
)
624 line
= raw_input(g
['decorated_name'])
628 cmd
= line
.split()[0]
631 # Save cmd to global variable and call process
632 g
['stuff'] = ' '.join(line
.split()[1:])
634 if cmd
in ['switch', 't', 'rt', 'rep']:
640 def stream(domain
, args
, name
='Rainbow Stream'):
648 PUBLIC_DOMAIN
: args
.track_keywords
,
649 SITE_DOMAIN
: 'Site Stream',
651 ascii_art(art_dict
[domain
])
653 # These arguments are optional:
655 timeout
=args
.timeout
,
656 block
=not args
.no_block
,
657 heartbeat_timeout
=args
.heartbeat_timeout
)
661 if args
.track_keywords
:
662 query_args
['track'] = args
.track_keywords
665 stream
= TwitterStream(
670 if domain
== USER_DOMAIN
:
671 tweet_iter
= stream
.user(**query_args
)
672 elif domain
== SITE_DOMAIN
:
673 tweet_iter
= stream
.site(**query_args
)
675 if args
.track_keywords
:
676 tweet_iter
= stream
.statuses
.filter(**query_args
)
678 tweet_iter
= stream
.statuses
.sample()
680 # Iterate over the stream.
681 for tweet
in tweet_iter
:
683 printNicely("-- None --")
684 elif tweet
is Timeout
:
685 printNicely("-- Timeout --")
686 elif tweet
is HeartbeatTimeout
:
687 printNicely("-- Heartbeat Timeout --")
688 elif tweet
is Hangup
:
689 printNicely("-- Hangup --")
690 elif tweet
.get('text'):
694 keyword
=args
.track_keywords
,
704 # Spawn stream process
705 args
= parse_arguments()
707 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
710 # Start listen process
714 g
['stream_pid'] = p
.pid
715 g
['image'] = args
.image