]> jfr.im git - z_archive/twitter.git/blob - twitter/cmdline.py
command line tool
[z_archive/twitter.git] / twitter / cmdline.py
1 """
2 USAGE:
3
4 twitter [action] [options]
5
6 ACTIONS:
7
8 friends get latest tweets from your friends (default action)
9 public get latest public tweets
10 set set your twitter status
11
12 OPTIONS:
13
14 -e --email <email> your email to login to twitter
15 -p --password <password> your twitter password
16 """
17
18 import sys
19 from getopt import getopt
20
21 from api import Twitter, TwitterError
22
23 options = {
24 'email': None,
25 'password': None,
26 'action': 'friends',
27 'forever': False,
28 'refresh': 600,
29 'extra_args': []
30 }
31
32 def parse_args(args, options):
33 long_opts = ['email', 'password', 'help']
34 short_opts = "e:p:h?"
35 opts, options['extra_args'] = getopt(args, short_opts, long_opts)
36
37 for opt, arg in opts:
38 if opt in ('-e', '--email'):
39 options['email'] = arg
40 elif opt in ('-p', '--password'):
41 options['password'] = arg
42 elif opt in ('-?', '-h', '--help'):
43 print __doc__
44 sys.exit(0)
45
46 class StatusFormatter(object):
47 def __call__(self, status):
48 return u"%s: %s" %(
49 status['user']['screen_name'], status['text'])
50
51 def no_action(twitter, options):
52 print >> sys.stderr, "No such action: ", options['action']
53 sys.exit(1)
54
55 def action_friends(twitter, options):
56 statuses = reversed(twitter.statuses.friends_timeline())
57 sf = StatusFormatter()
58 for status in statuses:
59 print sf(status)
60
61 def action_public(twitter, options):
62 statuses = reversed(twitter.statuses.public_timeline())
63 sf = StatusFormatter()
64 for status in statuses:
65 print sf(status)
66
67 def action_set_status(twitter, options):
68 twitter.statuses.update(
69 status=" ".join(options['extra_args']))
70
71 actions = {
72 'friends': action_friends,
73 'public': action_public,
74 'set': action_set_status,
75 }
76
77 def main():
78 args = sys.argv[1:]
79 if args and args[0][0] != "-":
80 options['action'] = args[0]
81 args = args[1:]
82 parse_args(args, options)
83 twitter = Twitter(options['email'], options['password'])
84 action = actions.get(options['action'], no_action)
85 try:
86 action(twitter, options)
87 except TwitterError, e:
88 print >> sys.stderr, e.message
89 print >> sys.stderr, "Use 'twitter -h' for help."
90 sys.exit(1)