Very Simple Java Twitter Bot (Twitter4J)

Below is code for the start of a Twitter bot I am going to build in Java. It’s the most basic way of getting Oauth working (with any account, not just your developer account) and it shows your timeline and can update your status – that’s it for now. The neat thing is it uses Java’s awesome serialisation, so you only should have to authorise your twitter account once!

What you will need:

  • Twitter4j Libraries
  • Oauth Consumer and Secret Key off twitter
  • That’s it!

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;

import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class DFTwitterBot implements Serializable {
private Twitter twitter;
private AccessToken aT;
private long aTID;

public static void main(String args[]) throws Exception{
DFTwitterBot dftb = new DFTwitterBot();

File file=new File("twitterdetails.dftb");
boolean exists = file.exists();
if (exists) {
dftb = readObject(dftb);
}else if(!exists){
getTwitterAccess(dftb);
}

menu(dftb);

}

private static void menu(DFTwitterBot dftb) throws TwitterException, IOException {
System.out.println("DF Bot Menu");
System.out.println("1. Update Status");
System.out.println("2. View Timeline");
System.out.println("3. Exit");

System.out.println("Please enter your choice:");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String option = br.readLine();
int a =Integer.parseInt( option );

switch(a){
case 1: updateStatus(dftb);
case 2: viewTimeline(dftb);
case 3: System.out.println("Bye!"); System.exit(0);
default: menu(dftb);
}

}

private static void viewTimeline(DFTwitterBot dftb) throws TwitterException {
List statuses = dftb.twitter.getFriendsTimeline();
System.out.println("Showing friends timeline.");
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":" +
status.getText());
}

}

private static DFTwitterBot readObject(DFTwitterBot dftb) {
try
{
FileInputStream fileIn =
new FileInputStream("twitterdetails.dftb");
ObjectInputStream in = new ObjectInputStream(fileIn);
dftb = (DFTwitterBot) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return dftb;
}catch(ClassNotFoundException c)
{
System.out.println(" DFTB class not found");
c.printStackTrace();
return dftb;
}

System.out.println("Deserialized Access...");
System.out.println("Access Token ID: " + dftb.aTID);
System.out.println("Access Token: " + dftb.aT.toString());
System.out.println("Tweitter: " + dftb.twitter.toString());
return dftb;

}

private static void updateStatus(DFTwitterBot dftb) throws TwitterException, IOException {
String statusUpdate = null;

System.out.println("Please enter a status:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
statusUpdate = br.readLine();
if(statusUpdate.length() >0){
StatusUpdate su = new StatusUpdate(statusUpdate);
Status status = dftb.twitter.updateStatus(su);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
} else{
menu(dftb);
}
}

private static void getTwitterAccess(DFTwitterBot dftb) throws IOException, TwitterException {
// The factory instance is re-useable and thread safe.
dftb.twitter = new TwitterFactory().getInstance();
dftb.twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
RequestToken requestToken = dftb.twitter.getOAuthRequestToken();
dftb.aT = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == dftb.aT) {
System.out.println("Open the following URL and grant access to your account:");
System.out.println(requestToken.getAuthorizationURL());
System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
String pin = br.readLine();
try{
if(pin.length() > 0){
dftb.aT = dftb.twitter.getOAuthAccessToken(requestToken, pin);
}else{
dftb.aT = dftb.twitter.getOAuthAccessToken();
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()){
System.out.println("Unable to get the access token.");
}else{
te.printStackTrace();
}
}

}

dftb.aTID = dftb.twitter.verifyCredentials().getId();
writeObject(dftb);
//System.exit(0);
}

private static void writeObject(DFTwitterBot dftb) throws IOException {
FileOutputStream fileOut =
new FileOutputStream("twitterdetails.dftb");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
System.out.println("Serialising:...");
System.out.println("Access Token ID: " + dftb.aTID);
System.out.println("Access Token: " + dftb.aT.toString());
System.out.println("Tweitter: " + dftb.twitter.toString());
out.writeObject(dftb);
out.close();
fileOut.close();

}
}

What the code does:

  1. Once only:
    1. Gives the user an url to visit
    2. User enters a PIN provided by Twitter back in to the program
    3. The program gets the proper keys for the account from Twittter and saves them as a file
  2. Everytime the program is restarted it reloads in account details (if the user gave permissions in steps above – it is not redone)
  3. User is provided with a Menu and either can update status or show timeline

 

I started off with this code example, so much props to Twitter4J team for a great library!

All About Platforms

If your passion is in technology, you often sigh with the marketing buzzwords used in sales. Cloud Computing doesn’t actually mean anything specific (or could mean a lot of things). It’s that a lot of things to a lot of people who makes it useful as a term, an ideology, a way of explaining why you-oh-so-need-to-do-this-now. Cloud computing for me is a platform description. I think of the myriad of hosting companies who offer a platform to build your service atop.

