0

I'm using the Twitter4j library to develop a proyect that works with Twitter, one of the things what I need is to get the Direct messages, I'm using the following code:

try{
    List<DirectMessage> loStatusList = loTwitter.getDirectMessages();
    for (DirectMessage loStatus : loStatusList) {
        System.out.println(loStatus.getId() + ",@" + loStatus.getSenderScreenName() + "," + loStatus.getText() + "|");
    }
}
catch(Exception e)

It works fine, but what the code returns is a list of the most recent messages in general. What I want is to get those direct messages using some kind of filter that allows finding them by a user that I indicate.

For example, I need to see the DM only from user @TwitterUser.

Is this posible with this library?

All kinds of suggestions are accepted, even if I should use another library I would be grateful if you let me know.

Daniel
  • 1
  • 1

1 Answers1

1

It looks like the actual Twitter API doesn't support a direct filter on that API, by username anyway. (See Twitter API doc: GET direct_messages.)

Which means, you'd have to make multiple calls to the API with pagination enabled, and cache the responses into a list.

Here is an example of pagination wtih Twitter4J getDirectMessages().

In that example, use the existing:

List<DirectMessage> messages;

But inside the loop, do:

messages.addAll(twitter.getDirectMessages(paging));

Note: you only would have to do this once. And in fact, you should persist these to a durable local cache like Redis or something. Because once you have the last message id, you can ask the Twitter API to only return "messages since id" with the since_id param.

Anyway, then on the client side you'd just do your filtering with the usual means in Java. For example:

// Joe is on twitter as @joe
private static final String AT_JOE = "Joe";

// Java 8 Lambda to filter by screen name
List<DirectMessage> messagesFromJoe = messages.stream()
    .filter(message -> message.getSenderScreenName().equals(AT_JOE))
    .collect(Collectors.toList());

Above, getSenderScreenName() was discovered by reading the Twitter4J API doc for DirectMessage.

Jameson
  • 6,400
  • 6
  • 32
  • 53
  • Thanks for the Info. Is the format of the Direct Message Object that is returned by the API (say using Twitter4J) the same as the normal "home" "timeline" Twitter Message or does it have any distinction as in indicating a Direct Message? – Rahul Saini Apr 04 '17 at 09:16