How to change keywords in twitter stream api using twitter4j?

I am using twitter4j to connect to the Stream API.

I understand that from this message Change the keywords of the Twitter stream filter without reopening the stream , it is impossible to change the 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 sample code that will allow me to disable it, change keywords and reconnect it?

I am currently trying to do this in the StatusListener in onStatus (), where after X minutes have passed, it will change the keyword to "juice". But for me there is no way to close the connection and reconnect to the 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); } 
+7
source share
2 answers

First you need to clear Up (), and then open a new stream with a filter (FilterQuery) to change the conditions of the track.

+4
source

You can do this by simply typing Filter(query) again, no need to call cleanUp() , since calling Filter(query) does this for you. This is how I do it and there is no need to stop / restart the stream!

 private TwitterStream twitterStream; private void filterTwitterStream() { if (conditionToStopStreaming) { if (null != twitterStream) { twitterStream.shutdown(); twitterStream = null; } } else { if (twitterStream == null) { twitterStream = new TwitterStreamFactory(getConfiguration()).getInstance(); twitterStream.addListener(getListener()); } FilterQuery qry = new FilterQuery(); String[] keywords = {......} qry.track(keywords); twitterStream.filter(qry); } } 

Where getConfiguration() returns my Configuration object and getListener() returns my defined StatusListener() object

+1
source

All Articles