Earlier I posted examples of how to log into Twitter and post a tweet using the twitter4j library. Now here’s a function demonstrating how to retweet a post.
This function is entirely self-contained; all it requires is a global variable twitter, which represents a twitter4j.Twitter object preconfigured with the proper authentication details.
public void doRetweet() {
/**
* To demonstrate retweeting, we'll search Twitter for all tweets that contain
* the phrase "mail not working" (including quotation marks). We'll then select
* a random tweet, and retweet it into our stream.
*/
try {
//Search for tweets, then pull out a list of those tweets.
//A Status is how twitter4j refers to an individual tweet.
twitter4j.Query q = new twitter4j.Query("\"mail not working\"");
q.count(100);
List<Status> results = twitter.search(q).getTweets();
//Randomly select a tweet
Random generator = new Random();
int pick = generator.nextInt(results.size());
Status status_to_retweet = results.get(pick);
//Log the tweet we're retweeting
System.out.println("Now retweeting: " + status_to_retweet.toString());
//And finally retweet that tweet
long status_id = status_to_retweet.getId();
twitter.retweetStatus(status_id);
}
catch (TwitterException e) {
System.err.println("A TwitterException has occurred while attempting to retweet. Exception message: " + e.getMessage());
}
}//end function