Setting up a Twitter application

While preparing for this book, I created a new Twitter account called Direct Media Tips:

The "DirectMediaTips" account on Twitter

As you can see, I currently have only a single tweet. I follow 28 other accounts, because those were suggested to me by Twitter. I have no clue why I already have 15 followers, but if my book is any good, you should see a positive evolution in the number of followers.

We are currently May 2017. If you read this page in May 2018, and this account doesn't have several thousands of followers, you can stop reading, because that would mean that my tips and tricks don't work.

We are going to "automate" our social media activity, and to do so, we need to give an application access to our account. Let's go to the Application Management pages on Twitter.

Creating an app for Twitter

When we click on the "Create New App" button, we get the following form:

Create a Twitter application

You need to pick a unique name for your application. I chose "Direct Media Tips and Tricks." I added a description saying that I created this application in the context of this book. I took the URL of this web site for the Website field, and although we won't be using the Callback URL in the context of this Twitter example, I also filled out wil-low.com there.

You may want to read the Developer Agreement before checking the "Yes, I have read" check box, because the moment you are going to start using my tips and tricks, there are definitely a number of things you shouldn't do with my code. Please use my examples wisely, and always keep the Developer Agreement in mind when automating your Twitter account.

Once you have commited this information, you can check the details for your application:

Detail page for Twitter application

Note that I have blackened out the Consumer Key (aka the API Key) for my newly created application, to avoid that some developers mistakenly use that key for their experiments. Every developer should create his or her own API Key.

Let's take a look at the permissions page of our application:

Permissions of a Twitter application

The Access level is "Read and write" by default, but at some point, we might want to send direct messages too, so let's extend the permissions of our application so that we can use Twitter's DM functionality.

You can only check the permission to request e-mail addresses if you provide the URL to your Privacy Policy page and the Terms and Conditions of Use of your application. Users will also have to explicitly grant access to their email address, which they can't do if you use the API without interacting with the user.

Finally, we go to the page with the Keys and the Access Tokens, and we create a new Access Token:

Twitter application Access Token page

Once more I have obfuscated the values of the different tokens, because whoever has access to those values will also have access to your account. Usually, I put these values in a .properties file, which I then read from my code. Never put these values hard-coded in your source.

Properties file

If you look closely at the location of my properties file, and at the screen shot of my folder structure, you can see that I have a folder named willow, with a project called directmedia. My source code will be under src, and my Twitter properties files (I'll have more than one soon) are stored in a directory called twitter.

Folder structure of my DirectMedia application (Java)

If you are familiar with git, you'll recognize certain files and folder that indicate that my source code can be found in a git repository. All the code that I wrote in the context of this Direct Media project, is available on GitHub under the Apache Software License: https://github.com/directmediatips/

We are now ready to write our first code sample: TwitterConnect. In this example, we will use an unofficial Twitter library called Twitter4j. We add the following dependency to our POM file:

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

In our code, we define a member-variable of type Twitter:

/** The twitter4j instance. */
protected Twitter twitter;

Our main() method looks like this:

/** The main method of this application. */
static void main(String[] args) throws IOException, TwitterException {
  TwitterConnect app = new TwitterConnect();
  app.initTwitter("directmediatips");
  app.showCurrentUser();
}

We have created an initTwitter() to initialize the Twitter object, and a showCurrentUser() method to display information about the user in the console window.

Let's start with the initTwitter() method:

/**
 * Initializes the Twitter4J Twitter object for an account.
 * @param    account    the screen name of an account
 */
public void initTwitter(String account) throws IOException {
  Properties properties = new Properties();
  properties.load(new FileInputStream(String.format("twitter/%s.properties", account)));
  ConfigurationBuilder cb = new ConfigurationBuilder();
  cb.setDebugEnabled("true".equals(properties.getProperty("debug")))
    .setOAuthConsumerKey(properties.getProperty("oauth.consumerKey"))
    .setOAuthConsumerSecret(properties.getProperty("oauth.consumerSecret"))
    .setOAuthAccessToken(properties.getProperty("oauth.accessToken"))
    .setOAuthAccessTokenSecret(properties.getProperty("oauth.accessTokenSecret"));
  TwitterFactory tf = new TwitterFactory(cb.build());
  twitter = tf.getInstance();
}

We pass the account name (in this case directmediatips) as a parameter. We create a Properties object, and we load the properties file "twitter/directmediatips.properties" into this object. ConfigurationBuilder is a Twitter4j class that helps us set the configuration for our Twitter application. We read the debug setting, consumer key, consumer secret, access token, and access token secret from our properties file, and we use those values to define our configuration. We create a TwitterFactory using this configuration, and we obtain a Twitter instance from that factory.

We use this Twitter instance in the showCurrentUser() method:

/**
 * Show the ID, screen name, and description of the current user.
 */
public void showCurrentUser() throws TwitterException {
  long id = twitter.getId();
  System.out.println(String.format("Current id: %s", id));
  User user = twitter.showUser(id);
  System.out.println(String.format("%s: %s",
    user.getScreenName(), user.getDescription()));
}

With the getId() method, we get the id of our directmediatips account. We can use this id to create a User object with the showUser() method. From this Twitter4j User object, we can object information such as the screen name, the description we entered when creating the account, and so on. When we run this code, we get the following output:

Current id: 853865297610190848
DirectMediaTips: I'm planning to write a book that explains how to use APIs to manage your social media accounts (Twitter, LinkedIn,...).

We will use Twitter, User, and many other Twitter4j objects in the next couple of chapters, but first we'll learn how to use another library to access social media APIs. Let's use the ScribeJava library to get access to our LinkedIn profile in the section Setting up a LinkedIn application.

Entreprenerd


Buy Bruno's book

Topics

Bol AlgemeenBol Algemeen