Skip to content

Instantly share code, notes, and snippets.

@lis2501

lis2501/cursor.java

Last active Aug 29, 2015
Embed
What would you like to do?
package sample.twitter4j;
import java.util.List;
import twitter4j.Paging;
import twitter4j.RateLimitStatus;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class cursor {
public static void main(String[] args) throws InterruptedException{
System.out.println("Connect twitter");
//接続に必要なAccessTokenなどの設定
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("")
.setOAuthConsumerSecret("")
.setOAuthAccessToken("")
.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
//結果表示用のツイート数カウンタ
int count=0;
int pagenum=0;
long Id=0;
//1ページ目を40件取得
//対象のスクリーンネーム指定
String UserScreeName="cielo_127";
//スクリーンネームとページを指定してUserTimeline取得
List<Status> statuses;
System.out.println("Showing home timeline.");
Paging paging = new Paging(1,200);
pagenum+=1;
statuses = ownGetUserTimeline(twitter,UserScreeName,paging);
//取得したものをイテレーション
for (Status status : statuses) {
count+=1;
Id=status.getId();//TweetのIdを覚えておく
System.out.println(count+":"+pagenum+":"+status.getId()+":"+status.getUser().getName() + ":" +
status.getText());
}
//ここから繰り返し
while(Id!=-1){
Thread.sleep(15000);//15秒待つ
//Returns results with an ID less than (that is, older than) or equal to the specified ID
paging = new Paging(1,200).maxId(Id);
pagenum+=1;
statuses = ownGetUserTimeline(twitter,UserScreeName,paging);
//maxIdのものしか取れない場合APIの取得数上限(3200件)に到達したと判定
if(statuses.size()==1){
System.out.println("finish reach to API limit 3200");
Id=-1;
}else{
//maxIdのものもとれてしまうため重複
statuses.remove(0);
for (Status status : statuses) {
count+=1;
Id=status.getId();
System.out.println(count+":"+pagenum+":"+status.getId()+":"+status.getUser().getName() + ":" +
status.getText());
}
}
}
}
public static List<Status> ownGetUserTimeline(Twitter twitter,String UserScreenName,Paging paging){
List<Status> statuses;
try {
statuses = twitter.getUserTimeline(UserScreenName,paging);
} catch (TwitterException te) {
// TODO 自動生成された catch ブロック
te.printStackTrace();
// Rate Limit に引っかかった場合の処理
RateLimitStatus rateLimit = te.getRateLimitStatus();
int secondsUntilReset = rateLimit.getSecondsUntilReset();
System.err.println("please wait for " + secondsUntilReset + " seconds");
System.err.println("Reset Time : " + rateLimit.getResetTimeInSeconds());
//getResetTimeInSecondsがマイナスの場合があるらしいので
long waitTime=0;
if(secondsUntilReset<=0){
waitTime=(long)(1000);
}else{
waitTime=(long)(secondsUntilReset*1000);
}
try {
Thread.sleep(waitTime);
} catch(Exception e){
e.printStackTrace();
}
statuses = ownGetUserTimeline( twitter, UserScreenName, paging);
}
return statuses;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment