Skip to content

Instantly share code, notes, and snippets.

@the-frey
Last active December 14, 2015 01:59
Show Gist options
  • Save the-frey/5010126 to your computer and use it in GitHub Desktop.
Save the-frey/5010126 to your computer and use it in GitHub Desktop.
Again inspired by the Codecademy Twitter API lesson, this is a way of checking Tweets that mention you via the command line (assuming you have set up an app for this very purpose). Pretty simple stuff, pretty-prints the response too.
require 'rubygems'
require 'oauth'
require 'json'
#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.
CONSUMER_KEY1 = "" #consumer key
CONSUMER_KEY2 = "" #consumer secret
ACCESS_TOKEN1 = "" #access token
ACCESS_TOKEN2 = "" #access secret
consumer_key = OAuth::Consumer.new(CONSUMER_KEY1,CONSUMER_KEY2)
access_token = OAuth::Token.new(ACCESS_TOKEN1,ACCESS_TOKEN2)
# All requests will be sent to this server.
#Make sure you put your username in the hash.
baseurl = "https://api.twitter.com"
query = URI.encode_www_form(
"screen_name" => "put_your_username_here",
"count" => "10",
"contributor_details" => true
)
# The verify credentials endpoint returns a 200 status if
# the request is signed correctly.
address = URI("#{baseurl}/1.1/statuses/mentions_timeline.json?#{query}")
def print_mentions(tweets)
#puts JSON.pretty_generate(tweets)
tweets.each do |t|
output = ""
output << "#{t["user"]["name"]} "
output << "(#{t["user"]["screen_name"]}) "
output << "#{t["created_at"]}: \n"
output << "#{t["text"]}\n\n"
output << "--- \n\n"
puts output
end
end
# Set up Net::HTTP to use SSL, which is required by Twitter.
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)
# Build the request and authorize it with OAuth.
request = Net::HTTP::Get.new address.request_uri
request.oauth! http, consumer_key, access_token
# Issue the request and return the response.
http.start
response = http.request request
tweets = nil
if response.code == '200'
tweets = JSON.parse(response.body)
print_mentions(tweets)
else
puts "Failed, response #{response.code}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment