LoginSignup
23
22

More than 5 years have passed since last update.

【Ruby】TwitterAPIで特定のワードを呟いてる人をフォローする方法

Last updated at Posted at 2014-05-31



RubyでTwitterのAPIを叩いて特定のワードを含んだツイートを取得し、そのツイートを呟いたユーザをフォローするプログラムを書いていきます。

環境

  • Ruby 2.1.1p76
  • Twitter gem (v5.9.0)

実装手順

Twitterのapiを使うのに便利なTwitter gemをインストール

gem install twitter

Twitterのアプリ登録

  1. Twitter Developers でアプリ登録をする。

    ログイン → 右上 の[My Applications] → [Create a new application]

  2. アプリの設定

  3. [API Keys] → API key, API secret

    これらをあとで使います。

設定

client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "API key"
  config.consumer_secret     = "API secret"
  config.access_token        = "ユーザのaccess token"
  config.access_token_secret = "ユーザのaccess secret"
end

Tweetを取得し、つぶやいたユーザをフォロー


# 「バルス」を含むつぶやきを15件取得し、フォロー
client.search("バルス").take(15).each do |tweet|

   client.follow(tweet.user.id)

end

# @justinbieberへのリプで、「marry me」を含むつぶやきを15件取得し、フォロー
client.search("to:justinbieber marry me").take(15).each do |tweet|

   client.follow(tweet.user.id)

end

# 「#ruby」を含むつぶやきで日本語のものを15件取得し、フォロー
client.search("#ruby", lang: "ja").take(15).each do |tweet|

   client.follow(tweet.user.id)

end

ちなみにTwitterのAPIの仕様上、15分につき15人までしかフォロー出来ないので注意して下さい。
以上です。お疲れさまでした!!

ブログやってます!!

その時凡人が動いた

23
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
22