2 Colorful user's timeline stream
5 from __future__
import print_function
6 from multiprocessing
import Process
8 import os
, os
.path
, sys
,signal
9 import argparse
, time
, datetime
11 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
12 from twitter
.api
import *
13 from twitter
.oauth
import OAuth
, read_token_file
14 from twitter
.oauth_dance
import oauth_dance
15 from twitter
.util
import printNicely
16 from dateutil
import parser
20 from .interactive
import *
40 def draw(t
, keyword
=None):
47 screen_name
= t
['user']['screen_name']
48 name
= t
['user']['name']
49 created_at
= t
['created_at']
50 date
= parser
.parse(created_at
)
51 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
52 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
54 res
= db
.tweet_query(tid
)
57 res
= db
.tweet_query(tid
)
58 rid
= res
[0].rainbow_id
61 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
62 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + ']')
65 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
66 # Highlight screen_name
67 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
69 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
70 # Highlight search keyword
73 lambda x
: on_yellow(x
) if
74 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
78 tweet
= ' '.join(tweet
)
81 line1
= u
"{u:>{uw}}:".format(
85 line2
= u
"{c:>{cw}}".format(
97 def parse_arguments():
101 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
105 help='Timeout for the stream (seconds).')
108 '--heartbeat-timeout',
109 help='Set heartbeat timeout.',
115 help='Set stream to non-blocking.')
119 help='Search the stream for specific text.')
120 return parser
.parse_args()
125 Authenticate with Twitter OAuth
127 # When using rainbow stream you must authorize.
128 twitter_credential
= os
.environ
.get(
132 '')) + os
.sep
+ '.rainbow_oauth'
133 if not os
.path
.exists(twitter_credential
):
134 oauth_dance("Rainbow Stream",
138 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
146 def get_decorated_name():
148 Beginning of every line
150 t
= Twitter(auth
=authen())
151 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
152 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
159 t
= Twitter(auth
=authen())
161 if g
['stuff'].isdigit():
163 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
172 t
= Twitter(auth
=authen())
173 user
= g
['stuff'].split()[0]
176 num
= int(g
['stuff'].split()[1])
179 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
183 print(red('A name should begin with a \'@\''))
190 t
= Twitter(auth
=authen())
191 t
.statuses
.update(status
=g
['stuff'])
198 t
= Twitter(auth
=authen())
200 id = int(g
['stuff'].split()[0])
201 tid
= db
.rainbow_query(id)[0].tweet_id
202 t
.statuses
.retweet(id=tid
,include_entities
=False,trim_user
=True)
204 print(red('Sorry I can\'t retweet for you.'))
212 t
= Twitter(auth
=authen())
214 id = int(g
['stuff'].split()[0])
215 tid
= db
.rainbow_query(id)[0].tweet_id
216 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
217 status
= ' '.join(g
['stuff'].split()[1:])
218 status
= '@' + user
+ ' ' + status
.decode('utf-8')
219 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
221 print(red('Sorry I can\'t understand.'))
229 t
= Twitter(auth
=authen())
231 id = int(g
['stuff'].split()[0])
232 tid
= db
.rainbow_query(id)[0].tweet_id
233 t
.statuses
.destroy(id=tid
)
234 print(green('Okay it\'s gone.'))
236 print(red('Sorry I can\'t delete this tweet for you.'))
243 t
= Twitter(auth
=authen())
245 if g
['stuff'][0] == '#':
246 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
247 print('Newest', SEARCH_MAX_RECORD
, 'tweet:')
249 draw(t
=rel
[i
], keyword
=g
['stuff'].strip()[1:])
252 print(red('A keyword should be a hashtag (like \'#AKB48\')'))
254 print(red('Sorry I can\'t understand.'))
259 List of friend (following)
261 t
= Twitter(auth
=authen())
262 g
['friends'] = t
.friends
.ids()['ids']
263 for i
in g
['friends']:
264 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
265 user
= cycle_color('@' + screen_name
)
274 t
= Twitter(auth
=authen())
275 g
['followers'] = t
.followers
.ids()['ids']
276 for i
in g
['followers']:
277 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
278 user
= cycle_color('@' + screen_name
)
288 Hi boss! I'm ready to serve you right now!
289 ----------------------------------------------------
290 "home" will show your timeline. "home 7" will show 7 tweet.
291 "view @bob" will show your friend @bob's home.
292 "t oops" will tweet "oops" immediately.
293 "rt 12345" will retweet to tweet with id "12345".
294 "rep 12345 oops" will reply "oops" to tweet with id "12345".
295 "del 12345" will delete tweet with id "12345".
296 "s #AKB48" will search for "AKB48" and return 5 newest tweet.
297 "fr" will list out your following people.
298 "fl" will list out your followers.
299 "h" will show this help again.
300 "c" will clear the terminal.
302 ----------------------------------------------------
303 Have fun and hang tight!
320 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
337 [home
,view
,tweet
,retweet
,reply
,delete
,search
,friend
,follower
,help,clear
,quit
]
342 init_interactive_shell(cmdset
)
345 if g
['prefix'] and not first
:
346 line
= raw_input(g
['decorated_name'])
350 cmd
= line
.split()[0]
353 # Save cmd to global variable and call process
354 g
['stuff'] = ' '.join(line
.split()[1:])
363 args
= parse_arguments()
369 # These arguments are optional:
371 timeout
=args
.timeout
,
372 block
=not args
.no_block
,
373 heartbeat_timeout
=args
.heartbeat_timeout
)
377 if args
.track_keywords
:
378 query_args
['track'] = args
.track_keywords
381 stream
= TwitterStream(
385 tweet_iter
= stream
.user(**query_args
)
387 # Iterate over the sample stream.
388 for tweet
in tweet_iter
:
390 printNicely("-- None --")
391 elif tweet
is Timeout
:
392 printNicely("-- Timeout --")
393 elif tweet
is HeartbeatTimeout
:
394 printNicely("-- Heartbeat Timeout --")
395 elif tweet
is Hangup
:
396 printNicely("-- Hangup --")
397 elif tweet
.get('text'):
407 p
= Process(target
=stream
)
409 g
['stream_pid'] = p
.pid