Twitter java application

twitter4j
java
api

#1

Hi! I am a beginner in programming and please I want you to help me. how can I retrieve and display the notifications, followers, following and messages of my account Twitter in my java application.I use twitter4j and eclipse luna. I want also write a direct message and i display it in my application. Please do you have videos or links to help me Thank you very much!


#2

The Twitter4J code examples are pretty good and should be a good starting point for you.


#3

Thank you very much.


#4

I tried this code to send direct messages but i have these errors when running. This is the code that i wrote:

try {
            DirectMessage message = tw.sendDirectMessage("my name", "slt!");
            System.out.println("Direct message successfully sent to " + message.getRecipientScreenName());
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to send a direct message: " + te.getMessage());
            System.exit(-1);
        }

and these are the errors:

400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
message - Recipient (user, screen name, or id) parameter is missing.
code - 38

Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=9bf58966 or http://www.google.co.jp/search?q=1431cdb7

TwitterException{exceptionCode=[9bf58966-1431cdb7], statusCode=400, message=Recipient (user, screen name, or id) parameter is missing., code=38, retryAfter=-1, rateLimitStatus=null, version=4.0.5-SNAPSHOT(build: 9b7efa6faa540a9defb3e6ba9122a356155986b1)}
	at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
	at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
	at twitter4j.HttpClientBase.post(HttpClientBase.java:86)
	at twitter4j.TwitterImpl.post(TwitterImpl.java:1822)
	at twitter4j.TwitterImpl.sendDirectMessage(TwitterImpl.java:308)
	at projet1.Mon_Application.main(Mon_Application.java:58)
Failed to send a direct message: 400:The request was invalid. An accompanying error message will explain why. This is the status code will be returned during version 1.0 rate limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request without authentication is considered invalid and you will get this response.
message - Recipient (user, screen name, or id) parameter is missing.
code - 38

Can you help me please?

other way : when i wrote this code which is written in http://twitter4j.org/en/code-examples.html#directMessage
i wrote :

Twitter sender = TwitterFactory.getSingleton();
    DirectMessage message = sender.sendDirectMessage(recipientId, message);
    System.out.println("Sent: " message.getText() + " to @" + message.getRecipientScreenName());

these expressions become underlined in red : recipientId and message.getText()
and i can’t ran the project.

NB: i wrote in the beginning

ConfigurationBuilder cb=new ConfigurationBuilder();
		cb.setDebugEnabled(true)
		   .setOAuthConsumerKey("XXXXXXXX")
		   .setOAuthConsumerSecret("XXX")
		   .setOAuthAccessToken("XXXX")
		   .setOAuthAccessTokenSecret("XXXXXXXXXXXX");
		   
		TwitterFactory tf=new TwitterFactory(cb.build());
		twitter4j.Twitter tw=tf.getInstance()

Can you help me please?


#5

“my name” is not a Twitter screen name, which this code expects. You’d need to put the user’s @handle (without the @).

I assume you’ve imported the DirectMessage class?


#6

YES ! I did it! Thank you very very very much :smiley: :wink:
I wrote my user’s @handle (without the @ ).


#7

Mr, sorry i disturb and bother you but i need help.
Now I write this code to display my followers :smile:

try {
        long cursor = -1;
        IDs ids;
        System.out.println("Listing followers's ids.");
        do {
            if (0 < args.length) {
                ids = tw.getFollowersIDs(args[0], cursor);
            } else {
                ids = tw.getFollowersIDs(cursor);
            }
            for (long id : ids.getIDs()) {
                System.out.println(id);
            }
        } while ((cursor = ids.getNextCursor()) != 0);
        System.exit(0);
	}
	catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);} 

and when running it i obtained this :
Listing followers’s ids.
xxxxxxxxxx
xxxxxxxxxx

where the x is a number so i obtained the ids but i want to obtain the name of followers so what you think can do ?? can i “convert” these ids into their names or what? Thank you very much.


#8

I’d throw those IDs into a lookupUsers call and parse out the names of the users from the response.


#9

Thank you. But I tried with lookupUsers but it doesn’t work. Can you help me again. Where should i write lookupUsers(id) ?

I tried also this code :

try {
			 TwitterFactory tf=new TwitterFactory(cb.build());
				twitter4j.Twitter tw=tf.getInstance();
				
			            ResponseList<User> users = tw.lookupUsers(args[0].split(","));
			            for (User user : users) {
			                if (null != user.getStatus()) {
			                     System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText());
			                } else {
			                    // the user is protected
			                    System.out.println("@" + user.getScreenName());
			                 }
			             }
			            System.out.println("Successfully looked up users [" + args[0] + "].");
			             System.exit(0);
			         } catch (TwitterException te) {
			            te.printStackTrace();
			             System.out.println("Failed to lookup users: " + te.getMessage());
			             System.exit(-1);
			         }

