Skip to content

Instantly share code, notes, and snippets.

@the-frey
Created February 21, 2013 14:10
Show Gist options
  • Save the-frey/5004952 to your computer and use it in GitHub Desktop.
Save the-frey/5004952 to your computer and use it in GitHub Desktop.
A simple program to tweet from the command line. Assuming like me you call this file tweet.rb, simply use: ruby tweet.rb to run. The structure is taken from the Codecademy Twitter API track - check it out, it's pretty cool.
require 'rubygems'
require 'oauth'
require 'json'
#install the above dependencies with rubygems -
#gem install dependency
#You will need these for OAuth. The second of each should be your secret value. The naming simply refects the order in the two OAuth class constructors. Create an app in the Twitter dev centre to get these values, making sure you select the option for 'read and write access'.
CONSUMER_KEY1 = "" #consumer key
CONSUMER_KEY2 = "" #consumer secret
ACCESS_TOKEN1 = "" #access token
ACCESS_TOKEN2 = "" #access secret
puts "What do you want to tweet?"
print "> "
tweet_text = STDIN.gets.chomp
if tweet_text.length > 140
tweet_invalid = true
abort("The tweet is too long (#{tweet_text.length}).")
end
consumer_key = OAuth::Consumer.new(CONSUMER_KEY1,CONSUMER_KEY2)
access_token = OAuth::Token.new(ACCESS_TOKEN1,ACCESS_TOKEN2)
baseurl = "https://api.twitter.com"
path = "/1.1/statuses/update.json"
address = URI("#{baseurl}#{path}")
request = Net::HTTP::Post.new address.request_uri
request.set_form_data(
"status" => "#{tweet_text}"
)
#Set up HTTP
http = Net::HTTP.new address.host, address.port
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
#Debugger
#puts http.set_debug_output($stderr)
#Issue the request
request.oauth! http, consumer_key, access_token
http.start
response = http.request request unless tweet_invalid == true
#Parse and print the tweet if the response code was 200
tweet = nil
if response.code == '200'
tweet = JSON.parse(response.body)
puts "Successfully posted Tweet: #{tweet["text"]}."
else
puts "Could not send the Tweet! " + "Code: #{response.code} \nBody: #{response.body}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment