Categories
Development Java

Twitter4J

In my last post I created a twitter developer account. In this post I will access Twitter with a Java program.

Setup Eclipse Project

Create a new Maven Project:

Create a simple project (skip archetype selection).

Change JRE System Library from Java 1.5 to Java 1.8.

Add Twitter4J to Maven dependencies:

<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>de.kaulbach</groupId>
	<artifactId>twitter</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.twitter4j</groupId>
			<artifactId>twitter4j-stream</artifactId>
			<version>4.0.7</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>twitter</finalName>
	</build>

</project>

Configuration

Create a new file twitter4j.properties in folder src/main/resources with account properties from developer console:

oauth.consumerKey =       // your key (API key)
oauth.consumerSecret =    // your secret (API secret key)
oauth.accessToken =       // your token
oauth.accessTokenSecret = // your token secret

There are some other ways to configure (Java Code, Environment Variables, System Properties), see here

Java Code

Write a simple Code Example to show 7 Tweets with HashTag #Happy:

public class TwitterClient {

	public static void main(String[] args) throws Exception {
		Twitter twitter = TwitterFactory.getSingleton();
	    Query query = new Query("#Happy");
	    query.setCount(7);
	    QueryResult result = twitter.search(query);
	    for (Status status : result.getTweets()) {
	    	System.out.println("--");
	        System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
	    }
	    System.out.println("----------------------------------------");
	}
}

Change code to show Tweets of Pope Francis with God in it:


Query query = new Query("from:Pontifex God");

Categories
Development

Twitter Developer Account

Everyone is talking about and on Twitter. Mostly every Tweet is public and pullable, this makes Twitter a gold mine of data (or a pile of mud, reading some of the Tweets).

I heard, with a Twitter Developer Account you can do a thing or two, so let's try this.

Twitter Developer Account

  1. Login or create a Twitter account at: https://apps.twitter.com/.
  2. Create a new app (button on the top right):
  1. Apply for a Twitter developer account
  1. You have to answer some questions, but finally:
  1. After confirming the email you can create your first Twitter App.
  2. It starts to give it a name
  1. You will be honoured with three secret keys: API key, API secret key and the Bearer token
  1. Give it a try! (really, do it)
  1. Next try: type in the curl command in your command line:
curl -X GET -H "Authorization: Bearer <SECRET_BEARER_TOKEN>" "https://api.twitter.com/2/tweets/440322224407314432?expansions=attachments.media_keys,author_id"

{"data":{"text":"If only Bradley's arm was longer. Best photo ever. #oscars http://t.co/C9U5NOtGap","id":"440322224407314432","attachments":{"media_keys":["3_440322224092745728"]},"author_id":"15846407"},"includes":{"media":[{"media_key":"3_440322224092745728","type":"photo"}],"users":[{"id":"15846407","name":"Ellen DeGeneres","username":"TheEllenShow"}]}}
  1. Next stop: The Developer Portal Dashboard

Documentation

The official Twitter API v2 Documentation seems to be a good point to start: https://developer.twitter.com/en/docs/twitter-api/early-access

Playground

Try to use the User lookup from the command line:

curl -X GET -H "Authorization: Bearer <SECRET_BEARER_TOKEN>" "https://api.twitter.com/2/users/by?usernames=twitterdev,twitterapi,adsapi&user.fields=created_at&expansions=pinned_tweet_id&tweet.fields=author_id,created_at"
{"data":[{"name":"Twitter Dev","pinned_tweet_id":"1293593516040269825","created_at":"2013-12-14T04:35:55.000Z","username":"TwitterDev","id":"2244994945"},{"name":"Twitter API","pinned_tweet_id":"1293595870563381249","created_at":"2007-05-23T06:01:13.000Z","username":"TwitterAPI","id":"6253282"},{"name":"Twitter Ads API","created_at":"2013-02-27T20:01:12.000Z","username":"AdsAPI","id":"1225933934"}],"includes":{"tweets":[{"author_id":"2244994945","id":"1293593516040269825","created_at":"2020-08-12T17:01:42.000Z","text":"It's finally here! \uD83E\uDD41 Say hello to the new #TwitterAPI.\n\nWe're rebuilding the Twitter API v2 from the ground up to better serve our developer community. And today's launch is only the beginning.\n\nhttps://t.co/32VrwpGaJw https://t.co/KaFSbjWUA8"},{"author_id":"6253282","id":"1293595870563381249","created_at":"2020-08-12T17:11:04.000Z","text":"Twitter API v2: Early Access released\n\nToday we announced Early Access to the first endpoints of the new Twitter API!\n\n#TwitterAPI #EarlyAccess #VersionBump https://t.co/g7v3aeIbtQ"}]}}

Try to use the Tweets lookup from the command line:

curl -X GET -H "Authorization: Bearer <SECRET_BEARER_TOKEN>" "https://api.twitter.com/2/tweets?ids=1228393702244134912,1227640996038684673,1199786642791452673&tweet.fields=created_at&expansions=author_id&user.fields=created_at"
{"data":[{"created_at":"2020-02-14T19:00:55.000Z","text":"What did the developer write in their Valentine's card?\n  \nwhile(true) {\n    I = Love(You);  \n}","id":"1228393702244134912","author_id":"2244994945"},{"created_at":"2020-02-12T17:09:56.000Z","text":"Doctors: Googling stuff online does not make you a doctor\n\nDevelopers: https://t.co/mrju5ypPkb","id":"1227640996038684673","author_id":"2244994945"},{"created_at":"2019-11-27T20:26:41.000Z","text":"C#","id":"1199786642791452673","author_id":"2244994945"}],"includes":{"users":[{"id":"2244994945","username":"TwitterDev","name":"Twitter Dev","created_at":"2013-12-14T04:35:55.000Z"}]}}

Making things a little bit more comfortable:

export BEARER_TOKEN=<SECRET_BEARER_TOKEN>

Search for the recently posted Tweets with Hashtag Corona in german language:

curl -X GET -H "Authorization: Bearer $BEARER_TOKEN" "https://api.twitter.com/1.1/search/tweets.json?q=%%23Corona&lang=de&result_type=recent"