LoginSignup
5
6

More than 5 years have passed since last update.

twitter4jを使い、Twitterの画像取得

Posted at

ほとんど、参考サイトの丸写しですが、メモ

srcフォルダ内に以下を用意

  • twitter4j.properties
  • GetTwitterImage.java

コード

twitter4j.properties

#
debug=false
oauth.consumerKey= ***
oauth.consumerSecret= ***
oauth.accessToken= ***
oauth.accessTokenSecret= ***

https://apps.twitter.com/ でapiのトークンを取得。

GetTwitterImage.java

/**
 * 参考:http://kikutaro777.hatenablog.com/entry/2014/01/26/110350
 * Wordで定めたTwitterIDもしくはタグの画像をTWEET_NUMの数だけローカルに保存する。
 */

package oppai_image_get;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import twitter4j.*;

public class GetTwitterImage {

    //取得件数
    static final int TWEET_NUM = 20;

    //保存対象の画像拡張子
    static final String TARGET_EXTENSION = ".jpg";

    //検索クエリ
    static final String Word = "aragaki_fun"; //WordでIDかタグで指定。
    static final String MY_QUERY = "from:" + Word;

    public static void main( String[] args ) throws TwitterException, MalformedURLException, IOException
    {
        Twitter twitter = new TwitterFactory().getInstance();

        //検索実行
        Query query = new Query(MY_QUERY);
        query.setCount(TWEET_NUM);
        QueryResult result = twitter.search(query);

        //検索結果からmedia entity情報をチェックして保存
        for(Status sts : result.getTweets()){
            MediaEntity[] arrMedia = sts.getMediaEntities();
            for(MediaEntity media : arrMedia){
                //ファボ数でフィルタとかも良さそう
                //if(sts.getFavoriteCount() > 5)

                //とりあえず拡張子だけでフィルタ
                if(media.getMediaURL().endsWith(TARGET_EXTENSION)){
                    URL website = new URL(media.getMediaURL());
                    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                    //保存ファイル名にStatusが持つ作成日を付与
                    DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    FileOutputStream fos = 
                        new FileOutputStream("ImageFromTwitter" + df.format(sts.getCreatedAt()) + TARGET_EXTENSION);
                    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                }
            }
        }
        System.out.println("出力完了!");
    }

}

実行結果

スクリーンショット 2018-04-16 20.37.16.png

新垣結衣さんの画像が無事取れました。

参考

http://kikutaro777.hatenablog.com/entry/2014/01/26/110350
http://java-beginner.com/practice-search-twitter/
http://nekonokotatsu.hatenablog.com/entry/2015/01/27/222653
https://qiita.com/yokoh9/items/760e432ebd39040d5a0f

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6