]> jfr.im git - z_archive/twitter.git/blame - twitter/cmdline.py
irc bot (not yet working)
[z_archive/twitter.git] / twitter / cmdline.py
CommitLineData
7364ea65 1"""
5251ea48 2USAGE:
7364ea65 3
5251ea48 4 twitter [action] [options]
5
6ACTIONS:
7
8 friends get latest tweets from your friends (default action)
9 public get latest public tweets
10 set set your twitter status
11
12OPTIONS:
13
14 -e --email <email> your email to login to twitter
15 -p --password <password> your twitter password
0ea01db7 16 -r --refresh run this command forever, polling every once
17 in a while (default: every 5 minutes)
18 -R --refresh-rate <rate> set the refresh rate (in seconds)
19 -f --format <format> specify the output format for status updates
20
21FORMATS for the --format option
22
23 default one line per status
24 verbose multiple lines per status, more verbose status info
25 urls nothing but URLs. Dare you click them?
7364ea65 26"""
27
5251ea48 28import sys
0ea01db7 29import time
5251ea48 30from getopt import getopt
f068ff42 31from getpass import getpass
0ea01db7 32import re
5251ea48 33
34from api import Twitter, TwitterError
35
36options = {
37 'email': None,
38 'password': None,
39 'action': 'friends',
0ea01db7 40 'refresh': False,
41 'refresh_rate': 600,
42 'format': 'default',
5251ea48 43 'extra_args': []
44}
45
46def parse_args(args, options):
0ea01db7 47 long_opts = ['email', 'password', 'help', 'format', 'refresh',
48 'refresh-rate']
49 short_opts = "e:p:f:h?rR:"
ae1d86aa 50 opts, extra_args = getopt(args, short_opts, long_opts)
5251ea48 51
52 for opt, arg in opts:
53 if opt in ('-e', '--email'):
54 options['email'] = arg
55 elif opt in ('-p', '--password'):
56 options['password'] = arg
0ea01db7 57 elif opt in ('-f', '--format'):
58 options['format'] = arg
59 elif opt in ('-r', '--refresh'):
60 options['refresh'] = True
61 elif opt in ('-R', '--refresh-rate'):
62 options['refresh_rate'] = int(arg)
5251ea48 63 elif opt in ('-?', '-h', '--help'):
64 print __doc__
65 sys.exit(0)
ae1d86aa 66
67 if extra_args:
68 options['action'] = extra_args[0]
69 options['extra_args'] = extra_args[1:]
5251ea48 70
71class StatusFormatter(object):
72 def __call__(self, status):
f068ff42 73 return (u"%s %s" %(
0ea01db7 74 status['user']['screen_name'], status['text']))
5251ea48 75
f068ff42 76class VerboseStatusFormatter(object):
77 def __call__(self, status):
78 return (u"-- %s (%s) on %s\n%s\n" %(
79 status['user']['screen_name'],
80 status['user']['location'],
81 status['created_at'],
0ea01db7 82 status['text']))
f068ff42 83
0ea01db7 84class URLStatusFormatter(object):
85 urlmatch = re.compile(r'https?://\S+')
86 def __call__(self, status):
87 urls = self.urlmatch.findall(status['text'])
88 return u'\n'.join(urls) if urls else ""
89
90formatters = {
91 'default': StatusFormatter,
92 'verbose': VerboseStatusFormatter,
93 'urls': URLStatusFormatter
94}
f068ff42 95
0ea01db7 96def get_status_formatter(options):
97 sf = formatters.get(options['format'])
98 if (not sf):
99 raise TwitterError(
100 "Unknown formatter '%s'" %(options['format']))
101 return sf()
102
103class Action(object):
104 pass
105
106class NoSuchAction(Action):
107 def __call__(self, twitter, options):
108 print >> sys.stderr, "No such action: ", options['action']
109 sys.exit(1)
110
111class StatusAction(Action):
112 def __call__(self, twitter, options):
113 statuses = self.getStatuses(twitter)
114 sf = get_status_formatter(options)
115 for status in statuses:
116 statusStr = sf(status)
117 if statusStr.strip():
118 print statusStr.encode(sys.stdout.encoding, 'replace')
119
120class FriendsAction(StatusAction):
121 def getStatuses(self, twitter):
122 return reversed(twitter.statuses.friends_timeline())
5251ea48 123
0ea01db7 124class PublicAction(StatusAction):
125 def getStatuses(self, twitter):
126 return reversed(twitter.statuses.public_timeline())
127
128class SetStatusAction(Action):
129 def __call__(self, twitter, options):
772fbdd1 130 statusTxt = (u" ".join(options['extra_args'])
131 if options['extra_args']
132 else unicode(raw_input("message: ")))
133 status = (statusTxt.encode('utf8', 'replace'))
0ea01db7 134 twitter.statuses.update(status=status)
5251ea48 135
136actions = {
0ea01db7 137 'friends': FriendsAction,
138 'public': PublicAction,
139 'set': SetStatusAction,
5251ea48 140}
141
ae1d86aa 142
7364ea65 143def main():
ae1d86aa 144 return main_with_args(sys.argv[1:])
145
146def main_with_args(args):
5251ea48 147 parse_args(args, options)
0ea01db7 148 if options['refresh'] and options['action'] == 'set':
149 print >> sys.stderr, "You can't repeatedly set your status, silly"
150 print >> sys.stderr, "Use 'twitter -h' for help."
151 sys.exit(1)
f068ff42 152 if options['email'] and not options['password']:
153 options['password'] = getpass("Twitter password: ")
5251ea48 154 twitter = Twitter(options['email'], options['password'])
0ea01db7 155 action = actions.get(options['action'], NoSuchAction)()
5251ea48 156 try:
0ea01db7 157 doAction = lambda : action(twitter, options)
158 if (options['refresh']):
159 while True:
160 doAction()
161 time.sleep(options['refresh_rate'])
162 else:
163 doAction()
5251ea48 164 except TwitterError, e:
165 print >> sys.stderr, e.message
166 print >> sys.stderr, "Use 'twitter -h' for help."
167 sys.exit(1)
0ea01db7 168 except KeyboardInterrupt:
169 pass
170