how can I capture response from twitter.com? ( ruby + twitter gem) - ruby

how can I capture response from twitter.com? To make sure that everything went ok?
I am using ruby and ruby twitter gem and the my code is basically like that
oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')
client = Twitter::Base.new(oauth)
client.update('Heeeyyyyoooo from Twitter Gem!')

The update twitter api method will send back a response that will let you know if everything went okay. It can respond in either json or xml, I'm sure the twitter gem is using one or the other as a default. You need to save the return value to a variable and parse it, if you have a status id in there then it worked. Try using a token or secret to check what happens when it errors. I would suggest changing your last line to this
ret = client.update('Heeeyyyyoooo from Twitter Gem!')
and then add this line below that to check out what you got back
puts ret.inspect
or
logger.info ret.inspect
or your choice of logging method
[Edit]
It looked like the twitter gem hides the twitter api's actual response from you, parses it for you and just returns you the relevant bits. in the case of the update method it just returns you the id of your new tweet. you can view the id like this
puts ret.id
If you use another library to connect to the twitter api and need to parse xml or json responses then then the rest of this answer may be what you are looking for.
[/Edit]
If you are not using a gem that parses twitter api responses for you then you will need to use something to parse the twitter api's responses into data that you can do something with. There are tons of ways to do this depending on what format you want to parse (json or xml)
My preferences:
XML : Hpricot : gem install hpricot : http://github.com/hpricot/hpricot
json : json : gem install json : http://github.com/flori/json
Here is more information on what the twitter api update method returns: http://apiwiki.twitter.com/Twitter-REST-API-Method:-statuses%C2%A0update

This worked for me...
begin
resp = Twitter.update(params[:message])
rescue Exception => e
# e.message contains the twitter response
end

Related

Ruby Script using Octokit: Making API Calls

I am trying to create a script that gets a list of all repositories from GitHub. GitHub has a ruby gem called Octokit that I am trying to utilize, but I am a little lost.
The API has a reference here. It shows that I can get this response using a GET request. I am trying to figure out how to perform this using the Octokit Gem.
I may be completely off base with this question as I am new to Ruby, but I'd appreciate some steps showing how this can be completed. If I should not be using Octokit for this, a recommendation for creating HTTP Requests and Parsing the appropriate JSON response would be appreciated as well.
The Code I have so far:
#!/usr/bin/ruby
require 'Octokit'
client = Octokit::Client.new \
:login => '',
:password => ''
user = client.user
user.login
Following along with the code you already wrote, you can get all of the repositories for the user who's credentials you're using when authenticating the client with:
client.repositories
You can also get the public repositories of another user by passing their login as an argument:
client.repositories('username_here')

Attempting a PUT to Google Groups API using OAuth2 gem and Ruby

I'm trying to do a PUT call on a Google Groups API using Ruby and the OAuth2 GEM. I've managed to authenticate OK, and the GET call works properly, but I can't seem to get the call to use the PUT method. I thought the following would work, since OAuth2 uses Faraday, but I just keep getting the 400 message back, with an indication that something's "required":
data = access_token.put('https://www.googleapis.com/groups/v1/groups/{email address}?alt=json').parsed do |request|
request.params['email'] = "{email address}"
end
Has anyone got a working example of passing parameters to a PUT request?
OK. Looks like the ".parsed" was interfering with the call here's what works, with some additions to the request object:
response = access_token.put('https://www.googleapis.com/groups/v1/groups/{email address}') do |request|
request.headers['Content-Type'] = 'application/json'
request.body='{"email": "{email address}"}'
end
# check this
puts response.status
# works if it's 200

Why does Google's Custom Search API say that I'm missing an access token when using the Ruby client?

