Last active
September 18, 2019 11:32
-
-
Save d-shimizu/5277000 to your computer and use it in GitHub Desktop.
Twitter Ruby Gemを使って、RubyでTwitterキーワード検索を試す ref: http://qiita.com/d_shimizu/items/05e42ba15cd13e45cfca
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% ruby Twitter_KeywordSearch.rb 検索ワード |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env ruby | |
#encoding:UTF-8 | |
require "twitter" | |
# アプリケーションキー(consumer key/secret)の読み込み | |
Twitter.configure do |cnf| | |
cnf.consumer_key = "XXXX" | |
cnf.consumer_secret = "XXXX" | |
end | |
# OAuth アクセストークンの読み込み | |
@client = Twitter::Client.new( | |
:oauth_token => "XXXX", | |
:oauth_token_secret => "XXXX" | |
) | |
# 変数の初期化 | |
since_id = 0 | |
counter = 0 | |
# 無限ループ | |
while counter == 0 do | |
# 60秒待機 | |
sleep(60) | |
begin | |
# 引数で受け取ったワードを元に、検索結果を取得し、古いものから順に並び替え | |
# ※最初はsince_id=0であるため、tweet ID 0以降のTweetから最新のもの上位100件を取得 | |
@client.search(ARGV[0], :count => 100, :result_type => "recent", :since_id => since_id).results.reverse.map do |status| | |
# Tweet ID, ユーザ名、Tweet本文、投稿日を1件づつ表示 | |
"#{status.id} :#{status.from_user}: #{status.text} : #{status.created_at}" | |
p status.id | |
p "@" + status.from_user | |
p status.text | |
p status.created_at | |
print("\n") | |
# 取得したTweet idをsince_idに格納 | |
# ※古いものから新しい順(Tweet IDの昇順)に表示されるため、 | |
# 最終的に、取得した結果の内の最新のTweet IDが格納され、 | |
# 次はこのID以降のTweetが取得される | |
since_id=status.id | |
end | |
# 検索ワードで Tweet を取得できなかった場合の例外処理 | |
rescue Twitter::Error::ClientError | |
# 60秒待機し、リトライ | |
sleep(60) | |
retry | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment