[Twitter4R]Twitter::ForbiddenError - ruby

I'm new to Twitter4R and Ruby on Rails. I'm using Ruby 1.9.2, Rails 3.1 and Twitter4R v0.7.0.
I'm trying to get my friends list from Twitter.
twitter = Twitter::Client.new(oauth_access: { key: token, secret: token_secret})
#these lines works fine.
twitter.status(:post, "POST TEST!!!")
twitter.friend(:add, "xxxx_jp")
#this line will cause ForbiddenError
friends = twitter.my(:friends)
I've checked the following site for information.
http://twitter4r.rubyforge.org/rdoc/Twitter/Client.html
Update
I now added config/initializers/twitter4r.rb:
require 'twitter'
Twitter::Client.configure do |config|
config.oauth_consumer_token = consumer_key
config.oauth_consumer_secret = consumer_secret
end
When debugging, I see the consumer_key and consumer_secret in Twitter::Consumer on debug window. But methods that require authentication like my(:friends) do not work.
How do I avoid the ForbiddenError?

That looks like the authentication in Twitter::Client.new didn't actually work. Here's a presentation on OAuth by Twitter4R's creator Susan Potter:
http://www.slideshare.net/mbbx6spp/twitter4r-oauth

Related

Customize Instagram widget on a Dashing.io dashboard

I have set up a dashboard using dashing with a number of (mostly) existing widgets. That worked so far - see production dashboard here (work in progress).
Now I would like to have an Instagram widget that displays the n lastest images taken by username.
I have found a widget that will display images by long and lat and also was able to get my tokens configured, so I can talk to the Instagram API.
Here's the code of my current widget originally from #mjamieson's gist on github.
require 'instagram'
require 'rest-client'
require 'json'
# Instagram Client ID from http://instagram.com/developer
Instagram.configure do |config|
config.client_id = ENV['INSTAGRAM_CLIENT_ID']
config.client_secret = ENV['INSTAGRAM_CLIENT_SECRET']
end
# Latitude, Longitude for location
instadash_location_lat = '45.429522'
instadash_location_long = '-75.689613'
SCHEDULER.every '10m', :first_in => 0 do |job|
photos = Instagram.media_search(instadash_location_lat,instadash_location_long)
if photos
photos.map do |photo|
{ photo: "#{photo.images.low_resolution.url}" }
end
end
send_event('instadash', photos: photos)
end
I got this to work, but would like to modify the given API call to only display images taken by me / a user of my choice. Unfortunately I don't understand ruby or json enough to figure out what the Instagram API documentation wants me to do.
I found the following url
https://api.instagram.com/v1/users/{user-id}/media/recent/?access_token={acces-token}
and tried it (with my credentials filled in). It returned json data correctly including my images (among other data).
How can I modify the given code to display images by username instead of location?
Any help is greatly appreciated.
You'll need an access_token to get content from some user. Take a look at sample application on gem page.
It seems you need something like this:
# here we take access token from session, assuming you already got it
# sometime before and stored it there for future use
client = Instagram.client(:access_token => session[:access_token])
photos = client.user_recent_media
And this example how to get this access_token using OAuth2 browser authorization and sinatra app:
require "sinatra"
require "instagram"
enable :sessions
CALLBACK_URL = "http://localhost:4567/oauth/callback"
Instagram.configure do |config|
config.client_id = "YOUR_CLIENT_ID"
config.client_secret = "YOUR_CLIENT_SECRET"
# For secured endpoints only
#config.client_ips = '<Comma separated list of IPs>'
end
get "/" do
'Connect with Instagram'
end
get "/oauth/connect" do
redirect Instagram.authorize_url(:redirect_uri => CALLBACK_URL)
end
get "/oauth/callback" do
response = Instagram.get_access_token(params[:code], :redirect_uri => CALLBACK_URL)
session[:access_token] = response.access_token
redirect "/nav"
end
Solution
require 'sinatra'
require 'instagram'
# Instagram Client ID from http://instagram.com/developer
Instagram.configure do |config|
config.client_id = ENV['INSTAGRAM_CLIENT_ID']
config.client_secret = ENV['INSTAGRAM_CLIENT_SECRET']
config.access_token = ENV['INSTAGRAM_ACCESS_TOKEN']
end
user_id = ENV['INSTAGRAM_USER_ID']
SCHEDULER.every '2m', :first_in => 0 do |job|
photos = Instagram.user_recent_media("#{user_id}")
if photos
photos.map! do |photo|
{ photo: "#{photo.images.low_resolution.url}" }
end
end
send_event('instadash', photos: photos)
end
Explaination
1.) In addition to the client_id and client_secret I had defined before, I just needed to add my access_token to the Instagram.configure section.
2.) The SCHEDULER was correctly working, but needed to call Instagram.user_recent_media("#{user_id}") instead of Instagram.media_search(instadash_location_lat,instadash_location_long)
3.) To do that I had to set a second missing variable for user_id
Now the call gets recent media filtered by user ID and outputs it into the dashing widget.
Thanks for the participation and hints! That pointed me into the right direction of the documentation and helped me to figure it out myself.

Ruby google_drive gem Problems

