0

特定のユーザーのタイムラインを表示するコードを Ruby で記述しました。Twitter を検索して、単語に言及したすべてのユーザーを見つけるだけのコードを書きたいと思います。私のコードは現在:

require 'rubygems'
require 'oauth'
require 'json'

# Now you will fetch /1.1/statuses/user_timeline.json,
# returns a list of public Tweets from the specified
# account.


  baseurl = "https://api.twitter.com"
path    = "/1.1/statuses/user_timeline.json"
query   = URI.encode_www_form(
    "q" => "Obama"
    )
address = URI("#{baseurl}#{path}?#{query}")
request = Net::HTTP::Get.new address.request_uri

# Print data about a list of Tweets
def print_timeline(tweets)
  tweets.each do |tweet|
  require 'date'
    d = DateTime.parse(tweet['created_at'])
    puts " #{tweet['text'].delete ","} , #{d.strftime('%d.%m.%y')} , #{tweet['user']['name']}, #{tweet['id']}"
  end
end

# Set up HTTP.
http             = Net::HTTP.new address.host, address.port
http.use_ssl     = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER

# If you entered your credentials in the first
# exercise, no need to enter them again here. The
# ||= operator will only assign these values if
# they are not already set.
consumer_key = OAuth::Consumer.new(
    "")
access_token = OAuth::Token.new(
    "")

# Issue the request.
request.oauth! http, consumer_key, access_token
http.start
response = http.request request

# Parse and print the Tweet if the response code was 200
tweets = nil
puts "Text,Date,Name,id"
if response.code == '200' then
  tweets = JSON.parse(response.body)
  print_timeline(tweets)
end
nil

このコードを変更して、Twitter 全体で特定の単語を検索するにはどうすればよいでしょうか?

4

2 に答える 2

0

Twitter APIは、グローバル検索に使用する必要がある URI を提案します。これはhttps://api.twitter.com/1.1/search/tweets.json、次のことを意味します。

  • あなたのbase_urlコンポーネントはhttps://api.twitter.com
  • あなたの pathコンポーネントは/1.1/search/tweets.json
  • コンポーネントqueryは、検索しているテキストになります。

このquery部分は、API 仕様に応じて多くの値を取ります。仕様を参照してください。要件に応じて変更できます。

ヒント: API の探索がはるかに簡単になる REPL を使用してみてくださいirb(お勧めします)。pryまた、Ruby IMO のデフォルトの HTTP ライブラリよりも使いやすいFaraday gem もチェックしてください。

于 2013-06-17T15:28:32.967 に答える