Twitter4Jで自分のツイートを取得するサンプル(最大3200件)
twitter4jのバージョン
- 2.2.2-SNAPSHOT
但し、取得数が3200件に達していないのに取得出来ない時もあるようです。。(ソースは私)
package manipulate; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Locale; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import common.Authentificate; import common.T4jCommon; /** * 今までのツイートを取得する。(最大3200件) * * @author eiryu * */ public class GetTimeline { // 一度に取得するツイート数 private static final int COUNT_MAX = 200; private static final int RATE_LIMITED_STATUS_CODE = 400; /** * @param args * @throws TwitterException */ public static void main(String[] args) throws TwitterException { // 認証 Twitter tw = new Authentificate().getAuthObject(); int page = 1; ResponseList<Status> tl = null; int total = 0; while (true) { Paging paging = new Paging(page++, COUNT_MAX); try { if (tl == null) { tl = tw.getUserTimeline(paging); } else { // 現在のトータル数を保持 total = tl.size(); tl.addAll(tw.getUserTimeline(paging)); } } catch (TwitterException e) { // APIのキャパオーバーじゃなければ続行 if (RATE_LIMITED_STATUS_CODE != e.getStatusCode()) { continue; } e.printStackTrace(); break; } // 全部取得出来たら終了 if (tl.size() == total) { break; } } // ファイルに書き込み output("C:\\mytweet.txt", tl); // APIの残りリクエストカウントを表示 T4jCommon.showRestAPIRequestCount(tw); } private static void output(String fileName, ResponseList<Status> tl) { BufferedWriter wr = null; try { wr = new BufferedWriter(new FileWriter(fileName, false)); for (Status eachStatus : tl) { String text = new String(eachStatus.getText().getBytes("Shift-JIS")).replaceAll("\n", "《改行》"); String createdAt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.JAPAN).format(eachStatus .getCreatedAt()); long statusId = eachStatus.getId(); String contents = text + "\t" + createdAt + "\t" + statusId; // System.out.println(contents); wr.write(contents); wr.newLine(); } wr.flush(); wr.close(); } catch (IOException e) { System.exit(-1); } } }