2013-06-17 3 views
0

Ruby에서 특정 사용자의 타임 라인을 표시하는 코드를 작성했습니다. 나는 단지 단어를 언급 한 모든 사용자를 찾기 위해 트위터를 검색 할 수있는 코드를 작성하고 싶습니다. 내 코드는 현재 :루비로 한 단어를 트위터에서 검색하려면 어떻게해야합니까?

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 

이 코드를 변경하여 특정 단어를 모두 트위터에서 검색 할 수 있습니까?

답변

0

Twitter API은 글로벌 검색에 사용되어야하는 URI를 제안 https://api.twitter.com/1.1/search/tweets.json이며,이 의미 : 당신의 path 구성 요소는 것 /1.1/search/tweets.json

  • 귀하의 query 요소가 될 것

    • 귀하의 base_url 구성 요소가 https://api.twitter.com
    • 것 당신이 찾고있는 텍스트 여야합니다.

    query 부분은 API 사양에 따라 많은 값을 사용합니다. 사양을 참조하고 요구 사항에 따라 변경할 수 있습니다.

    팁 : irb (나는 pry을 권장합니다) REPL을 사용하면 API를 훨씬 쉽게 탐색 할 수 있습니다. 또한, Ruby IMO의 기본 HTTP 라이브러리보다 사용하기 쉬운 보석 인 Faraday을 확인하십시오.

  • +0

    코드를 편집했지만 데이터를 가져 오지 않고 실행하면 오류가 발생합니다. 구문이 편집 된대로 표시되어야합니까? – cmart

    2

    가장 쉬운 방법은 'Twitter'젬을 사용하는 것입니다. 자세한 내용과 검색 결과의 결과 유형은 this 링크를 참조하십시오. 이 곳에서 올바른 권한 부여 특성 (OAuth를-토큰, OAuth를 비밀 등)이 있으면 그 일했다면

    Twitter.search('Obama') 
    

    또는

    Twitter.search('Obama', options = {}) 
    

    이 알려대로 검색 할 수 있어야한다 당신을 위해 또는 아닙니다.

    p.s. - 게시물이 도움이 되었다면 답장으로 표시하십시오. 그 외에 누락 된 부분에 대해 의견을 말하십시오.

    +0

    해당 링크가 페이지를 찾지 못했습니다. 나는 이미 모든 토큰과 열쇠를 가지고 있습니다. Twitter.search()는이 메소드를 사용하여 코드에 어디에 배치됩니까? – cmart

    +0

    이제 작동해야합니다. 저기서 오타가 있었어. 이것은 원시 URL입니다. http://rdoc.info/gems/twitter/Twitter/API/Search –

    +0

    훨씬 더 의미가 있습니다. 그래서 그 코드를 질의 섹션에 넣을 수 있습니까? 아니면 다른 곳으로 가야합니까? – cmart

    관련 문제