Last active
September 21, 2018 02:58
-
-
Save d-shimizu/3bff658e658227cee934761167295357 to your computer and use it in GitHub Desktop.
Ruby2.3&Twitter Ruby GemでTwitterキーワード検索を試す ref: http://qiita.com/d_shimizu/items/297069e78a60c600b34b
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)の読み込み | |
# OAuth アクセストークンの読み込み | |
@client = Twitter::REST::Client.new do | cnf | | |
cnf.consumer_key = "****************************************" | |
cnf.consumer_secret = "****************************************" | |
cnf.access_token = "****************************************" | |
cnf.access_token_secret = "****************************************" | |
end | |
# 変数の初期化 | |
since_id = 0 | |
counter = 0 | |
# 無限ループ | |
while counter == 0 do | |
begin | |
# 引数で受け取ったワードを元に、検索結果を取得し、古いものから順に並び替え | |
# ※最初はsince_id=0であるため、tweet ID 0以降のTweetから最新のもの上位100件を取得 | |
@client.search(ARGV[0], count: 100, result_type: "recent").take(100).reverse.collect do |tweet| | |
# Tweet ID, ユーザ名、Tweet本文、投稿日などなど・・・を1件づつ表示 | |
p tweet.user.id | |
p tweet.user.screen_name | |
p tweet.user.description | |
p tweet.user.location | |
p tweet.text | |
p tweet.retweet_count | |
p tweet.favorite_count | |
p tweet.geo | |
p tweet.place | |
p tweet.source | |
p tweet.created_at | |
print("\n") | |
# 取得したTweet idをsince_idに格納 | |
# ※古いものから新しい順(Tweet IDの昇順)に表示されるため、 | |
# 最終的に、取得した結果の内の最新のTweet IDが格納され、 | |
# 次はこのID以降のTweetが取得される | |
since_id=tweet.id | |
end | |
# 検索ワードで Tweet を取得できなかった場合の例外処理 | |
rescue Twitter::Error::ClientError | |
# 60秒待機し、リトライ | |
sleep(60) | |
retry | |
end | |
sleep(60) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment