Search code examples
twitter4jtwitter-streaming-api

How to change keywords on twitter stream api using twitter4j?


I am using twitter4j to connect to Stream API.

I understand that from this post, Change Twitter stream filter keywords without re-opening stream, there is no way to change keywords while the connection is open. I have to disconnect and change the filter predicate and reconnect it.

I would like to know if there is any code sample that would allow me to disconnect it, change the keywords and reconnect it?

Currently, I tried to do this in the StatusListener under onStatus() where after an X amount of time has passed, it will change the keyword to "juice". But there is no method for me to close the connection and reconnect to Stream API.

if (diff>=timeLapse) {
   StatusListener listener = createStatusListener();
   track = "juice";
   twitterStream = new TwitterStreamFactory().getInstance();
   twitterStream.addListener(listener);
   FilterQuery fq = new FilterQuery();
   fq.track(new String[] {track});
   startTime=System.currentTimeMillis();
   twitterStream.filter(fq);
}

Solution

  • You need to cleanUp() the stream first and then open a new stream with filter(FilterQuery) method to change track terms.