https://github.com/gimite/google-drive-ruby
There seems to be an update on google docs. There is now an "Addon" function in NEW google docs. Has someone found a work around for new version of google docs and google_drive gem?
require 'google_drive'
session = GoogleDrive.login("username#gmail.com", "password")
# the key is found in the url of a google doc web address
# https://docs.google.com/a/pz7XtlQC-PYx-jrVMJErTcg#gid=0
ws = session.spreadsheet_by_key("pz7XtlQC-PYx-jrVMJErTcg").worksheets[0]
ws.rows
=> ERRORS
ws[1,1]
=> "test"
ws[1,1] = "hi"
ws.save()
=> ERRORS
does anyone have a workaround?
From the version 0.3.8 gem supports new Spreadsheets.
Also, you can try spreadsheer_by_url method.
For example:
require 'google_drive'
session = GoogleDrive.login("username#gmail.com", "password")
ws = session.spreadsheet_by_url('https://docs.google.com/a/pz7XtlQC-PYx-jrVMJErTcg#gid=0').worksheets[0]

Koala and Omniauth-twitter don't go together

I posted the same in github of Koala but noone answered to me so I put here.
So when I try to login with Twitter with Omniauth:
I, [2013-11-15T18:57:12.371006 #28412] INFO -- omniauth: (twitter) Request phase initiated.
127.0.0.1 - - [15/Nov/2013 18:57:13] "GET /auth/twitter HTTP/1.1" 500 144366 0.9355
I have also a Koala login to facebook I don't use Omniauth for Facebook I just use Omniauth for twitter, If I don't require Koala is ok, but if I have both it generates:
undefined method `[]=' for #<Koala::Facebook::OAuth:0x00000001b03348>
~>In oauth.rb line 31
I'm using 1.6.0 version of Koala and Sinatra.
My code is:
#Facebook
get '/loginfb' do
session['oauth'] = Koala::Facebook::OAuth.new($APP_ID, $APP_SECRET, "#{request.base_url}/callbackfb")
redirect session['oauth'].url_for_oauth_code(:permissions => ["publish_stream"])
end
get '/callbackfb' do
session['access_token'] = session['oauth'].get_access_token(params[:code])
registerUserFB() #Just register the user function
redirect '/accounts'
end
#Twitter
#By defualt logs in with /auth/twitter
get '/auth/twitter/callback' do
erb "<h1>#{params[:provider]}</h1><pre>#{JSON.pretty_generate(request.env['omniauth.auth'])}</pre>"
p auth['credentials']['token']
end
get '/auth/failure' do
erb "<h1>Authentication Failed:</h1><h3>message:<h3> <pre>#{params}</pre>"
end
Thanks guys in advance.
I used another gem for logging with twitter called twitter_oauth yo can find here
For use with sinatra is quite simple:
#Sinatra stuff
require 'twitter_oauth'
#more sinatra stuff
$CONSUMER_KEY = '32423...'
$CONSUMER_SECRET = '...adads...'
$CALLBACK_URL = 'http://....'
tw_client = TwitterOAuth::Client.new(
:consumer_key => $CONSUMER_KEY,
:consumer_secret => $CONSUMER_SECRET
)
$request_token = tw_client.request_token(:oauth_callback => $CALLBACK_URL)
#sinatra routes
get '/logintw' do
redirect $request_token.authorize_url
end
get '/callbacktw' do
#access_token = $request_token.get_access_token :oauth_verifier => params[:oauth_verifier]
p #access_token.params[:oauth_token]
p #access_token.params[:oauth_token_secret]
p #access_token.params[:screen_name]
p #access_token.params[:user_id]
redirect '/accounts'
end
#more sinatra routes
Is not the best solution but is one and for me works!
Thanks anyway.

Twitter REST API and ruby hashtag confusion

so I'm trying to set up a script to grab tweets so I can use them in my app. Currently I'm using Ruby 2.0.0 and the 1.1 Twitter API REST. Currently I'm not worried about storing the tweets in a database or anything I'm just simply trying to get the correct tweets into terminal. Here is my current code.
require 'twitter'
client = Twitter::REST::Client.new do |config|
config.consumer_key = "XXXXXXXXXXXXXXXXXX"
config.consumer_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
config.access_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
config.access_token_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
end
topics = ["#BreakingBad", "#Gameofthones"]
client.filter(:track => topics.join(",")) do |tweet|
puts tweet.text
endtag = options[:search]
My problem is that when I run the script I get flooded with just a mass of tweets in all different languages. Any help would be great. Thanks.

Writing autologin using Net::Http in Ruby

http://ruby-doc.org/stdlib-1.8.7/libdoc/net/http/rdoc/Net/HTTP.html
After reading the doc very carefully, I'm writing the following code snippet for the autologin feature of my program:
url = URI.parse('http://localhost/login.aspx')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'username'
The target page asks only the correct user name, no password is needed in order to login, the basic_auth method requires two parameters, user name and password, if I leave one out, I'll get the error, I tried to write it like this "req.basic_auth 'username', ''", but I still cannot login.
Could anyone kindly give me a hint?
more info:
I also tried req.basic_auth 'username', '', it didn't seem to be working, I know this because there's another line of line follow right after this one, which is basically doing auto form submission.
x = Net::HTTP.post_form(URI.parse("http://localhost/NewTask.aspx"), params)
puts x.body
And the puts result came back with the redirect to login page body.
You can consider using ruby mechanize gem. a login example will be much simpler(from official site), for this one, you will not need to do the agent cert and private key thing:
require 'rubygems'
require 'mechanize'
# create Mechanize instance
agent = Mechanize.new
# set the path of the certificate file
agent.cert = 'example.cer'
# set the path of the private key file
agent.key = 'example.key'
# get the login form & fill it out with the username/password
login_form = agent.get("http://example.com/login_page").form('Login')
login_form.Userid = 'TestUser'
login_form.Password = 'TestPassword'
# submit login form
agent.submit(login_form, login_form.buttons.first)

Resources