]> jfr.im git - z_archive/twitter.git/blob - twitter/cmdline.py
Misc fixes for unicode
[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, 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 if extra_args:
47 options['action'] = extra_args[0]
48 options['extra_args'] = extra_args[1:]
49
50 class StatusFormatter(object):
51 def __call__(self, status):
52 return (u"%s: %s" %(
53 status['user']['screen_name'], status['text'])).encode(
54 sys.stdout.encoding, 'replace')
55
56 def no_action(twitter, options):
57 print >> sys.stderr, "No such action: ", options['action']
58 sys.exit(1)
59
60 def action_friends(twitter, options):
61 statuses = reversed(twitter.statuses.friends_timeline())
62 sf = StatusFormatter()
63 for status in statuses:
64 print sf(status)
65
66 def action_public(twitter, options):
67 statuses = reversed(twitter.statuses.public_timeline())
68 sf = StatusFormatter()
69 for status in statuses:
70 print sf(status)
71
72 def action_set_status(twitter, options):
73 twitter.statuses.update(
74 status=(u" ".join(options['extra_args'])).encode(
75 'utf8', 'replace'))
76
77 actions = {
78 'friends': action_friends,
79 'public': action_public,
80 'set': action_set_status,
81 }
82
83
84 def main():
85 return main_with_args(sys.argv[1:])
86
87 def main_with_args(args):
88 parse_args(args, options)
89 twitter = Twitter(options['email'], options['password'])
90 action = actions.get(options['action'], no_action)
91 try:
92 action(twitter, options)
93 except TwitterError, e:
94 print >> sys.stderr, e.message
95 print >> sys.stderr, "Use 'twitter -h' for help."
96 sys.exit(1)