not able to get authentication token - ruby-on-rails

I tried to use twitter api with ruby for exact search. But because of new twitter api i am not able to access the json file.
this is link
https://api.twitter.com/1.1/search/tweets.json?q=%23superbowl&result_type=recent
Can you please tell me how to fetch json file.
I have posted my rb file , plz help
# http://ruby-doc.org/stdlib-2.0.0/libdoc/open-uri/rdoc/OpenURI.html
require 'open-uri'
# https://github.com/flori/json
require 'json'
# http://stackoverflow.com/questions/9008847/what-is-difference-between-p-and-pp
require 'pp'
require 'twitter'
#load 'twitter_config.rb'
#Create seprate config file.
#Encrprty ur keys using md5.
client = Twitter::REST::Client.new do |config|
config.consumer_key = "3OpBStixWSMAzBttp6UWON7QA"
config.consumer_secret = "MBmfQXoHLY61hYHzGYU8n69sQRQPheXJDejP1SKE2LBdgaqRg4"
config.access_token = "322718806-qScub4diRzggWUO9DaLKMVKwXZcgrqHD2OFbwQTr"
config.access_token_secret = "aWAIxQVnqF3nracQ0cC0HbRbSDxlCAaUIICorEAPlxIub"
end
# Construct the URL we'll be calling
print "please enter phrase you want to search"
phrase_value=gets.chomp;
#pets = File.open("https://api.twitter.com/1.1/search/tweets.json?q=#{phrase_value}", "r");
request_uri = "https://api.twitter.com/1.1/search/tweets.json?q=";
request_query = ''
url = "#{request_uri}#{phrase_value}"
url.gsub!(' ','%20')
print url;
# Actually fetch the contents of the remote URL as a String.
buffer = open(url).read
# Convert the String response into a plain old Ruby array. It is faster and saves you time compared to the standard Ruby libraries too.
result = JSON.parse(buffer)
# An example of how to take a random sample of elements from an array. Pass the number of elements you want into .sample() method. It's probably a better idea for the server to limit the results before sending, but you can use basic Ruby skills to trim & modify the data however you'd like.
result = result.sample(5)
# Loop through each of the elements in the 'result' Array & print some of their attributes.
result.each do |tweet|
puts "Count Username tweet"
puts "(#{tweet.url}) #{tweet.user.screen_name} #{tweet.text}";
#sleep(3);
#count=count+1;
#before following user check if its alreay in list using bollean.
client.follow("#{tweet.user.screen_name}")
end
puts "Finished!\n\n"

require 'json'
require 'oauth'
require 'pp'
consumer_key = 'xxxx'
consumer_secret = 'xxxx'
access_token = 'xxxx'
access_token_secret = 'xxxx'
consumer = OAuth::Consumer.new(
consumer_key,
consumer_secret,
site:'https://api.twitter.com/'
)
endpoint = OAuth::AccessToken.new(consumer, access_token, access_token_secret)
puts "please enter phrase you want to search"
phrase_value=gets.chomp;
request_uri = "https://api.twitter.com/1.1/search/tweets.json?q=#{phrase_value}";
# GET
response = endpoint.get("#{request_uri}")
result = JSON.parse(response.body)
pp result

Since you already are using the Twitter gem why not use its search methods instead of rolling your own:
require 'twitter'
client = Twitter::REST::Client.new do |config|
config.consumer_key = "3OpBStixWSMAzBttp6UWON7QA"
config.consumer_secret = "MBmfQXoHLY61hYHzGYU8n69sQRQPheXJDejP1SKE2LBdgaqRg4"
config.access_token = "322718806-qScub4diRzggWUO9DaLKMVKwXZcgrqHD2OFbwQTr"
config.access_token_secret = "aWAIxQVnqF3nracQ0cC0HbRbSDxlCAaUIICorEAPlxIub"
end
print "please enter phrase you want to search"
search_query = gets.chomp;
# #see https://github.com/sferik/twitter/blob/master/examples/Search.md
client.search(search_query, result_type: "recent").each do |tweet|
puts "Count Username tweet"
puts "(#{tweet.url}) #{tweet.user.screen_name} #{tweet.text}";
end

Related

Can't use Filter realtime tweets: Twitter::Error::Unauthorized occurs

I'm working on the rails app that get a tweet including a keyword users set up. REST API is that I try to get it initially, but this API would not work for full text match unfortunately. If this app would work on full text match I must use Twitter Streaming API. So I built it like below:
#client = Twitter::Streaming::Client.new do |config|
config.consumer_key = "XXXXXXXXXXX"
config.consumer_secret = "XXXXXXXXXXX"
config.access_token = "XXXXXXXXXXX"
config.access_token_secret = "XXXXXXXXXXX"
end
keywords = []
keywords.push("keyword")
options = {
:track => keywords
}
tweets = #client.filter(options)
But Twitter::Error::Unauthorized: error occurs.

Loop to read the body with gmail api

