]>
jfr.im git - z_archive/twitter.git/blob - twitter/cmdline.py
5 twitter [action] [options]
9 authorize authorize the command-line tool to interact with Twitter
11 friends get latest tweets from your friends (default action)
12 help print this help text that you are currently reading
13 leave stop following a user
14 list get list of a user's lists; give a list name to get
16 mylist get list of your lists; give a list name to get tweets
18 public get latest public tweets
19 pyprompt start a Python prompt for interacting with the twitter
21 replies get latest replies to you
22 search search twitter (Beware: octothorpe, escape it)
23 set set your twitter status
24 shell login to the twitter shell
25 rate get your current rate limit status (remaining API reqs)
30 -r --refresh run this command forever, polling every once
31 in a while (default: every 5 minutes)
32 -R --refresh-rate <rate> set the refresh rate (in seconds)
33 -f --format <format> specify the output format for status updates
34 -c --config <filename> read username and password from given config
35 file (default ~/.twitter)
36 -l --length <count> specify number of status updates shown
37 (default: 20, max: 200)
38 -t --timestamp show time before status lines
39 -d --datestamp show date before status lines
40 --no-ssl use less-secure HTTP instead of HTTPS
41 --oauth <filename> filename to read/store oauth credentials to
43 FORMATS for the --format option
45 default one line per status
46 verbose multiple lines per status, more verbose status info
48 ansi ansi colour (rainbow mode)
53 The config file should be placed in your home directory and be named .twitter.
54 It must contain a [twitter] header, and all the desired options you wish to
58 format: <desired_default_format_for_output>
59 prompt: <twitter_shell_prompt e.g. '[cyan]twitter[R]> '>
61 OAuth authentication tokens are stored in the file .twitter_oauth in your
65 from __future__
import print_function
68 input = __builtins__
['raw_input']
69 except AttributeError:
73 CONSUMER_KEY
='uS6hO2sV6tDKIOeVjhnFnQ'
74 CONSUMER_SECRET
='MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'
78 from getopt
import gnu_getopt
as getopt
, GetoptError
79 from getpass
import getpass
86 from ConfigParser
import SafeConfigParser
88 from configparser
import ConfigParser
as SafeConfigParser
91 from urllib
.parse
import quote
93 from urllib2
import quote
96 from .api
import Twitter
, TwitterError
97 from .oauth
import OAuth
, write_token_file
, read_token_file
98 from .oauth_dance
import oauth_dance
100 from .util
import smrt_input
, printNicely
107 'prompt': '[cyan]twitter[R]> ',
108 'config_filename': os
.environ
.get('HOME', '') + os
.sep
+ '.twitter',
109 'oauth_filename': os
.environ
.get('HOME', '') + os
.sep
+ '.twitter_oauth',
117 def parse_args(args
, options
):
118 long_opts
= ['help', 'format=', 'refresh', 'oauth=',
119 'refresh-rate=', 'config=', 'length=', 'timestamp',
120 'datestamp', 'no-ssl']
121 short_opts
= "e:p:f:h?rR:c:l:td"
122 opts
, extra_args
= getopt(args
, short_opts
, long_opts
)
123 extra_args
= [arg
.decode(locale
.getpreferredencoding())
124 for arg
in extra_args
]
126 for opt
, arg
in opts
:
127 if opt
in ('-f', '--format'):
128 options
['format'] = arg
129 elif opt
in ('-r', '--refresh'):
130 options
['refresh'] = True
131 elif opt
in ('-R', '--refresh-rate'):
132 options
['refresh_rate'] = int(arg
)
133 elif opt
in ('-l', '--length'):
134 options
["length"] = int(arg
)
135 elif opt
in ('-t', '--timestamp'):
136 options
["timestamp"] = True
137 elif opt
in ('-d', '--datestamp'):
138 options
["datestamp"] = True
139 elif opt
in ('-?', '-h', '--help'):
140 options
['action'] = 'help'
141 elif opt
in ('-c', '--config'):
142 options
['config_filename'] = arg
143 elif opt
== '--no-ssl':
144 options
['secure'] = False
145 elif opt
== '--oauth':
146 options
['oauth_filename'] = arg
148 if extra_args
and not ('action' in options
and options
['action'] == 'help'):
149 options
['action'] = extra_args
[0]
150 options
['extra_args'] = extra_args
[1:]
152 def get_time_string(status
, options
, format
="%a %b %d %H:%M:%S +0000 %Y"):
153 timestamp
= options
["timestamp"]
154 datestamp
= options
["datestamp"]
155 t
= time
.strptime(status
['created_at'], format
)
156 i_hate_timezones
= time
.timezone
158 i_hate_timezones
= time
.altzone
159 dt
= datetime
.datetime(*t
[:-3]) - datetime
.timedelta(
160 seconds
=i_hate_timezones
)
162 if timestamp
and datestamp
:
163 return time
.strftime("%Y-%m-%d %H:%M:%S ", t
)
165 return time
.strftime("%H:%M:%S ", t
)
167 return time
.strftime("%Y-%m-%d ", t
)
170 class StatusFormatter(object):
171 def __call__(self
, status
, options
):
173 get_time_string(status
, options
),
174 status
['user']['screen_name'], status
['text']))
176 class AnsiStatusFormatter(object):
178 self
._colourMap
= ansi
.ColourMap()
180 def __call__(self
, status
, options
):
181 colour
= self
._colourMap
.colourFor(status
['user']['screen_name'])
182 return ("%s%s%s%s %s" %(
183 get_time_string(status
, options
),
184 ansi
.cmdColour(colour
), status
['user']['screen_name'],
185 ansi
.cmdReset(), status
['text']))
187 class VerboseStatusFormatter(object):
188 def __call__(self
, status
, options
):
189 return ("-- %s (%s) on %s\n%s\n" %(
190 status
['user']['screen_name'],
191 status
['user']['location'],
192 status
['created_at'],
195 class URLStatusFormatter(object):
196 urlmatch
= re
.compile(r
'https?://\S+')
197 def __call__(self
, status
, options
):
198 urls
= self
.urlmatch
.findall(status
['text'])
199 return '\n'.join(urls
) if urls
else ""
202 class ListsFormatter(object):
203 def __call__(self
, list):
204 if list['description']:
205 list_str
= "%-30s (%s)" % (list['name'], list['description'])
207 list_str
= "%-30s" % (list['name'])
208 return "%s\n" % list_str
210 class ListsVerboseFormatter(object):
211 def __call__(self
, list):
212 list_str
= "%-30s\n description: %s\n members: %s\n mode:%s\n" % (list['name'], list['description'], list['member_count'], list['mode'])
215 class AnsiListsFormatter(object):
217 self
._colourMap
= ansi
.ColourMap()
219 def __call__(self
, list):
220 colour
= self
._colourMap
.colourFor(list['name'])
221 return ("%s%-15s%s %s" %(
222 ansi
.cmdColour(colour
), list['name'],
223 ansi
.cmdReset(), list['description']))
226 class AdminFormatter(object):
227 def __call__(self
, action
, user
):
228 user_str
= "%s (%s)" %(user
['screen_name'], user
['name'])
229 if action
== "follow":
230 return "You are now following %s.\n" %(user_str)
232 return "You are no longer following %s.\n" %(user_str)
234 class VerboseAdminFormatter(object):
235 def __call__(self
, action
, user
):
236 return("-- %s: %s (%s): %s" % (
237 "Following" if action
== "follow" else "Leaving",
242 class SearchFormatter(object):
243 def __call__(self
, result
, options
):
245 get_time_string(result
, options
, "%a, %d %b %Y %H:%M:%S +0000"),
246 result
['from_user'], result
['text']))
248 class VerboseSearchFormatter(SearchFormatter
):
249 pass #Default to the regular one
251 class URLSearchFormatter(object):
252 urlmatch
= re
.compile(r
'https?://\S+')
253 def __call__(self
, result
, options
):
254 urls
= self
.urlmatch
.findall(result
['text'])
255 return '\n'.join(urls
) if urls
else ""
257 class AnsiSearchFormatter(object):
259 self
._colourMap
= ansi
.ColourMap()
261 def __call__(self
, result
, options
):
262 colour
= self
._colourMap
.colourFor(result
['from_user'])
263 return ("%s%s%s%s %s" %(
264 get_time_string(result
, options
, "%a, %d %b %Y %H:%M:%S +0000"),
265 ansi
.cmdColour(colour
), result
['from_user'],
266 ansi
.cmdReset(), result
['text']))
268 _term_encoding
= None
269 def get_term_encoding():
270 global _term_encoding
271 if not _term_encoding
:
272 lang
= os
.getenv('LANG', 'unknown.UTF-8').split('.')
274 _term_encoding
= lang
[1]
276 _term_encoding
= 'UTF-8'
277 return _term_encoding
280 status_formatters
= {
281 'default': StatusFormatter
,
282 'verbose': VerboseStatusFormatter
,
283 'urls': URLStatusFormatter
,
284 'ansi': AnsiStatusFormatter
286 formatters
['status'] = status_formatters
289 'default': AdminFormatter
,
290 'verbose': VerboseAdminFormatter
,
291 'urls': AdminFormatter
,
292 'ansi': AdminFormatter
294 formatters
['admin'] = admin_formatters
296 search_formatters
= {
297 'default': SearchFormatter
,
298 'verbose': VerboseSearchFormatter
,
299 'urls': URLSearchFormatter
,
300 'ansi': AnsiSearchFormatter
302 formatters
['search'] = search_formatters
305 'default': ListsFormatter
,
306 'verbose': ListsVerboseFormatter
,
308 'ansi': AnsiListsFormatter
310 formatters
['lists'] = lists_formatters
312 def get_formatter(action_type
, options
):
313 formatters_dict
= formatters
.get(action_type
)
314 if (not formatters_dict
):
316 "There was an error finding a class of formatters for your type (%s)"
318 f
= formatters_dict
.get(options
['format'])
321 "Unknown formatter '%s' for status actions" %(options
['format']))
324 class Action(object):
326 def ask(self
, subject
='perform this action', careful
=False):
328 Requests fromt he user using `raw_input` if `subject` should be
329 performed. When `careful`, the default answer is NO, otherwise YES.
330 Returns the user answer in the form `True` or `False`.
336 prompt
= 'You really want to %s %s? ' %(subject
, sample
)
338 answer
= input(prompt
).lower()
340 return answer
in ('yes', 'y')
342 return answer
not in ('no', 'n')
344 print(file=sys
.stderr
) # Put Newline since Enter was never pressed
346 # Figure out why on OS X the raw_input keeps raising
347 # EOFError and is never able to reset and get more input
348 # Hint: Look at how IPython implements their console
354 def __call__(self
, twitter
, options
):
355 action
= actions
.get(options
['action'], NoSuchAction
)()
357 doAction
= lambda : action(twitter
, options
)
358 if (options
['refresh'] and isinstance(action
, StatusAction
)):
362 time
.sleep(options
['refresh_rate'])
365 except KeyboardInterrupt:
366 print('\n[Keyboard Interrupt]', file=sys
.stderr
)
369 class NoSuchActionError(Exception):
372 class NoSuchAction(Action
):
373 def __call__(self
, twitter
, options
):
374 raise NoSuchActionError("No such action: %s" %(options
['action']))
376 class StatusAction(Action
):
377 def __call__(self
, twitter
, options
):
378 statuses
= self
.getStatuses(twitter
, options
)
379 sf
= get_formatter('status', options
)
380 for status
in statuses
:
381 statusStr
= sf(status
, options
)
382 if statusStr
.strip():
383 printNicely(statusStr
)
385 class SearchAction(Action
):
386 def __call__(self
, twitter
, options
):
387 # We need to be pointing at search.twitter.com to work, and it is less
388 # tangly to do it here than in the main()
389 twitter
.domain
="search.twitter.com"
391 # We need to bypass the TwitterCall parameter encoding, so we
392 # don't encode the plus sign, so we have to encode it ourselves
393 query_string
= "+".join(
395 for term
in options
['extra_args']])
397 results
= twitter
.search(q
=query_string
)['results']
398 f
= get_formatter('search', options
)
399 for result
in results
:
400 resultStr
= f(result
, options
)
401 if resultStr
.strip():
402 printNicely(resultStr
)
404 class AdminAction(Action
):
405 def __call__(self
, twitter
, options
):
406 if not (options
['extra_args'] and options
['extra_args'][0]):
407 raise TwitterError("You need to specify a user (screen name)")
408 af
= get_formatter('admin', options
)
410 user
= self
.getUser(twitter
, options
['extra_args'][0])
411 except TwitterError
as e
:
412 print("There was a problem following or leaving the specified user.")
413 print("You may be trying to follow a user you are already following;")
414 print("Leaving a user you are not currently following;")
415 print("Or the user may not exist.")
420 printNicely(af(options
['action'], user
))
422 class ListsAction(StatusAction
):
423 def getStatuses(self
, twitter
, options
):
424 if not options
['extra_args']:
425 raise TwitterError("Please provide a user to query for lists")
427 screen_name
= options
['extra_args'][0]
429 if not options
['extra_args'][1:]:
430 lists
= twitter
.user
.lists(user
=screen_name
)['lists']
432 printNicely("This user has no lists.")
434 lf
= get_formatter('lists', options
)
435 printNicely(lf(list))
438 return reversed(twitter
.user
.lists
.list.statuses(
439 user
=screen_name
, list=options
['extra_args'][1]))
442 class MyListsAction(ListsAction
):
443 def getStatuses(self
, twitter
, options
):
444 screen_name
= twitter
.account
.verify_credentials()['screen_name']
445 options
['extra_args'].insert(0, screen_name
)
446 return ListsAction
.getStatuses(self
, twitter
, options
)
449 class FriendsAction(StatusAction
):
450 def getStatuses(self
, twitter
, options
):
451 return reversed(twitter
.statuses
.friends_timeline(count
=options
["length"]))
453 class PublicAction(StatusAction
):
454 def getStatuses(self
, twitter
, options
):
455 return reversed(twitter
.statuses
.public_timeline(count
=options
["length"]))
457 class RepliesAction(StatusAction
):
458 def getStatuses(self
, twitter
, options
):
459 return reversed(twitter
.statuses
.replies(count
=options
["length"]))
461 class FollowAction(AdminAction
):
462 def getUser(self
, twitter
, user
):
463 return twitter
.friendships
.create(id=user
)
465 class LeaveAction(AdminAction
):
466 def getUser(self
, twitter
, user
):
467 return twitter
.friendships
.destroy(id=user
)
469 class SetStatusAction(Action
):
470 def __call__(self
, twitter
, options
):
471 statusTxt
= (" ".join(options
['extra_args'])
472 if options
['extra_args']
473 else str(input("message: ")))
475 ptr
= re
.compile("@[\w_]+")
477 s
= ptr
.match(statusTxt
)
478 if s
and s
.start() == 0:
479 replies
.append(statusTxt
[s
.start():s
.end()])
480 statusTxt
= statusTxt
[s
.end()+1:]
483 replies
= " ".join(replies
)
484 if len(replies
) >= 140:
491 limit
= 140 - len(replies
)
492 if len(statusTxt
) > limit
:
493 end
= string
.rfind(statusTxt
, ' ', 0, limit
)
496 splitted
.append(" ".join((replies
,statusTxt
[:end
])))
497 statusTxt
= statusTxt
[end
:]
499 for status
in splitted
:
500 twitter
.statuses
.update(status
=status
)
502 class TwitterShell(Action
):
504 def render_prompt(self
, prompt
):
505 '''Parses the `prompt` string and returns the rendered version'''
506 prompt
= prompt
.strip("'").replace("\\'","'")
507 for colour
in ansi
.COLOURS_NAMED
:
508 if '[%s]' %(colour) in prompt
:
509 prompt
= prompt
.replace(
510 '[%s]' %(colour), ansi
.cmdColourNamed(colour
))
511 prompt
= prompt
.replace('[R]', ansi
.cmdReset())
514 def __call__(self
, twitter
, options
):
515 prompt
= self
.render_prompt(options
.get('prompt', 'twitter> '))
517 options
['action'] = ""
519 args
= input(prompt
).split()
520 parse_args(args
, options
)
521 if not options
['action']:
523 elif options
['action'] == 'exit':
525 elif options
['action'] == 'shell':
526 print('Sorry Xzibit does not work here!', file=sys
.stderr
)
528 elif options
['action'] == 'help':
529 print('''\ntwitter> `action`\n
530 The Shell Accepts all the command line actions along with:
532 exit Leave the twitter shell (^D may also be used)
534 Full CMD Line help is appended below for your convinience.''', file=sys
.stderr
)
535 Action()(twitter
, options
)
536 options
['action'] = ''
537 except NoSuchActionError
as e
:
538 print(e
, file=sys
.stderr
)
539 except KeyboardInterrupt:
540 print('\n[Keyboard Interrupt]', file=sys
.stderr
)
542 print(file=sys
.stderr
)
543 leaving
= self
.ask(subject
='Leave')
545 print('Excellent!', file=sys
.stderr
)
549 class PythonPromptAction(Action
):
550 def __call__(self
, twitter
, options
):
553 smrt_input(globals(), locals())
557 class HelpAction(Action
):
558 def __call__(self
, twitter
, options
):
561 class DoNothingAction(Action
):
562 def __call__(self
, twitter
, options
):
565 class RateLimitStatus(Action
):
566 def __call__(self
, twitter
, options
):
567 rate
= twitter
.account
.rate_limit_status()
568 print("Remaining API requests: %s / %s (hourly limit)" % (rate
['remaining_hits'], rate
['hourly_limit']))
569 print("Next reset in %ss (%s)" % (int(rate
['reset_time_in_seconds']-time
.time()),
570 time
.asctime(time
.localtime(rate
['reset_time_in_seconds']))))
573 'authorize' : DoNothingAction
,
574 'follow' : FollowAction
,
575 'friends' : FriendsAction
,
576 'list' : ListsAction
,
577 'mylist' : MyListsAction
,
579 'leave' : LeaveAction
,
580 'public' : PublicAction
,
581 'pyprompt' : PythonPromptAction
,
582 'replies' : RepliesAction
,
583 'search' : SearchAction
,
584 'set' : SetStatusAction
,
585 'shell' : TwitterShell
,
586 'rate' : RateLimitStatus
,
589 def loadConfig(filename
):
590 options
= dict(OPTIONS
)
591 if os
.path
.exists(filename
):
592 cp
= SafeConfigParser()
594 for option
in ('format', 'prompt'):
595 if cp
.has_option('twitter', option
):
596 options
[option
] = cp
.get('twitter', option
)
599 def main(args
=sys
.argv
[1:]):
602 parse_args(args
, arg_options
)
603 except GetoptError
as e
:
604 print("I can't do that, %s." %(e), file=sys
.stderr
)
605 print(file=sys
.stderr
)
608 config_path
= os
.path
.expanduser(
609 arg_options
.get('config_filename') or OPTIONS
.get('config_filename'))
610 config_options
= loadConfig(config_path
)
612 # Apply the various options in order, the most important applied last.
613 # Defaults first, then what's read from config file, then command-line
615 options
= dict(OPTIONS
)
616 for d
in config_options
, arg_options
:
617 for k
,v
in list(d
.items()):
620 if options
['refresh'] and options
['action'] not in (
621 'friends', 'public', 'replies'):
622 print("You can only refresh the friends, public, or replies actions.", file=sys
.stderr
)
623 print("Use 'twitter -h' for help.", file=sys
.stderr
)
626 oauth_filename
= os
.path
.expanduser(options
['oauth_filename'])
628 if (options
['action'] == 'authorize'
629 or not os
.path
.exists(oauth_filename
)):
631 "the Command-Line Tool", CONSUMER_KEY
, CONSUMER_SECRET
,
632 options
['oauth_filename'])
634 oauth_token
, oauth_token_secret
= read_token_file(oauth_filename
)
638 oauth_token
, oauth_token_secret
, CONSUMER_KEY
, CONSUMER_SECRET
),
639 secure
=options
['secure'],
641 domain
='api.twitter.com')
644 Action()(twitter
, options
)
645 except NoSuchActionError
as e
:
646 print(e
, file=sys
.stderr
)
648 except TwitterError
as e
:
649 print(str(e
), file=sys
.stderr
)
650 print("Use 'twitter -h' for help.", file=sys
.stderr
)