Trying to Pull Images from Twitter

Hello there,

I am quite new to this so please bear with me. I am trying to use a keyword search to pull images from twitter using twitter4j. I want it to show the images positioned randomly on the screen in a loop.

This code I have below is a combination of different ones I have found online. Its currently finding tweets using these keywords and showing them in the console, however, it is not displaying them on the screen and I’m not sure why…

Another thing is that I think it is doing a live stream from twitter so pulling tweets immediately at the time the code is run, so I am not getting lots of results when I put in an obscure keyword, I want it to search for the last 100 tweets with images using the keywords.

From another project I’ve worked on I know a query search gave me way more results but I’ve tried to apply that here with no success :confounded:

Query query = new Query("#SudaneseCulture"); 
  query.setCount(100);

I’d really appreciate all the help I can get! thank you

///////////////////////////// Config your setup here! ////////////////////////////

// { site, parse token }
String imageService[][] = { 
  {"http://twitpic.com",   "<img class=\"photo\" id=\"photo-display\" src=\""},
  {"http://twitpic.com",   "<img class=\"photo\" id=\"photo-display\" src=\""}, 
  {"http://img.ly",        "<img alt=\"\" id=\"the-image\" src=\"" }, 
  {"http://lockerz.com/", "<img id=\"photo\" src=\""}, 
  {"http://instagr.am/",   "<meta property=\"og:image\" content=\""} 
};

// This is where you enter your Oauth info
static String OAuthConsumerKey = "zUuYo8gWYnHe93WBL3CMr6I7t";
static String OAuthConsumerSecret = "RzvfBJkOq9C5usb63Z7TRMSOVmHMaqiIizYJn7nQop8oApP8BY";
static String AccessToken = "1042449081975627777-7M4OeQcEKKA0lNNapBFN4e1GouJoLr";
static String AccessTokenSecret = "0lW5YtWslAa9UnjcxUW9ESfDI5TxWzAndR3kvaDKwG2Kj";

// if you enter keywords here it will filter, otherwise it will sample

String keywords[] = {"Sudani", "Sudanese", "SudaneseCulture","#SudaneseCulture" , "@voicesofSudan" //sample keyword!!!!!!!!
};
  
///////////////////////////// End Variable Config ////////////////////////////

TwitterStream twitter = new TwitterStreamFactory().getInstance();
 

PImage img;
boolean imageLoaded;

void setup() {
  frameRate(10); 
  size(800, 600);
  noStroke();
  imageMode(CENTER);

  connectTwitter();
  twitter.addListener(listener);
  if (keywords.length==0) twitter.sample();
  else twitter.filter(new FilterQuery().track(keywords));
}

void draw() {
  background(0);
  if (imageLoaded) image(img, width/5, height/5);
  //image(loadImage((status.getUser().getImage())), (int)random(width*.45), height-(int)random(height*.4));
}

// Initial connection
void connectTwitter() {
  twitter.setOAuthConsumer(OAuthConsumerKey, OAuthConsumerSecret);
  AccessToken accessToken = loadAccessToken();
  twitter.setOAuthAccessToken(accessToken);
}

// Loading up the access token
  private static AccessToken loadAccessToken() {
  return new AccessToken(AccessToken, AccessTokenSecret);
}

// This listens for new tweet
  StatusListener listener = new StatusListener() {
 
  //@Override
  public void onStatus(Status status) {
  System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
  }
 
  //@Override
  public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
    System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
  }
 
  //@Override
  public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
    System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
  }
 
  //@Override
  public void onScrubGeo(long userId, long upToStatusId) {
    System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
  }
 
  //@Override
  public void onStallWarning(StallWarning warning) {
    System.out.println("Got stall warning:" + warning);
  }
 
  //@Override
  public void onException(Exception ex) {
    ex.printStackTrace();
  }
};
  public void onStatus(Status status) {

    String imgUrl = null;
    String imgPage = null;

// Checks for images posted using twitter API

    if (status.getMediaEntities() != null) {
      imgUrl= status.getMediaEntities()[0].getMediaURL().toString();
    }
// Checks for images posted using other APIs

    else {
      if (status.getURLEntities().length > 0) {
        if (status.getURLEntities()[0].getExpandedURL() != null) {
          imgPage = status.getURLEntities()[0].getExpandedURL().toString();
        }
        else {
          if (status.getURLEntities()[0].getDisplayURL() != null) {
            imgPage = status.getURLEntities()[0].getDisplayURL().toString();
          }
        }
      }

      if (imgPage != null) imgUrl  = parseTwitterImg(imgPage);
    }

    if (imgUrl != null) {

      println("found image: " + imgUrl);

      // hacks to make image load correctly

      if (imgUrl.startsWith("//")){
        println("s3 weirdness");
        imgUrl = "http:" + imgUrl;
      }
      if (!imgUrl.endsWith(".jpg")) {
        byte[] imgBytes = loadBytes(imgUrl);
        saveBytes("tempImage.jpg", imgBytes);
        imgUrl = "tempImage.jpg";
      }

      println("loading " + imgUrl);
      img = loadImage(imgUrl);
      imageLoaded = true;
    }
  }

public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
   System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
 }
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
    System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
  }
public void onScrubGeo(long userId, long upToStatusId) {
    System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
  }

  public void onException(Exception ex) {
  ex.printStackTrace();
  }
  
// Twitter doesn't recognize images from other sites as media, so must be parsed manually
// You can add more services at the top if something is missing

String parseTwitterImg(String pageUrl) {

  for (int i=0; i<imageService.length; i++) {
    if (pageUrl.startsWith(imageService[i][0])) {

      String fullPage = "";  // container for html
      String lines[] = loadStrings(pageUrl); // load html into an array, then move to container
      for (int j=0; j < lines.length; j++) { 
        fullPage += lines[j] + "\n";
      }

      String[] pieces = split(fullPage, imageService[i][1]);
      pieces = split(pieces[1], "\""); 

      return(pieces[0]);
    }
  }
  return(null);
}