Technology has been and will continue to be all about platforms. Look at Windows, the perfect example of an “open” platform that is actually very, very closed. Open in the sense it makes you feel fuzzy inside with all the control you seem to have. But closed when the platform operator decides they need a change of direction and emphasis. If your smart, you realise this and either a) kick the football down the road or b) do your best to plan ahead. Either option is sub-optimal. What platforms do offer you is a foundation to build upon. They save you time, money, engineering talent and when they work well are indispensable.

If you build the platform, you can make a lot of money. Just ask Amazon and Microsoft. Facebook, Twitter and Google are still ramping up their platform efforts. Adobe has just announced the realised their very valuable Flash platform is dead on mobile devices. They realised platforms are very purpose specific (to be valuable) and that value is in the already-mature desktop market – the investment in mobile wasn’t worth it. Adobe has always made money from the tools (as has Microsoft, apart from selling the platform Windows they sell Office, Sharepoint etc) and is focusing on targeting a larger platform in HTML5. If Adobe succeeds they’ll make a lot more money, or even if they capture a small section of the market which is bigger then the previous flash creation tools market.

Monetisation is also tricky for platforms. Amazon’s strategy is similar to Wal-Mart, make it big, reliable and cheap. Only big companies can ever compete with Amazon on that scale. Smaller companies must rely on getting as many people to their platform as possible (to get as big) or creating a niche in say highly regulated environments which are high value but low volume.

In short: Platforms are good, but know when to jump off !

Reflection on 9-11

It’s been 10 years since the anniversary of 9/11 and much of the world has changed a lot in that period. We’ve had full body scanners at airports, marshalls on flights, bombs hidden in toner cartridges and two wars. I reflected on this and remembered two really good articles I’ll share here on the topic. Hopefully we’ve changed for the better.
Continue reading

Thoughts on IPv6

A multitude of websites have been reporting the impending doom of ipv4 exhaustion, which is going to happen soon. All the top level address’ will be gone, but the regional registries will still have stocks of address’ in to 2011. As a user of ipv6, I thought I could share sone thoughts/insights on the events ahead…

Below is a very good video which one of my favourite tech shows, Hak5 made with an IPv6 Consultant, Joe Klein.

http://www.youtube-nocookie.com/v/cl4cEbPayek?fs=1&hl=en_US

My own experience has been straightforward on the set up side of things. We had to purchase an
Apple Airport Extreme router however, which is the biggest pain in the transition, the cost. Most home routers do not have proper IPv6 capability, a serious problem. This will cost the Internet Service providers a lot of money in keeping these old routers shielded from the ever increasing IPv6 enabled websites and services – to the point at which a large scale upgrade may well be cheaper, but this is not likely to happen in the short term.

Datacenter Cabling

Data centers will be one of the first o be all IPv6. (Photo Credit dmitrybarsky)

Setup of IPv6

The funny thing with IPv6 is tht machines self issue address’ and can use them locally if you have an IPv6 capable router, defaulting to IPv4 when going through your NAT to the Internet. So it’s the bridge to your ISP is the issue. Where I set it up, my ISP is small and has no IPv6 support. I emailed them about it, to get no response. It’s probably worth trying again since most ISP’s are running trials now, and you may get a router upgrade if you opt-in now. So I had to set up a tunnel, using the excellent Hurricane Electric. My ISP is slow though (average 1mbps rural wireless) and when the tunnel is set up all traffic defaults to IPv6, it makes it even slower. Tunnels are not ideal because the result will always depend on the quality of connection to your tunnel provider and the overhead that provides. Since IPv6 packets are bigger than IPv4 packets, your going to get a lot more IPv4 packets for the same volume of traffic, the major downside of tunneling. Tunnels are good to get some IPv6 experience, but not much else unless you have a very fast connection. The transition itself will probably look like this:

  1. Tunnels are set up, small contained IPv6 networks exist (already happend)
  2. IPv6 islands merge, major ISP’s peer and inter-network communication switches to IPv6 (happening now)
  3. ISP’s start to use 4to6 tunnels to get to the IPv6 part of the internet
  4. ISP’s switch equipment and use 6to4 tunnels to get to ever decreasing IPv4 Internet
  5. Like Usenet, ISPs state there is no demand for IPv4, and drop it to be fully native IPv6

So I’d advise anyone right now who has the patience and the interest to invest time in IPv6, it’s a game-changing technology, not necessarily better but a must to have knowledge of. As I mentioned earlier Hurricane Electric provide free tunnels (you can even set it up on a single computer if your router can’t support IPv6) and free certification to test these skills