Is this code give me the name of folloawers? but when i wrote it, it give me exception and i didn’t know how i correct it.
this exception appears :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at projet1.Mon_Application.main(Mon_Application.java:104)

Can you help me?

Other question please:
My application can display the timeline, write a tweet and write direct message but these functionalities work only on my account (from my application and my twitter account) now i want to access to other accounts of users. They should write their emails and their passwords in my application and my application should display for the user his timeline, he can also write a tweet in his account of twitter…
What should i do to connect the twitter account of any user with my application. My appliacation consist in doing a twitter USSD application.
Can you help me please?
Should i write this or something else?

Initially, you don’t have a permission to access the user’s account and need to acquire access token by redirecting the user to an authorization URL as follows:

  public static void main(String args[]) throws Exception{
    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
      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){
           accessToken = twitter.getOAuthAccessToken(requestToken, pin);
         }else{
           accessToken = twitter.getOAuthAccessToken();
         }
      } catch (TwitterException te) {
        if(401 == te.getStatusCode()){
          System.out.println("Unable to get the access token.");
        }else{
          te.printStackTrace();
        }
      }
    }
    //persist to the accessToken for future reference.
    storeAccessToken(twitter.verifyCredentials().getId() , accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
  }
  private static void storeAccessToken(int useId, AccessToken accessToken){
    //store accessToken.getToken()
    //store accessToken.getTokenSecret()
  }

After you acquired the AccessToken for the user, the RequestToken is not required anymore. You can persist the AccessToken to any kind of persistent store such as RDBMS, or File system by serializing the object, or by geting the token and the secret from AccessToken#getToken() and AccessToken#getTokenSecret().

  public static void main(String args[]) throws Exception{
    // The factory instance is re-useable and thread safe.
    TwitterFactory factory = new TwitterFactory();
    AccessToken accessToken = loadAccessToken(Integer.parseInt(args[0]));
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumerKey("[consumer key]", "[consumer secret]");
    twitter.setOAuthAccessToken(accessToken);
    Status status = twitter.updateStatus(args[1]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
  }
  private static AccessToken loadAccessToken(int useId){
    String token = // load from a persistent store
    String tokenSecret = // load from a persistent store
    return new AccessToken(token, tokenSecret);
  }

Because i did’nt understand them.

Sorry but i need help and thank you very much .


#10

Please can you help me. I need you and thank you very much .


#11

Hi, i want to display list of received direct messages and i wrote this code :
ConfigurationBuilder cb1=new ConfigurationBuilder();
cb1.setDebugEnabled(true)
.setOAuthConsumerKey(“xxxxxxxxxxxxxxx”)
.setOAuthConsumerSecret(“xxxxxxxxxxxxxxx”)
.setOAuthAccessToken(“xxxxxxxxxxxxxxxxx”)
.setOAuthAccessTokenSecret(“xxxxxxxxxxxxxxxx”);

	        try {
	        	TwitterFactory tf=new TwitterFactory(cb1.build());
				twitter4j.Twitter tw=tf.getInstance();
	            Paging paging = new Paging(1);
	            List<DirectMessage> messages;
	            do {
	                messages = ((DirectMessagesResources) tw).getDirectMessages(paging);
	                for (DirectMessage message : messages) {
	                    System.out.println("From: @" + message.getSenderScreenName()   + " --- "
	                            + message.getText()+" ---- reçu à la date : "+message.getCreatedAt());
	                }
	                paging.setPage(paging.getPage() + 1);
	            } while (messages.size() > 0 && paging.getPage() < 10);
	            System.out.println("done.");
	            System.exit(0);
	        } catch (TwitterException te) {
	            te.printStackTrace();
	            System.out.println("Failed to get messages: " + te.getMessage());
	            System.exit(-1);
	        }

but it doesn’t work. I had this errors :
Failed to get messages: 403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
message - This application is not allowed to access or delete your direct messages.
code - 93

403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
message - This application is not allowed to access or delete your direct messages.
code - 93

Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=7da221bb or
http://www.google.co.jp/search?q=11fbb269
TwitterException{exceptionCode=[7da221bb-11fbb269], statusCode=403, message=This application is not allowed to access or delete your direct messages., code=93, retryAfter=-1, rateLimitStatus=RateLimitStatusJSONImpl{remaining=14, limit=15, resetTimeInSeconds=1438338113, secondsUntilReset=4371}, version=4.0.4}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1786)
at twitter4j.TwitterImpl.getDirectMessages(TwitterImpl.java:269)
at Mon_Application.messages(Mon_Application.java:300)
at Mon_Application.accueil(Mon_Application.java:112)
at Mon_Application.connexion(Mon_Application.java:83)
at Mon_Application.main(Mon_Application.java:40)

and when i created the developer account i made for permissions : Read, Write and Access direct messages . So why it told me this : This application is not allowed to access or delete your direct messages.
Please I need your help and i wait your answers and thank you very much.


Display notifications of an account twitter in a java application using twitter4j