8
votes

Is it possible to get tweets which contain photos? I am currently using twitter search api and getting all the tweets having entity details by setting include_entities=true. I see picture details under media object but is there anyway to filter and get tweets objects which just have these media items. Or is there anyway in Twitter4j to do this query?

4

4 Answers

16
votes

There is no specific way to specify that I need only photos or videos but you can filter the results based on filter:links or filter:images or filter:videos in your query along with include_entities=true.

For Example: To get the tweets that contain links since 2012-01-31, you query should have include_entities parameter as well as filter:links as shown as follows:

https://search.twitter.com/search.json?q=from%3Agoogle%20since%3A2012-01-31%20filter%3Alinks&include_entities=true"

As your need is to filter your tweets based on images/photos, I think you should use filter:images.

An example of your case would look like:

https://search.twitter.com/search.json?q=from%3Agoogle%20since%3A2012-01-31%20filter%3Aimages&include_entities=true"

Hope this helps.

2
votes

With Latest twitter API I couldn't get filters work and I couldn't find either any explanation in their docs. Althought you can get all the tweets and then parse only the media ones. You can fire this if inside your parsing script:

if(this.entities.media != null){
  //Parse the tweet
}

This is not the best solution but the worst part comes to twitter who's giving you more information and using more of its own resources.

0
votes

In the lastest twitter API you can do it in the ConfigurationBuilder instance, before creating the Twitter instance:

ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(false);
cb.setOAuthConsumerKey(API_KEY);
cb.setOAuthConsumerSecret(API_SECRET);
cb.setOAuthAccessToken(ACCESS_TOKEN);
cb.setOAuthAccessTokenSecret(SECRET_KEY);
// enabling include_entities parameters
cb.setIncludeEntitiesEnabled(true);
Twitter twitterInstance = new TwitterFactory(cb.build()).getInstance();

Also, after enabling the entities, in the search string you have to had the condition "filter:images".

List<String> keywords = new ArrayList<String>();
keywords.add("#pet");
keywords.add("cat");
// String.join for Java 8
String twitterSearchString = "((" + String.join(" OR ", keywords) + ")";
// adding the filter condition
twitterSearchString  += " AND filter:images)";
Query q = new Query(twitterSearchString);

And you will get just results with images (tested with twitter4j-core 4.0.4).

0
votes

For filter in twitter API you can check official document for latest version as on date Apr 02 2019

https://developer.twitter.com/en/docs/tweets/search/guides/standard-operators.html