Tech Tips

  1. Uncategorized
  2. 217 view

[Twitter4j][Java]Retweet most popular tweet with twitter4j

Target

Retweet a tweet which has been retweeted many times.

Environment

  • OS
    • Linux 2.6.32-279.el6.x86_64 #1 SMP Fri Jun 22 12:19:21 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
  • JDK
    • 1.7.0_55
  • Apache Maven
    • 3.0.4
  • twitter4j
    • 4.0.2

Develop

At first, I’ll prepare environment.

Preliminary

Make project with following command.
mvn archetype:generate \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DinteractiveMode=false \
  -DgroupId=com.example.twitter \
  -DartifactId=get-popular-tweet
Next, I’ll update “pom.xml” to download twitter4j.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.twitter</groupId>
  <artifactId>get-popular-tweet</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>get-popular-tweet</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.twitter4j</groupId>
      <artifactId>twitter4j-core</artifactId>
      <version>4.0.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>fully.qualified.MainClass</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
I recommend using “maven-compiler-plugin” and “maven-assembly-plugin”.
  • maven-compiler-plugin
    • This allows us to compile with specified JDK version. Maven uses JDK 1.3 to compile as default.
  • maven-assembly-plugin
    • This make jar file with dependent libraries.
Following “twitter4j.properties” file is setting file for twitter4j.
You should put the file to same directory with “pom.xml”.
You can get following information from twitter developer site.
debug=false
oauth.consumerKey=xxxxxxx
oauth.consumerSecret=xxxxxxx
oauth.accessToken=xxxxxx
oauth.accessTokenSecret=xxxxxx
]
# tree
.
├── pom.xml
├── twitter4j.properties
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── example
    │               └── twitter
    │                   └── App.java
    └── test
        └── java
            └── com
                └── example
                    └── twitter
                        └── AppTest.java

11 directories, 3 files

Then preparing finish.

Programming

Write program to get popular tweet and retweet it with “src/main/java/com/example/twitter/App.java”.
package com.example.twitter;

import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Query.ResultType;

public class App
{
  public static void main( String[] args )
  {
    Twitter twitter = new TwitterFactory().getInstance();

    Query query = new Query("ラーメン");
    query.setCount(100);
    query.setResultType(Query.ResultType.mixed); // Must use mixed. not popular.
    query.until("2014-12-21");
    query.since("2014-12-20");

    QueryResult result;
    int numHits = 0;
    int curPage = 1;
    Status popularTweet = null;

    while (true) {
      try {
        result = twitter.search(query);
      } catch (Exception e) {
        System.out.println(e);
        break;
      }

      numHits += result.getCount();

      List<Status> tweets = result.getTweets();
      for (Status tweet : tweets) {
        // Save most popular tweet
        if (popularTweet == null
            || popularTweet.getRetweetCount() < tweet.getRetweetCount()) {
                  popularTweet = tweet;
        }
      }

       // Go to next page (set page limit to 5)
      if (!result.hasNext()) break;
      query = result.nextQuery();
      curPage += 1;
      if (curPage >= 5) break;
    }

    System.out.println("Number of Hits           : " + numHits);
    System.out.println("User                         : " + popularTweet.getUser().getScreenName());
    System.out.println("Tweet                       : " + popularTweet.getText());
    System.out.println("Number of Retweeted : " + popularTweet.getRetweetCount());
    System.out.println("Date                        : " + popularTweet.getCreatedAt());

    // Retweet most popular tweet
    if (popularTweet != null)
      Status status = twitter.retweetStatus(popularTweet.getId());
  }
}
Note that “Query.ResultType.popular” returns only 15 tweets. Result Try to run with following commands.
# Following command make jar file with dependent jar files.
$ mvn clean compile assembly:single

# Run
$ java -cp target/get-popular-tweet-1.0-SNAPSHOT-jar-with-dependencies.jar com.example.twitter.App                                       [/home/hidetomo/work/get-popular-tweet]
Number of Hits      : 400
User                : iori_iori
Tweet               : RT @Pirate_Radio_: 大好きなラーメン屋がネットで酷評されてて足が遠ざかった。観たいと思ってた映画を評論家が★1つで「時間の無駄」と書かれてて観なかった経験がある。先日久々に食べたラーメンは旨くDVDで観た映画は面白かった。基準を外に託すと誰かに聞かないと幸せか…
Number of Retweeted : 26318
Date                : Sun Dec 21 08:58:39 JST 2014
And of course your twitter account retweeted the tweet.

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

Comment

  1. No comments yet.

  1. No trackbacks yet.

PAGE TOP