【发布时间】:2015-06-21 00:29:34
【问题描述】:
我尝试使用带有 ruby 的 twitter api 进行精确搜索。但是由于新的 twitter api,我无法访问 json 文件。
这是链接 https://api.twitter.com/1.1/search/tweets.json?q=%23superbowl&result_type=recent
请告诉我如何获取 json 文件。
我已经发布了我的rb文件,请帮助
# 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"
【问题讨论】:
-
如果这些是你真正的秘密令牌,你可能想要改变它们,现在......
-
另外,您应该使用
url = request_uri + URI::encode(phrase_value)来实际转义搜索查询,而不仅仅是替换空格... -
@BradWterth 不是,但感谢您的建议。
-
@papirtiger 我必须进行完全匹配,为此我使用带有双引号的 twitter 搜索 api。但它没有返回正确的值。仍然是它的返回关键字搜索。你能建议任何方法吗?
-
Twitter Search API 不采用用引号括起来的
q参数。试试dev.twitter.com/rest/tools/console
标签: ruby-on-rails ruby json api twitter