+
+class NoSuchAction(Action):
+ def __call__(self, twitter, options):
+ raise NoSuchActionError("No such action: %s" %(options['action']))
+
+class StatusAction(Action):
+ def __call__(self, twitter, options):
+ statuses = self.getStatuses(twitter, options)
+ sf = get_formatter('status', options)
+ for status in statuses:
+ statusStr = sf(status, options)
+ if statusStr.strip():
+ printNicely(statusStr)
+
+class SearchAction(Action):
+ def __call__(self, twitter, options):
+ # We need to be pointing at search.twitter.com to work, and it is less
+ # tangly to do it here than in the main()
+ twitter.domain="search.twitter.com"
+ twitter.uriparts=()
+ # We need to bypass the TwitterCall parameter encoding, so we
+ # don't encode the plus sign, so we have to encode it ourselves
+ query_string = "+".join(
+ [quote(term)
+ for term in options['extra_args']])
+
+ results = twitter.search(q=query_string)['results']
+ f = get_formatter('search', options)
+ for result in results:
+ resultStr = f(result, options)
+ if resultStr.strip():
+ printNicely(resultStr)
+
+class AdminAction(Action):
+ def __call__(self, twitter, options):
+ if not (options['extra_args'] and options['extra_args'][0]):
+ raise TwitterError("You need to specify a user (screen name)")
+ af = get_formatter('admin', options)
+ try:
+ user = self.getUser(twitter, options['extra_args'][0])
+ except TwitterError as e:
+ print("There was a problem following or leaving the specified user.")
+ print("You may be trying to follow a user you are already following;")
+ print("Leaving a user you are not currently following;")
+ print("Or the user may not exist.")
+ print("Sorry.")
+ print()
+ print(e)
+ else:
+ printNicely(af(options['action'], user))
+
+class ListsAction(StatusAction):
+ def getStatuses(self, twitter, options):
+ if not options['extra_args']:
+ raise TwitterError("Please provide a user to query for lists")
+
+ screen_name = options['extra_args'][0]
+
+ if not options['extra_args'][1:]:
+ lists = twitter.user.lists(user=screen_name)['lists']
+ if not lists:
+ printNicely("This user has no lists.")
+ for list in lists:
+ lf = get_formatter('lists', options)
+ printNicely(lf(list))
+ return []
+ else:
+ return reversed(twitter.user.lists.list.statuses(
+ user=screen_name, list=options['extra_args'][1]))
+
+
+class MyListsAction(ListsAction):
+ def getStatuses(self, twitter, options):
+ screen_name = twitter.account.verify_credentials()['screen_name']
+ options['extra_args'].insert(0, screen_name)
+ return ListsAction.getStatuses(self, twitter, options)
+
+
+class FriendsAction(StatusAction):
+ def getStatuses(self, twitter, options):
+ return reversed(twitter.statuses.friends_timeline(count=options["length"]))
+
+class PublicAction(StatusAction):
+ def getStatuses(self, twitter, options):
+ return reversed(twitter.statuses.public_timeline(count=options["length"]))
+
+class RepliesAction(StatusAction):
+ def getStatuses(self, twitter, options):
+ return reversed(twitter.statuses.replies(count=options["length"]))
+
+class FollowAction(AdminAction):
+ def getUser(self, twitter, user):
+ return twitter.friendships.create(id=user)
+
+class LeaveAction(AdminAction):
+ def getUser(self, twitter, user):
+ return twitter.friendships.destroy(id=user)
+
+class SetStatusAction(Action):
+ def __call__(self, twitter, options):
+ statusTxt = (" ".join(options['extra_args'])
+ if options['extra_args']
+ else str(input("message: ")))
+ replies = []
+ ptr = re.compile("@[\w_]+")
+ while statusTxt:
+ s = ptr.match(statusTxt)
+ if s and s.start() == 0:
+ replies.append(statusTxt[s.start():s.end()])
+ statusTxt = statusTxt[s.end()+1:]
+ else:
+ break
+ replies = " ".join(replies)
+ if len(replies) >= 140:
+ # just go back
+ statusTxt = replies
+ replies = ""
+
+ splitted = []
+ while statusTxt:
+ limit = 140 - len(replies)
+ if len(statusTxt) > limit:
+ end = string.rfind(statusTxt, ' ', 0, limit)
+ else:
+ end = limit
+ splitted.append(" ".join((replies,statusTxt[:end])))
+ statusTxt = statusTxt[end:]
+
+ for status in splitted:
+ twitter.statuses.update(status=status)
+
+class TwitterShell(Action):
+
+ def render_prompt(self, prompt):
+ '''Parses the `prompt` string and returns the rendered version'''
+ prompt = prompt.strip("'").replace("\\'","'")
+ for colour in ansi.COLOURS_NAMED:
+ if '[%s]' %(colour) in prompt:
+ prompt = prompt.replace(
+ '[%s]' %(colour), ansi.cmdColourNamed(colour))
+ prompt = prompt.replace('[R]', ansi.cmdReset())
+ return prompt
+
+ def __call__(self, twitter, options):
+ prompt = self.render_prompt(options.get('prompt', 'twitter> '))
+ while True:
+ options['action'] = ""
+ try:
+ args = input(prompt).split()
+ parse_args(args, options)
+ if not options['action']:
+ continue
+ elif options['action'] == 'exit':
+ raise SystemExit(0)
+ elif options['action'] == 'shell':
+ print('Sorry Xzibit does not work here!', file=sys.stderr)
+ continue
+ elif options['action'] == 'help':
+ print('''\ntwitter> `action`\n
+ The Shell Accepts all the command line actions along with:
+
+ exit Leave the twitter shell (^D may also be used)
+
+ Full CMD Line help is appended below for your convinience.''', file=sys.stderr)
+ Action()(twitter, options)
+ options['action'] = ''
+ except NoSuchActionError as e:
+ print(e, file=sys.stderr)
+ except KeyboardInterrupt:
+ print('\n[Keyboard Interrupt]', file=sys.stderr)
+ except EOFError:
+ print(file=sys.stderr)
+ leaving = self.ask(subject='Leave')
+ if not leaving:
+ print('Excellent!', file=sys.stderr)
+ else:
+ raise SystemExit(0)
+
+class PythonPromptAction(Action):
+ def __call__(self, twitter, options):
+ try:
+ while True:
+ smrt_input(globals(), locals())
+ except EOFError:
+ pass
+
+class HelpAction(Action):
+ def __call__(self, twitter, options):
+ print(__doc__)
+
+class DoNothingAction(Action):
+ def __call__(self, twitter, options):
+ pass
+
+class RateLimitStatus(Action):
+ def __call__(self, twitter, options):
+ rate = twitter.account.rate_limit_status()
+ print("Remaining API requests: %s / %s (hourly limit)" % (rate['remaining_hits'], rate['hourly_limit']))
+ print("Next reset in %ss (%s)" % (int(rate['reset_time_in_seconds']-time.time()),
+ time.asctime(time.localtime(rate['reset_time_in_seconds']))))
+
+actions = {
+ 'authorize' : DoNothingAction,
+ 'follow' : FollowAction,
+ 'friends' : FriendsAction,
+ 'list' : ListsAction,
+ 'mylist' : MyListsAction,
+ 'help' : HelpAction,
+ 'leave' : LeaveAction,
+ 'public' : PublicAction,
+ 'pyprompt' : PythonPromptAction,
+ 'replies' : RepliesAction,
+ 'search' : SearchAction,
+ 'set' : SetStatusAction,
+ 'shell' : TwitterShell,
+ 'rate' : RateLimitStatus,
+}
+
+def loadConfig(filename):
+ options = dict(OPTIONS)
+ if os.path.exists(filename):
+ cp = SafeConfigParser()
+ cp.read([filename])
+ for option in ('format', 'prompt'):
+ if cp.has_option('twitter', option):
+ options[option] = cp.get('twitter', option)
+ return options
+
+def main(args=sys.argv[1:]):
+ arg_options = {}
+ try:
+ parse_args(args, arg_options)
+ except GetoptError as e:
+ print("I can't do that, %s." %(e), file=sys.stderr)
+ print(file=sys.stderr)
+ raise SystemExit(1)
+
+ config_path = os.path.expanduser(
+ arg_options.get('config_filename') or OPTIONS.get('config_filename'))
+ config_options = loadConfig(config_path)
+
+ # Apply the various options in order, the most important applied last.
+ # Defaults first, then what's read from config file, then command-line
+ # arguments.
+ options = dict(OPTIONS)
+ for d in config_options, arg_options:
+ for k,v in list(d.items()):
+ if v: options[k] = v
+
+ if options['refresh'] and options['action'] not in (
+ 'friends', 'public', 'replies'):
+ print("You can only refresh the friends, public, or replies actions.", file=sys.stderr)
+ print("Use 'twitter -h' for help.", file=sys.stderr)
+ return 1
+
+ oauth_filename = os.path.expanduser(options['oauth_filename'])
+
+ if (options['action'] == 'authorize'
+ or not os.path.exists(oauth_filename)):
+ oauth_dance(
+ "the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET,
+ options['oauth_filename'])
+
+ oauth_token, oauth_token_secret = read_token_file(oauth_filename)
+
+ twitter = Twitter(
+ auth=OAuth(
+ oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
+ secure=options['secure'],
+ api_version='1',
+ domain='api.twitter.com')
+
+ try:
+ Action()(twitter, options)
+ except NoSuchActionError as e:
+ print(e, file=sys.stderr)
+ raise SystemExit(1)
+ except TwitterError as e:
+ print(str(e), file=sys.stderr)
+ print("Use 'twitter -h' for help.", file=sys.stderr)
+ raise SystemExit(1)