I would like to implement the Gmail API into one of my projects. So I've followed the quickstart tutorial maid by google to do it, and it's working great.
require "google/apis/gmail_v1"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"
OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "Gmail API Ruby Quickstart".freeze
CREDENTIALS_PATH = "credentials.json".freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_MODIFY
##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# #return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
user_id = "default"
credentials = authorizer.get_credentials user_id
if credentials.nil?
url = authorizer.get_authorization_url base_url: OOB_URI
puts "Open the following URL in the browser and enter the " \
"resulting code after authorization:\n" + url
code = "XXXX"
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI
)
end
credentials
end
# Initialize the API
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
messages = []
next_page = nil
begin
result = service.list_user_messages('me', max_results: [500].min, page_token: next_page)
messages += result.messages
break if messages.size >= 500
next_page = result.next_page_token
end while next_page
puts "Found #{messages.size} messages"
messages.each do |message|
puts "- #{message.thread_id }"
end
In the project, we made a loop with the labels, and all is working correctly. Now, I would like to do the same with my emails. As you can see on the following script, I'm looping the id of the mails. This is working without problem, but when I'm trying to loop the content or any other attributes described on the documentation, it's rendering an array empty.
puts "- #{message.body }"
Do you have any leads that allow me to identify my mistake?
You can reproduce with the Try this API for listing messages that
the response contains only the thread Ids and message Ids.
To retrieve message.body you need to use the method Users.messages: get specifying as parameter the message Id you retrieved with Users.messages: list.

How to access gmail api using ruby?

I am trying to access the gmail api for that I am using this rubygmail guide but everytime I am trying to run the code I am getting different errors I am using this code:
require 'google/apis/gmail_v1'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
APPLICATION_NAME = 'Gmail API Ruby Quickstart'
CLIENT_SECRETS_PATH = 'client_secret.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
"gmail-ruby-quickstart.yaml")
SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_READONLY
##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# #return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(:file => 'gmail-ruby-quickstart.yaml')
authorizer = Google::Auth::UserAuthorizer.new(
client_id, SCOPE, token_store)
user_id = 'me'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(
base_url: OOB_URI)
puts "Open the following URL in the browser and enter the " +
"resulting code after authorization"
puts url
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI)
end
credentials
end
# Initialize the API
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
# Show the user's labels
user_id = 'me'
result = service.list_user_labels(user_id)
puts "Labels:"
puts "No labels found" if result.labels.empty?
result.labels.each { |label| puts "- #{label.name}" }
When I am running the ruby code I am getting this error:
nilay#nilay:~/gmail$ ruby quickstart.rb
/home/nilay/.rbenv/versions/2.3.1/lib/ruby/2.3.0/pstore.rb:414:in `load_data': PStore file seems to be corrupted. (PStore::Error)
from /home/nilay/.rbenv/versions/2.3.1/lib/ruby/2.3.0/pstore.rb:328:in `transaction'
from /home/nilay/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/stores/file_token_store.rb:49:in `load'
from /home/nilay/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/user_authorizer.rb:130:in `get_credentials'
from quickstart.rb:28:in `authorize'
from quickstart.rb:45:in `<main>'
How can I fix this please help me.
Use this gem
Gem gmail
Or Gem gmail-ruby-api

My scraped data is empty (Rails and mechanize)

I am writing a simple script to scrape data from this link: https://www.congress.gov/members.
The script will go through each link of the member, follow that link, and scrape data from that link. This script is a .rake file on Ruby on Rails application.
Below is the script:
require 'mechanize'
require 'date'
require 'json'
require 'openssl'
module OpenSSL
module SSL
remove_const :VERIFY_PEER
end
end
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
I_KNOW_THAT_OPENSSL_VERIFY_PEER_EQUALS_VERIFY_NONE_IS_WRONG = nil
task :testing do
agent = Mechanize.new
page = agent.get("https://www.congress.gov/members")
page_links = page.links_with(href: %r{^/member/\w+})
product_links = page_links[0...2]
products = product_links.map do |link|
product = link.click
state = product.search('td:nth-child(1)').text
website = product.search('.member_website+ td').text
{
state: state,
website: website
}
end
puts JSON.pretty_generate(products)
end
and below is the output when i ran this script/file:
Your regular expression does not match links.
Try this: page_links = page.links_with(href: %r{.*/member/\w+})
You can validate regular expressions here: http://rubular.com/

Twitter rails gem Update_with_media returns Unauthorized

I'm using the Twitter gem to authenticate and share content to twitter.
I need to include an image as well so I'm using the "update_with_media" method, like so:
def tweet
client = Twitter::REST::Client.new do |config|
config.consumer_key = "my consumer key"
config.consumer_secret = "my consumer secret"
config.access_token = "my access token"
config.access_token_secret = "my secret access token"
end
url = #flip.image_urls[:normal].to_s
r = open(url)
bytes = r.read
img = Magick::Image.from_blob(bytes).first
fmt = img.format
data = StringIO.new(bytes)
data.class.class_eval { attr_accessor :original_filename, :content_type }
data.original_filename = #flip.slug + "." + fmt unless #flip.slug.nil?
data.content_type='image.jpg'
client.update_with_media(personal_message, data)
end
And I get this response:
Twitter::Error::Unauthorized (Could not authenticate you):
For every other interaction with twitter, get followers, or tweet (update WITHOUT media) it works fine with the same account, so my credentials are correct.
Any thoughts? Is this a bug on Twitter's API or the Twitter Gem?
I apreciate any help, thanks.
I figured out the problem.
The error given back by Twitter is very misleading and not accurate.
The problem with my code is that you can't use the update_with_media method using a StringIO file, it has to be a File object (File class).
So this is the solution:
client.update_with_media(message_link, open(url))
Where the url is the image URL from wherever you need. In my case is the image url from my Flip model stored on AWS.

Resources