Class: ConsoleTweet::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/console_tweet/cli.rb

Constant Summary collapse

AllowedMethods =

The allowed API methods

[:setup, :help, :status, :tweet, :timeline, :show, :replies]
ConsumerKey =

Twitter API details

'MvVdCyl6xCVtEUVdcp4rw'
ConsumerSecret =
'3xD0oy47WhWYUIBCU6QzcIBqsrAAL3KnYWKhd6ALk2k'
TOKEN_PATH =

Where to store the .twitter file

File.expand_path('~/.twitter')
NameColor =

Some colors used in the output

"\e[33m"
CommandColor =
"\e[36m"
DefaultColor =
"\e[0m"
ErrorColor =
"\e[31m"

Instance Method Summary collapse

Constructor Details

#initializeCLI

By default there are no arguments and no commands



26
27
28
29
# File 'lib/console_tweet/cli.rb', line 26

def initialize
  @commands = []
  @arguments = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(command, *arguments) ⇒ Object

Catch other methods



160
161
162
# File 'lib/console_tweet/cli.rb', line 160

def method_missing(command, *arguments)
  failtown "Unknown command: #{command}\n"
end

Instance Method Details

#failtown(message = nil) ⇒ Object

Show error message with help below it



154
155
156
157
# File 'lib/console_tweet/cli.rb', line 154

def failtown(message = nil)
  puts "#{ErrorColor}Uh-oh! #{message}#{DefaultColor}\n" if message
  help
end

#get_access_tokenObject

Prompt the user for a PIN using a request token, and see if we can successfully authenticate them



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/console_tweet/cli.rb', line 46

def get_access_token
  @client = TwitterOAuth::Client.new(:consumer_key => ConsumerKey, :consumer_secret => ConsumerSecret)
  request_token = @client.request_token
  # ask the user to visit the auth url
  puts "To authenticate your client, visit the URL: #{request_token.authorize_url}"
  open_link request_token.authorize_url
  # wait for the user to give us the PIN back
  print 'Enter PIN: '
  begin
    @client.authorize(request_token.token, request_token.secret, :oauth_verifier => self.class.get_input.chomp)
  rescue OAuth::Unauthorized
    false # Didn't get an access token
  end
end

#help(*args) ⇒ Object

Display help section



141
142
143
144
145
146
147
148
149
150
151
# File 'lib/console_tweet/cli.rb', line 141

def help(*args)
  puts "#{NameColor}console-tweet#{DefaultColor} by John Crepezzi <[email protected]>"
  puts 'http://github.com/seejohnrun/console-tweet'
  puts
  puts "#{CommandColor}twitter#{DefaultColor} View your timeline, since last view"
  puts "#{CommandColor}twitter setup#{DefaultColor} Setup your account"
  puts "#{CommandColor}twitter status#{DefaultColor} Get your most recent status" 
  puts "#{CommandColor}twitter tweet \"Hello World\"#{DefaultColor} Send out a tweet"
  puts "#{CommandColor}twitter show [username]#{DefaultColor} Show the timeline for a user"
  puts "#{CommandColor}twitter replies#{DefaultColor} Get the most recent @replies and mentions" 
end

#replies(*args) ⇒ Object

Returns the 20 most recent @replies / mentions



128
129
130
131
132
133
134
135
136
137
138
# File 'lib/console_tweet/cli.rb', line 128

def replies(*args)
  load_default_token
  return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
  # Only send since_id_replies to @client if it's not nil
  mentions = since_id_replies ? @client.mentions(:since_id => since_id_replies) : @client.mentions
  if mentions.any?
    print_tweets(mentions)
    # Save the last id as since_id
    self.since_id_replies = mentions.last['id']
  end
end

#setup(*args) ⇒ Object

Get the access token for the user and save it



116
117
118
119
120
121
122
123
124
125
# File 'lib/console_tweet/cli.rb', line 116

def setup(*args)
  # Keep trying to get the access token
  until @access_token = self.get_access_token
    print "Try again? [Y/n] "
    return false if self.class.get_input.downcase == 'n'
  end
  # When we finally get it, record it in a dotfile
  tokens = {:default => { :token => @access_token.token, :secret => @access_token.secret }}
  save_tokens(tokens)
end

#show(args) ⇒ Object

Get 20 most recent statuses of user, or specified user



95
96
97
98
99
100
101
102
103
104
# File 'lib/console_tweet/cli.rb', line 95

def show(args)
  # If we have no user to get, use the timeline instead
  return timeline(args) if args.nil? || args.count == 0
  target_user = args[0]
  # Get the timeline and print the tweets if we don't get an error
  load_default_token # for private tweets
  res = @client.user_timeline(:screen_name => target_user)
  return failtown("show :: #{res['error']}") if !res || res.include?('error')
  print_tweets(res)
end

#startObject

Get the commands from the command line (Somewhat primitive, will be expanded) TODO



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/console_tweet/cli.rb', line 33

def start
  ARGV.each do |arg|
    unless arg.index('-') === 0
      @commands << arg
    end
  end
  # get the first command as the method, and the rest of the commands as args
  method = @commands.empty? ? :timeline : @commands[0].to_sym
  return method_missing(method) unless AllowedMethods.include?(method)
  self.send(method, @commands[1..@commands.size])
end

#status(*args) ⇒ Object

Get the user’s most recent status



107
108
109
110
111
112
113
# File 'lib/console_tweet/cli.rb', line 107

def status(*args)
  load_default_token
  return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
  user = @client.info
  status = user['status']
  puts "#{user['name']} (at #{status['created_at']}) #{status['text']}" unless status.nil?
end

#timeline(*args) ⇒ Object

Display the user’s timeline



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/console_tweet/cli.rb', line 62

def timeline(*args)
  load_default_token
  return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
  # Only send since_id to @client if it's not nil
  home_timeline = since_id ? @client.home_timeline(:since_id => since_id) : @client.home_timeline
  if home_timeline.any?
    print_tweets(home_timeline)
    # Save the last id as since_id
    self.since_id = home_timeline.last['id']
  end
end

#tweet(*args) ⇒ Object

Send a tweet for the user



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/console_tweet/cli.rb', line 75

def tweet(*args)
  load_default_token
  # get it from them directly
  tweet_text = args.join(' ').strip
  # or let them append / or pipe
  tweet_text += (tweet_text.empty? ? '' : ' ') + STDIN.read unless STDIN.tty?
  # or let them get prompted for it
  if tweet_text.empty?
    print 'Tweet (Press return to finish): '
    tweet_text = STDIN.gets.strip
  end
  return failtown("Empty Tweet") if tweet_text.empty?
  return failtown("Tweet is too long!") if tweet_text.scan(/./mu).size > 140
  return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
  # actually post it
  @client.update(tweet_text)
  puts "Tweet Posted!"
end