ZOFTINO.COM android and web dev tutorials

Automate Message Posting to Twitter

If you can derive useful Twitter messages or data from your application database, there is no need to login to Twitter and post messages manually to communicate with your Twitter users. Automating message posting to Twitter not only helps save resources but it also helps in posting accurate messages provided you have right source of data which you want to communicate to your Twitter Users.

Twitter provides several APIs to read and write messages to Twitter. There are frame works in different languages which can be used to write programs to connect to Twitter for reading and writing data.

There are rules and limits for using Twitter APIs. Before start using Twitter API, it is better to understand rules and especially rate limits. If you violate rate limits, your account will get banned from using Twitter API. There is Twitter Rest API documentation with all the details about rate limits.

It is easy to write a program to post messages on Twitter using Twitter4J which is a java base frame work to access Twitter API. With Twitter4J you can post simple text message and message with image. To access your Twitter account via Twitter Rest API, you need consumer key and secret & access token key and secret of your Twitter app.

Below is the program which can be used to post simple text message or message with image.


	public boolean postMessageToTwitter(String message, File imageFile) throws Exception{
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setOAuthConsumerKey("consumerKeyStr");
		cb.setOAuthConsumerSecret("consumerSecretStr");
		cb.setOAuthAccessToken("accessTokenStr");
		cb.setOAuthAccessTokenSecret("accessTokenSecretStr");

		TwitterFactory tf = new TwitterFactory(cb.build());
		Twitter twitter = tf.getInstance();

		StatusUpdate status = new StatusUpdate(message);	
		if(imageFile != null){
			status.setMedia(imageFile);
		}
		
		twitter.updateStatus(status);

		return true;
	}

This program can be called from your main program which retrieves list of messages to be posted and posts messages to Twitter one by one with some delay between two messages. Delay between messages is required to comply with Twitter Api rate limit. Thread.Sleep can be used to achieve delay between two messages.