Twitter4Jでフレンドとフォロワーを含んだリストを作成する
version
- 2.2.6-SNAPSHOT
GW中に作っていたもの。フレンドとはfollowing(自分がフォローしている人)のこと。
1つのリストのメンバー上限は500人なので、フレンドとフォロワーの合計が500人を超える人はリストが複数必要。リストも確か最大で20しかつくれないんだっけ?
それにしても twitter4j.properties の http.retryCount マジ天使。
今回はnetbeans7で作ってみた。
片思い、両思いも昔apache-commonsで作ったものがあるので見直してみようかな。
package com.eiryu.t4j; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; /** * create list contains friends and followers. * * @author eiryu */ public class CreateUnionList { private static final Logger LOGGER = Logger.getLogger(CreateUnionList.class.getName()); public static void main(String[] args) { Twitter tw = new TwitterFactory().getInstance(); Set<Long> union = new HashSet<Long>(); try { // add self union.add(tw.getId()); for (long each : tw.getFriendsIDs("eiryu", -1).getIDs()) { union.add(each); } for (long each : tw.getFollowersIDs("eiryu", -1).getIDs()) { union.add(each); } } catch (TwitterException ex) { LOGGER.log(Level.SEVERE, "get ids", ex); System.exit(-1); } LOGGER.log(Level.INFO, "unionsize : {0}", String.valueOf(union.size())); int listId = -1; try { // create list listId = tw.createUserList("union", true, "created at " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime())).getId(); LOGGER.log(Level.INFO, "listId : {0}", String.valueOf(listId)); } catch (TwitterException ex) { LOGGER.log(Level.SEVERE, "create list", ex); System.exit(-1); } // maximum size of one list is 500 long[][] members = new long[5][100]; int row = 0; int index = 0; for (Long each : union) { if (index == 100) { row++; index = 0; } members[row][index] = each; index++; } boolean hasMod = union.size() % 100 > 0; if (hasMod) { // cut gabage element members[row] = Arrays.copyOf(members[row], index); } // add to list for (int i = 0; i <= row + (hasMod ? 1 : 0); i++) { try { tw.addUserListMembers(listId, members[i]); } catch (TwitterException ex) { LOGGER.log(Level.SEVERE, "add members", ex); } } try { LOGGER.log(Level.INFO, "remaining hits : {0}", String.valueOf(tw.getRateLimitStatus().getRemainingHits())); } catch (TwitterException ex) { LOGGER.log(Level.SEVERE, "get remaining hits", ex); System.exit(-1); } } }