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 *
51 def draw(t
, keyword
=None, fil
=[], ig
=[]):
59 screen_name
= t
['user']['screen_name']
60 name
= t
['user']['name']
61 created_at
= t
['created_at']
62 favorited
= t
['favorited']
63 date
= parser
.parse(created_at
)
64 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
65 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
71 urls
= t
['entities']['urls']
73 expanded_url
.append(u
['expanded_url'])
82 media
= t
['entities']['media']
84 media_url
= m
['media_url']
89 screen_name
= '@' + screen_name
90 if fil
and screen_name
not in fil
:
92 if ig
and screen_name
in ig
:
95 res
= db
.tweet_query(tid
)
98 res
= db
.tweet_query(tid
)
99 rid
= res
[0].rainbow_id
102 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
103 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
105 meta
= meta
+ green(u
'\u2605')
109 for index
in range(len(expanded_url
)):
111 lambda x
: expanded_url
[index
] if x
== url
[index
] else x
,
114 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
115 # Highlight screen_name
116 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
118 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
119 # Highlight search keyword
122 lambda x
: on_yellow(x
) if
123 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
128 tweet
= ' '.join(tweet
)
131 line1
= u
"{u:>{uw}}:".format(
135 line2
= u
"{c:>{cw}}".format(
148 response
= requests
.get(media_url
)
149 image_to_display(StringIO(response
.content
))
152 def parse_arguments():
156 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
160 help='Timeout for the stream (seconds).')
163 '--heartbeat-timeout',
164 help='Set heartbeat timeout.',
170 help='Set stream to non-blocking.')
174 help='Search the stream for specific text.')
178 help='Filter specific screen_name.')
182 help='Ignore specific screen_name.')
183 return parser
.parse_args()
188 Authenticate with Twitter OAuth
190 # When using rainbow stream you must authorize.
191 twitter_credential
= os
.environ
.get(
195 '')) + os
.sep
+ '.rainbow_oauth'
196 if not os
.path
.exists(twitter_credential
):
197 oauth_dance("Rainbow Stream",
201 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
209 def get_decorated_name():
211 Beginning of every line
213 t
= Twitter(auth
=authen())
214 name
= '@' + t
.account
.verify_credentials()['screen_name']
215 g
['original_name'] = name
[1:]
216 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
224 target
= g
['stuff'].split()[0]
227 args
= parse_arguments()
229 if g
['stuff'].split()[-1] == '-f':
230 only
= raw_input('Only nicks: ')
231 ignore
= raw_input('Ignore nicks: ')
232 args
.filter = filter(None, only
.split(','))
233 args
.ignore
= filter(None, ignore
.split(','))
234 elif g
['stuff'].split()[-1] == '-d':
235 args
.filter = ONLY_LIST
236 args
.ignore
= IGNORE_LIST
238 printNicely(red('Sorry, wrong format.'))
242 if target
== 'public':
243 keyword
= g
['stuff'].split()[1]
244 if keyword
[0] == '#':
245 keyword
= keyword
[1:]
247 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
248 args
.track_keywords
= keyword
256 g
['stream_pid'] = p
.pid
259 elif target
== 'mine':
261 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
270 g
['stream_pid'] = p
.pid
272 printNicely(green('Stream switched.'))
274 printNicely(cyan('Only: ' + str(args
.filter)))
276 printNicely(red('Ignore: ' + str(args
.ignore
)))
279 printNicely(red('Sorry I can\'t understand.'))
286 t
= Twitter(auth
=authen())
288 if g
['stuff'].isdigit():
290 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
299 t
= Twitter(auth
=authen())
300 user
= g
['stuff'].split()[0]
303 num
= int(g
['stuff'].split()[1])
306 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
310 printNicely(red('A name should begin with a \'@\''))
317 t
= Twitter(auth
=authen())
318 t
.statuses
.update(status
=g
['stuff'])
325 t
= Twitter(auth
=authen())
327 id = int(g
['stuff'].split()[0])
328 tid
= db
.rainbow_query(id)[0].tweet_id
329 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
331 printNicely(red('Sorry I can\'t retweet for you.'))
338 t
= Twitter(auth
=authen())
340 id = int(g
['stuff'].split()[0])
341 tid
= db
.rainbow_query(id)[0].tweet_id
342 t
.favorites
.create(_id
=tid
, include_entities
=False)
343 printNicely(green('Favorited.'))
344 draw(t
.statuses
.show(id=tid
))
346 printNicely(red('Omg some syntax is wrong.'))
353 t
= Twitter(auth
=authen())
355 id = int(g
['stuff'].split()[0])
356 tid
= db
.rainbow_query(id)[0].tweet_id
357 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
358 status
= ' '.join(g
['stuff'].split()[1:])
359 status
= '@' + user
+ ' ' + status
.decode('utf-8')
360 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
362 printNicely(red('Sorry I can\'t understand.'))
369 t
= Twitter(auth
=authen())
371 id = int(g
['stuff'].split()[0])
372 tid
= db
.rainbow_query(id)[0].tweet_id
373 t
.statuses
.destroy(id=tid
)
374 printNicely(green('Okay it\'s gone.'))
376 printNicely(red('Sorry I can\'t delete this tweet for you.'))
383 t
= Twitter(auth
=authen())
385 id = int(g
['stuff'].split()[0])
386 tid
= db
.rainbow_query(id)[0].tweet_id
387 t
.favorites
.destroy(_id
=tid
)
388 printNicely(green('Okay it\'s unfavorited.'))
389 draw(t
.statuses
.show(id=tid
))
391 printNicely(red('Sorry I can\'t unfavorite this tweet for you.'))
398 t
= Twitter(auth
=authen())
400 if g
['stuff'][0] == '#':
401 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
403 printNicely('Newest tweets:')
404 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
405 draw(t
=rel
[i
], keyword
=g
['stuff'].strip()[1:])
408 printNicely(magenta('I\'m afraid there is no result'))
410 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
412 printNicely(red('Sorry I can\'t understand.'))
417 List of friend (following)
419 t
= Twitter(auth
=authen())
420 g
['friends'] = t
.friends
.ids()['ids']
421 for i
in g
['friends']:
422 name
= t
.users
.lookup(user_id
=i
)[0]['name']
423 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
424 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
432 t
= Twitter(auth
=authen())
433 g
['followers'] = t
.followers
.ids()['ids']
434 for i
in g
['followers']:
435 name
= t
.users
.lookup(user_id
=i
)[0]['name']
436 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
437 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
446 h
, w
= os
.popen('stty size', 'r').read().split()
449 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
450 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
452 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
453 usage
+= s
* 2 + green('switch public #AKB') + \
454 ' will switch to public stream and follow "' + \
455 yellow('AKB') + '" keyword.\n'
456 usage
+= s
* 2 + green('switch mine') + \
457 ' will switch to your personal stream.\n'
458 usage
+= s
* 2 + green('switch mine -f ') + \
459 ' will prompt to enter the filter.\n'
460 usage
+= s
* 3 + yellow('Only nicks') + \
461 ' filter will decide nicks will be INCLUDE ONLY.\n'
462 usage
+= s
* 3 + yellow('Ignore nicks') + \
463 ' filter will decide nicks will be EXCLUDE.\n'
464 usage
+= s
* 2 + green('switch mine -d') + \
465 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
466 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
468 usage
+= s
+ 'For more action: \n'
469 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
470 green('home 7') + ' will show 7 tweet.\n'
471 usage
+= s
* 2 + green('view @mdo') + \
472 ' will show ' + yellow('@mdo') + '\'s home.\n'
473 usage
+= s
* 2 + green('t oops ') + \
474 'will tweet "' + yellow('oops') + '" immediately.\n'
476 green('rt 12 ') + ' will retweet to tweet with ' + \
477 yellow('[id=12]') + '.\n'
479 green('fav 12 ') + ' will favorite the tweet with ' + \
480 yellow('[id=12]') + '.\n'
481 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
482 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
484 green('del 12 ') + ' will delete tweet with ' + \
485 yellow('[id=12]') + '.\n'
487 green('ufav 12 ') + ' will unfavorite tweet with ' + \
488 yellow('[id=12]') + '.\n'
489 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
490 yellow('AKB48') + '" and return 5 newest tweet.\n'
491 usage
+= s
* 2 + green('fr') + ' will list out your following people.\n'
492 usage
+= s
* 2 + green('fl') + ' will list out your follower.\n'
493 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
494 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
495 usage
+= s
* 2 + green('q') + ' will quit.\n'
497 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
498 usage
+= s
+ 'Have fun and hang tight!\n'
513 os
.system('rm -rf rainbow.db')
514 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
523 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
555 Listen to user's input
560 ['public #', 'mine'], # switch
575 init_interactive_shell(d
)
579 line
= raw_input(g
['decorated_name'])
583 cmd
= line
.split()[0]
586 # Save cmd to global variable and call process
587 g
['stuff'] = ' '.join(line
.split()[1:])
589 if cmd
in ['switch', 't', 'rt', 'rep']:
595 def stream(domain
, args
, name
='Rainbow Stream'):
603 PUBLIC_DOMAIN
: args
.track_keywords
,
604 SITE_DOMAIN
: 'Site Stream',
606 ascii_art(art_dict
[domain
])
608 # These arguments are optional:
610 timeout
=args
.timeout
,
611 block
=not args
.no_block
,
612 heartbeat_timeout
=args
.heartbeat_timeout
)
616 if args
.track_keywords
:
617 query_args
['track'] = args
.track_keywords
620 stream
= TwitterStream(
625 if domain
== USER_DOMAIN
:
626 tweet_iter
= stream
.user(**query_args
)
627 elif domain
== SITE_DOMAIN
:
628 tweet_iter
= stream
.site(**query_args
)
630 if args
.track_keywords
:
631 tweet_iter
= stream
.statuses
.filter(**query_args
)
633 tweet_iter
= stream
.statuses
.sample()
635 # Iterate over the stream.
636 for tweet
in tweet_iter
:
638 printNicely("-- None --")
639 elif tweet
is Timeout
:
640 printNicely("-- Timeout --")
641 elif tweet
is HeartbeatTimeout
:
642 printNicely("-- Heartbeat Timeout --")
643 elif tweet
is Hangup
:
644 printNicely("-- Hangup --")
645 elif tweet
.get('text'):
648 keyword
=args
.track_keywords
,
657 # Spawn stream process
658 args
= parse_arguments()
660 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
663 # Start listen process
667 g
['stream_pid'] = p
.pid