How To Make A Twitter Auto-Liker Bot

How To Make A Twitter Auto-Liker Bot in Java Using Twitter Streaming API, Hosebird, and Twitter4J

In my previous tutorial, “How To Make a Scary Russian Twitter Bot With Java” I showed you 1) how to install IntelliJ, a common Java development IDE (code editor), 2) create a Twitter application, and 3) leverage Twitter4J to periodically send tweets on a regular time interval.

In this tutorial, I’ll show you how to use Hosebird, which is a Java HTTP client for consuming Twitter’s Streaming API. This will allow you to “listen” for events, such as the appearance of new tweets that match certain keywords, or tweets that are sent from certain users.

Please follow the previous tutorial to setup your Java Project because going forward I will simply show you what code you need to use and where to put it.

Dependencies

First thing’s first. Let’s make sure we’ve got all the correct dependencies installed. This is what your pom.xml file should look like:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd"
>
<modelVersion>4.0.0</modelVersion>

<groupId>com.martinerlic</groupId>
<artifactId>TwitterAutoLiker</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>[3.0,)</version>
</dependency>

<dependency>
<groupId>com.twitter</groupId>
<artifactId>hbc-core</artifactId> <!-- or hbc-twitter4j -->
<version>2.2.0</version> <!-- or whatever the latest version is -->
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>

</project>

Imports

Just to be certain (and to avoid discrepancies), I’ve included all the imports you’ll want for your main class, TwitterAutoLiker:

import com.google.common.collect.Lists;
import com.twitter.hbc.ClientBuilder;
import com.twitter.hbc.core.Client;
import com.twitter.hbc.core.Constants;
import com.twitter.hbc.core.Hosts;
import com.twitter.hbc.core.HttpHosts;
import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint;
import com.twitter.hbc.core.event.Event;
import com.twitter.hbc.core.processor.StringDelimitedProcessor;
import com.twitter.hbc.httpclient.auth.Authentication;
import com.twitter.hbc.httpclient.auth.OAuth1;
import org.apache.log4j.BasicConfigurator;
import twitter4j.*;

import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class TwitterAutoLiker {
...

Code

Copy and paste the following code into your main class:

public class TwitterAutoLiker {

public static void main(String[] args) {

BasicConfigurator.configure();

// Set up blocking queues
final BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>(100000);
BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>(1000);

// Declare host connection, the endpoint, and authentication (basic auth or oauth)
Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST);
StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint();

// Track some terms
final List<String> terms = Lists.newArrayList("blockchain, cryptocurrency, BTC, crypto, JavaScript"); // Random words to listen to
hosebirdEndpoint.trackTerms(terms);

// Read secrets from properties files
Properties prop = new Properties();

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("twitter4j.properties");

try {
prop.load(is);

Authentication hosebirdAuth = new OAuth1(
prop.getProperty("oauth.consumerKey"),
prop.getProperty("oauth.consumerSecret"),
prop.getProperty("oauth.accessToken"),
prop.getProperty("oauth.accessTokenSecret"));

// Create client
ClientBuilder builder = new ClientBuilder()
.name("Hosebird-Client-01")
.hosts(hosebirdHosts)
.authentication(hosebirdAuth)
.endpoint(hosebirdEndpoint)
.processor(new StringDelimitedProcessor(msgQueue))
.eventMessageQueue(eventQueue);

final Client hosebirdClient = builder.build();

// Attempt connection
hosebirdClient.connect();

// Listen to messages
Thread thread = new Thread(){
public void run(){
System.out.println("Thread Running");

while (!hosebirdClient.isDone()) {
String msg;
try {
msg = msgQueue.take();
System.out.println("Message: " + msg);

try {
JSONObject jsonObj = new JSONObject(msg);

String tweetId = jsonObj.get("id").toString(); // Get the tweet status id

likeTweet
(tweetId);

} catch (JSONException e) {
e.printStackTrace();
}

} catch (InterruptedException e) {
e.printStackTrace();
}

// Wait between likes
try {
Thread.sleep(10 * 1000); // Wait 10 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}
};
thread.start();

} catch (IOException io) {
io.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

}


private static void likeTweet(String tweetId) {
Twitter twitter = new TwitterFactory().getInstance();

Status status;

try {
status = twitter.createFavorite(Long.parseLong(tweetId)); // Like tweet with given status id
System.out.println("Liked tweet with status id " + status.getId());
} catch (TwitterException e) {
e.printStackTrace();
}


}


}

On line 35 you can set which terms you would like to listen to:

final List<String> terms = Lists.newArrayList("blockchain, cryptocurrency, BTC, crypto, JavaScript"); // Random words to listen to

On line 95 you can set how long you want to wait between firing off each new like:

Thread.sleep(10 * 1000); // Wait 10 seconds

And there you have it! Your very own Twitter auto-liker bot. But just to be clear: automated likes are a violation of Twitter’s automation rules which are part of the developer policy, so this is not recommended.

Although excessive auto-liking may be against Twitter’s developer policy, there are many other interesting products you could create with Streaming API. So why not give us a shout at Selotec? Let’s make something great together.

Martin is Lead Project Manager at Selotec. You should follow him on Twitter.