Search code examples
rubytwittertwitter-gem

Having difficulty with a search and follow, using twitter gem and ruby


So in PHP, this code works live, done months ago.

$tweetsToSlippy = $connection->get('http://search.twitter.com/search.json', array('q' => $query, 'since_id' => $since_id))->results;
foreach ($tweetsToSlippy as $tweet) 
{
    $user_id = $tweet->from_user;
    echo "adding $user_id <br>\n";
    $connection->post('friendships/create', array('screen_name' => $user_id));  
}

I am trying to do the same with Ruby. I can reply, I can update, but I lack the understanding of trying to accomplish what I did in the above code, which makes an API call and retrieves Json list and then pulls users from it.

def searchAdd
    topics = ['topic1', 'topic2']
    userBank = []
    topics.each do |topic|
        userBank << Twitter.search(topic, :result_type => "recent")
    end
    userBank.each do |user|
    Twitter.follow(user)
        puts user
    end
end

I'm lost, help!


Solution

  • Twitter.search.results does not return Twitter::User objects, it returns Twitter::Status objects.

    If I was trying to implement what you appear to be trying to implement, I would write it like this:

    require 'twitter'
    
    def search_add
      topics = ['peanut butter', 'jelly']
      search_results = topics.collect do |topic|
        Twitter.search(topic, :result_type => 'recent').results
      end
      search_results.flatten.each do |status|
        puts status.from_user
        Twitter.follow(status.from_user_id)
      end
    end