I'm trying to use Google's Custom Search API through the Google API Ruby client. I have setup my API key through the Google API console, and have also created my CSE. Based on the documentation, it seems that, as long as I provide an API key (which I am doing), I shouldn't need an OAuth2 authentication token to call the list method. However, when I try to execute the code below, I get the following error:
ArgumentError: Missing access token.
What am I missing? Here's my code:
# create client
client = Google::APIClient.new
# Fetch discovery doc
search = client.discovered_api('custom search')
# Call list method
response = client.execute(
search.cse.list, 'key' => '<my API key>', 'cx' => '<my CSE id>', 'alt' => 'json', 'q' => 'hello world'
)
I believe this is in fact a bug in the client (it's in alpha). After fiddling with it a little more, I've found a workaround:
just after creating the client object, assign it a "dummy" access token:
client.authorization.access_token = '123'
then you can call the search.cse.list method without getting the 'ArgumentError: Missing access token.' error.
If you're just after using Google CSE with ruby, try google-cse. I just built the gem, although I've been using it for a while privately. Much easier to work with than the alpha client
I found out that adding client.retries = 3 to my code solves this problem.
With the current version of the gem (0.7.1), you need to set the authorization to nil in addition to setting the key:
require 'google/api_client'
client = Google::APIClient.new
client.key = ENV['GOOGLE_API_KEY']
client.authorization = nil
client.execute ...

Fetching signed_request in a Facebook App with Ruby/Sinatra and the Rest-Graph gem

I've built a Facebook app using Sinatra and the Rest-Graph gem. Now I would like to embed the app as an iframe tab in a Facebook Page.
To do that, I need to fetch data from the signed_request sent to my app by Facebook.
The Rest-Graph gem states the following feature on its Github page:
Utility to extract access_token and
check sig in cookies/signed_request
I couldn't find any documentation on how to use this "utility". Can you point me to some documentation or even better, give me an example on how this is used with Ruby/Sinatra?
Nearly all of the Graph API libraries that are available deal with signed_request in a similar way. Rest-Graph has a parse_signed_request method (Rest-Graph/lib/core.rb) that you can call in Sinatra.
I'm using Koala for this with Sinatra, and it works as advertised:
oauth = Koala::Facebook::OAuth.new(APP_ID, APP_CODE)
signed_request = oauth.parse_signed_request(params["signed_request"])
You get back a hash of the JSON object that Facebook posts:
{
"algorithm"=>"HMAC-SHA256",
"issued_at"=>1303883452,
"user"=>
{
"country"=>"us",
"locale"=>"en_US"
},
"user_id"=>"100002364226618"
}
rest-graph makes it pretty easy, too. Just tested this in a Sinatra app. Works perfectly:
rg = RestGraph.new( :app_id => APP_ID, :secret => APP_SECRET)
parsed_request = rg.parse_signed_request!(params["signed_request"])
Lemme know if that doesn't work for you.
I just got a response to this question from "cardinalblue", the developer of the Rest-Graph gem. This little example was exactly what I was looking for:
require 'sinatra'
require 'rest-graph'
app_id = '123'
secret = 'abc'
config = {:app_id => app_id,
:secret => secret}
post '/' do
rg = RestGraph.new(config)
rg.parse_signed_request!(params['signed_request'])
"#{rg.get('me').inspect.gsub('<', '<')}\n"
end
run Sinatra::Application
Sidenote: In case you're building something similar, please note the post '/' do. Facebook Pages fetch your page using a POST request instead of a GET.

Issues POSTing XML to OAuth and Signature Invalid with Ruby OAuth Gem

[Cross-posted from the OAuth Ruby Google Group. If you couldn't help me there, don't worry bout it]
I'm working on integrating a project with TripIt's OAuth API
and am running into a weird issue.
I authenticate fine, I store and retrieve the token/secret for a given
user with no problem, I can even make GET requests to a number of
services using the gem. But when I try using the one service I need
POST for, I'm getting a 401 "invalid signature" response.
Perhaps I'm not understanding how to pass in data to the AccessToken's
post method, so here's a sample of my code:
xml = <<-XML
<Request>
<Trip>
<start_date>2008-12-09</start_date>
<end_date>2008-12-27</end_date>
<primary_location>New York, NY</primary_location>
</Trip>
</Request>
XML`
response = access_token.post('/v1/create', {:xml => xml},
{'Content-Type' => 'application/x-www-form-urlencoded'})
I've tried this with and without escaping the xml string before hand.
The guys at TripIt seemed to think that perhaps the xml param wasn't
getting included in the signature_base_string, but when I output that
(from lib/signature/base.rb) I see:
POST&https%3A%2F%2Fapi.tripit.com%2Fv1%2Fcreate&oauth_consumer_key
%3D%26oauth_nonce
%3Djs73Y9caeuffpmPVc6lqxhlFN3Qpj7OhLcfBTYv8Ww%26oauth_signature_method
%3DHMAC-SHA1%26oauth_timestamp%3D1252011612%26oauth_token
%3D%26oauth_version%3D1.0%26xml%3D%25253CRequest%25253E
%25250A%252520%252520%25253CTrip%25253E%25250A
%252520%252520%252520%252520%25253Cstart_date%25253E2008-12-09%25253C
%252Fstart_date%25253E%25250A
%252520%252520%252520%252520%25253Cend_date%25253E2008-12-27%25253C
%252Fend_date%25253E%25250A
%252520%252520%252520%252520%25253Cprimary_location%25253ENew
%252520York%252C%252520NY%25253C%252Fprimary_location%25253E%25250A
%252520%252520%25253C%252FTrip%25253E%25250A%25253C%252FRequest%25253E
%25250A
This seems to be correct to me.
I output signature (from the same file) and the output doesn't match
the oauth_signature param of the Auth header in lib/client/
net_http.rb. It's been URL-encoded in the auth header. Is this
correct?
Anyone know if the gem is broken/if there's a fix somewhere? I'm finding it hard to trace through some of the code.
Your oauth_token is empty. Not familiar with the protocol, is that ok?
Once you include the correct token, please also remember to use token_secret in the signing.

Resources