List of usage examples for twitter4j TwitterStream filter
TwitterStream filter(final String... track);
From source file:me.timothy.twittertoreddit.TwitterToRedditMain.java
License:Open Source License
private void begin() throws InterruptedException { loadConfiguration();/*from ww w . java 2 s . c o m*/ HttpRestClient rClient = new HttpRestClient(); rClient.setUserAgent("TwitterToReddit Bot by /u/Tjstretchalot"); User user = new User(rClient, username, password); try { user.connect(); } catch (Exception e) { System.err.println("Failed to connect"); return; } System.out.println("Succesfully Authenticated to Reddit"); Thread.sleep(1000); System.out.println(".."); Thread.sleep(1000); System.out.println("Authenticating to Twitter.."); TwitterStream stream = new TwitterStreamFactory().getInstance(); FilterQuery filter = new FilterQuery(); filter.follow(new long[] { twitterId }); TwitterToReddit mBot = new TwitterToReddit(rClient, user, twitterId, subreddit); mBot.beginStreaming(stream); stream.filter(filter); System.out.println("Success! The bot is now active and will post new tweets as well as print out here"); System.out.println(); }
From source file:my.twittergui.TwitterUI.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed String text;//from ww w . j a va 2s .c o m text = jTextField1.getText(); //jTextArea1.append(text+"\n"); jTextArea1.append("Searching for: "); String[] strarray = text.split(" "); for (int i = 0; i < strarray.length; i++) { jTextArea1.append(strarray[i] + "\n"); } File filed = null; filed = new File("C:\\Results"); if (!filed.exists()) { filed.mkdir(); } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("") .setOAuthAccessTokenSecret(""); StatusListener listener = new StatusListener() { public void onStatus(Status status) { try { int fileno = 0; String strI = Integer.toString(fileno); String fname = "C:\\results\\DataCol" + strI + ".csv"; File file = new File(fname); FileWriter bw = new FileWriter(file, true); if (file.length() == 0) { bw.write("\"Screen Name\", text, \"created at\", geolocation, Retweet? \r\n"); bw.flush(); } while (file.length() > 10485760) { fileno += 1; strI = Integer.toString(fileno); fname = "DataCol" + strI + ".txt"; file = new File(fname); bw = new FileWriter(file, true); bw.write("\"Screen Name\", \"text\", \"created_at\", \"geolocation\" \r\n"); bw.flush(); } // if(!status.isRetweet()){ bw.write("\r\n"); bw.write("\"" + status.getUser().getScreenName() + "\","); String tweettxt = status.getText(); tweettxt = tweettxt.replace("\n", ""); tweettxt = tweettxt.replace(",", ""); tweettxt = tweettxt.replace("\"", ""); bw.write("\"" + tweettxt + "\","); bw.write("\"" + status.getCreatedAt() + "\","); if (status.getGeoLocation() != null) { bw.write("\"" + status.getGeoLocation() + "\""); } else bw.write("N/A,"); if (status.isRetweet()) bw.write("Yes"); else bw.write("No"); bw.flush(); bw.close(); //System.out.print("\n"); String str = "@" + status.getUser().getScreenName() + " " + status.getText() + " " + status.getCreatedAt() + " "; if (status.getGeoLocation() != null) str += status.getGeoLocation(); //System.out.print(str); jTextArea1.append(str + "\n"); // } bw.close(); } catch (IOException e) { //System.out.print("EXCEPTION"); e.printStackTrace(); } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onStallWarning(StallWarning stall) { } public void onScrubGeo(long a, long b) { } public void onException(Exception ex) { ex.printStackTrace(); } }; TwitterStreamFactory tf = new TwitterStreamFactory(cb.build()); TwitterStream twitterStream = tf.getInstance(); twitterStream.addListener(listener); // Filter FilterQuery filtre = new FilterQuery(); Scanner in = new Scanner(System.in); filtre.track(strarray); twitterStream.filter(filtre); }
From source file:nlptexthatespeechdetection.dataCollection.GetTwitterDoc2VecTrainingData.java
public static void main(String[] args) throws FileNotFoundException, IOException { File dir = new File(folderName); if (!dir.exists()) dir.mkdir();/* ww w. ja v a 2 s . com*/ if (!dir.isDirectory()) { System.out.println(folderName + " is not a directory"); return; } System.out.println("number of tweets required: "); int numTweetsRequired = (new Scanner(System.in)).nextInt(); String path = folderName + "/" + fileName; File file = new File(path); if (!file.exists()) file.createNewFile(); FileWriter writer = new FileWriter(path, true); TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); StatusListener listener = new StatusListener() { int numTweets = 0; @Override public void onStatus(Status status) { if (status.getLang().equals("in")) { try { String statusText = status.getText(); writer.write("\n"); writer.write(statusText); numTweets++; System.out.println("numTweets: " + numTweets); if (numTweets >= numTweetsRequired) { writer.close(); System.exit(0); } } catch (IOException ex) { Logger.getLogger(GetTwitterDoc2VecTrainingData.class.getName()).log(Level.SEVERE, null, ex); } } } @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(); } }; twitterStream.addListener(listener); FilterQuery filterQuery = new FilterQuery(); filterQuery.track(new String[] { "a", "i", "u", "e", "o" }); filterQuery.language("in"); twitterStream.filter(filterQuery); }
From source file:nlptexthatespeechdetection.dataCollection.TwitterStreamingAnnotator.java
public static void main(String[] args) throws NotDirectoryException { Scanner sc = new Scanner(System.in); System.out.println("Nama Anda (sebagai anotator): "); String namaAnotator = sc.nextLine(); AnnotatedDataFolder annotatedDataFolder = new AnnotatedDataFolder(dataFolderName); TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); StatusListener listener = new StatusListener() { @Override/* w ww . j a v a2s . c o m*/ public void onStatus(Status status) { if (status.getLang().equals("in")) { System.out.println(); System.out.println(); System.out.println("=======ANOTASI======="); System.out.println("status: " + status.getText()); System.out.println(); System.out.println("is this a hate speech?(y/n. any other if you do not know)"); String annotatorResponse = sc.nextLine().trim().toLowerCase(); Date date = new Date(); String dateString = dateFormat.format(date); try { if (annotatorResponse.equals("y")) { String filePath = annotatedDataFolder.saveHateSpeechString(namaAnotator, dateString, status.getText()); System.out.println("Saved data to: " + filePath); } else if (annotatorResponse.equals("n")) { String filePath = annotatedDataFolder.saveNotHateSpeechString(namaAnotator, dateString, status.getText()); System.out.println("Saved data to: " + filePath); } System.out.println("thank you!"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { Logger.getLogger(TwitterStreamingAnnotator.class.getName()).log(Level.SEVERE, null, ex); } } else { System.out.println("ignoring non-indonesian tweet"); } // if (status.getGeoLocation() != null) { // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * " + status.getId() + " $ " + status.getGeoLocation().toString()); // } // if (status.getLang().equals("id")) { // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * " + status.getId() + " # " + status.getLang() + " $ " + (status.getGeoLocation() == null ? "NULLGEO" : status.getGeoLocation().toString())); // } } @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(); } }; twitterStream.addListener(listener); FilterQuery filterQuery = new FilterQuery(); filterQuery.track(new String[] { "a", "i", "u", "e", "o" }); filterQuery.language("in"); twitterStream.filter(filterQuery); }
From source file:nlptexthatespeechdetection.NLPTextHateSpeechDetection.java
/** * @param args the command line arguments *//*from w w w .j a v a 2 s .c o m*/ public static void main(String[] args) throws TwitterException, NotDirectoryException, IOException { HateSpeechClassifier1 classifier = new HateSpeechClassifier1(); AnnotatedDataFolder data = new AnnotatedDataFolder("data"); boolean overSampling = false; classifier.train(data.getDateSortedLabeledData(overSampling)); TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); StatusListener listener = new StatusListener() { int numHateSpeech = 0; int numTweets = 0; @Override public void onStatus(Status status) { if (status.getLang().equals("in")) { numTweets++; if (classifier.isHateSpeech(status.getText(), 0.5)) { System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * " + status.getId() + " # " + status.getLang() + " $ " + (status.getGeoLocation() == null ? "NULLGEO" : status.getGeoLocation().toString())); System.out.println(); System.out.println("lang: " + status.getLang()); System.out.println("number of detected hate speech: " + numHateSpeech); System.out.println("total number of streamed tweets: " + numTweets); System.out.println(); System.out.println(); numHateSpeech++; } } else { System.out.println("ignoring non-Indonesian tweet"); } // if (status.getGeoLocation() != null) { // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * " + status.getId() + " $ " + status.getGeoLocation().toString()); // } // if (status.getLang().equals("id")) { // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * " + status.getId() + " # " + status.getLang() + " $ " + (status.getGeoLocation() == null ? "NULLGEO" : status.getGeoLocation().toString())); // } } @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(); } }; twitterStream.addListener(listener); FilterQuery filterQuery = new FilterQuery(); filterQuery.track(new String[] { "a", "i", "u", "e", "o" }); filterQuery.language("in"); twitterStream.filter(filterQuery); twitterStream.sample(); }
From source file:org.rtsa.storm.TwitterSpout.java
License:Apache License
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { queue = new LinkedBlockingQueue<Status>(1000); _collector = collector;/*from www. ja va 2 s . c o m*/ StatusListener listener = new StatusListener() { public void onStatus(Status status) { if (status.getText().length() != 0 && status.getLang().equals("en")) { queue.offer(status); } } public void onDeletionNotice(StatusDeletionNotice sdn) { } public void onTrackLimitationNotice(int i) { } public void onScrubGeo(long l, long l1) { } public void onException(Exception ex) { } public void onStallWarning(StallWarning arg0) { // TODO Auto-generated method stub } }; TwitterStream twitterStream = new TwitterStreamFactory( new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance(); twitterStream.addListener(listener); twitterStream.setOAuthConsumer(consumerKey, consumerSecret); AccessToken token = new AccessToken(accessToken, accessTokenSecret); twitterStream.setOAuthAccessToken(token); if (keyWords.length == 0) { twitterStream.sample(); } else { FilterQuery query = new FilterQuery().track(keyWords); twitterStream.filter(query); } }
From source file:org.selman.tweetamo.TweetamoClient.java
License:Apache License
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: [language] [search topic]"); }// w ww . jav a2 s .c o m kinesisClient = new AmazonKinesisClient(new ClasspathPropertiesFileCredentialsProvider()); waitForStreamToBecomeAvailable(STREAM_NAME); LOG.info("Publishing tweets to stream : " + STREAM_NAME); StatusListener listener = new StatusListener() { public void onStatus(Status status) { try { PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(STREAM_NAME); putRecordRequest.setData(TweetSerializer.toBytes(status)); putRecordRequest.setPartitionKey(status.getUser().getScreenName()); PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest); LOG.info("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey() + ", ShardID : " + putRecordResult.getShardId()); } catch (Exception e) { LOG.error("Failed to putrecord", e); } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onException(Exception ex) { ex.printStackTrace(); } @Override public void onScrubGeo(long arg0, long arg1) { } @Override public void onStallWarning(StallWarning arg0) { } }; ClasspathTwitterCredentialsProvider provider = new ClasspathTwitterCredentialsProvider(); TwitterCredentials credentials = provider.getTwitterCredentials(); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(credentials.getConsumerKey()) .setOAuthConsumerSecret(credentials.getConsumerSecret()) .setOAuthAccessToken(credentials.getAccessToken()) .setOAuthAccessTokenSecret(credentials.getAccessTokenSecret()); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); twitterStream.addListener(listener); FilterQuery filterQuery = new FilterQuery(); filterQuery.language(new String[] { args[0] }); filterQuery.track(new String[] { args[1] }); twitterStream.filter(filterQuery); }
From source file:org.smarttechie.servlet.SimpleStream.java
public void getStream(TwitterStream twitterStream, String[] parametros, final Session session)//,PrintStream out) { listener = new StatusListener() { @Override/*from www . ja v a2 s . c o m*/ public void onException(Exception arg0) { // TODO Auto-generated method stub } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { // TODO Auto-generated method stub } @Override public void onScrubGeo(long arg0, long arg1) { // TODO Auto-generated method stub } @Override public void onStatus(Status status) { Twitter twitter = new TwitterFactory().getInstance(); User user = status.getUser(); // gets Username String username = status.getUser().getScreenName(); System.out.println(""); String profileLocation = user.getLocation(); System.out.println(profileLocation); long tweetId = status.getId(); System.out.println(tweetId); String content = status.getText(); System.out.println(content + "\n"); JSONObject obj = new JSONObject(); obj.put("User", status.getUser().getScreenName()); obj.put("ProfileLocation", user.getLocation().replaceAll("'", "''")); obj.put("Id", status.getId()); obj.put("UserId", status.getUser().getId()); //obj.put("User", status.getUser()); obj.put("Message", status.getText().replaceAll("'", "''")); obj.put("CreatedAt", status.getCreatedAt().toString()); obj.put("CurrentUserRetweetId", status.getCurrentUserRetweetId()); //Get user retweeteed String otheruser; try { if (status.getCurrentUserRetweetId() != -1) { User user2 = twitter.showUser(status.getCurrentUserRetweetId()); otheruser = user2.getScreenName(); System.out.println("Other user: " + otheruser); } } catch (Exception ex) { System.out.println("ERROR: " + ex.getMessage().toString()); } obj.put("IsRetweet", status.isRetweet()); obj.put("IsRetweeted", status.isRetweeted()); obj.put("IsFavorited", status.isFavorited()); obj.put("InReplyToUserId", status.getInReplyToUserId()); //In reply to obj.put("InReplyToScreenName", status.getInReplyToScreenName()); obj.put("RetweetCount", status.getRetweetCount()); if (status.getGeoLocation() != null) { obj.put("GeoLocationLatitude", status.getGeoLocation().getLatitude()); obj.put("GeoLocationLongitude", status.getGeoLocation().getLongitude()); } JSONArray listHashtags = new JSONArray(); String hashtags = ""; for (HashtagEntity entity : status.getHashtagEntities()) { listHashtags.add(entity.getText()); hashtags += entity.getText() + ","; } if (!hashtags.isEmpty()) obj.put("HashtagEntities", hashtags.substring(0, hashtags.length() - 1)); if (status.getPlace() != null) { obj.put("PlaceCountry", status.getPlace().getCountry()); obj.put("PlaceFullName", status.getPlace().getFullName()); } obj.put("Source", status.getSource()); obj.put("IsPossiblySensitive", status.isPossiblySensitive()); obj.put("IsTruncated", status.isTruncated()); if (status.getScopes() != null) { JSONArray listScopes = new JSONArray(); String scopes = ""; for (String scope : status.getScopes().getPlaceIds()) { listScopes.add(scope); scopes += scope + ","; } if (!scopes.isEmpty()) obj.put("Scopes", scopes.substring(0, scopes.length() - 1)); } obj.put("QuotedStatusId", status.getQuotedStatusId()); JSONArray list = new JSONArray(); String contributors = ""; for (long id : status.getContributors()) { list.add(id); contributors += id + ","; } if (!contributors.isEmpty()) obj.put("Contributors", contributors.substring(0, contributors.length() - 1)); System.out.println("" + obj.toJSONString()); insertNodeNeo4j(obj); //out.println(obj.toJSONString()); String statement = "INSERT INTO TweetsClassification JSON '" + obj.toJSONString() + "';"; executeQuery(session, statement); } @Override public void onTrackLimitationNotice(int arg0) { // TODO Auto-generated method stub } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; FilterQuery fq = new FilterQuery(); fq.track(parametros); twitterStream.addListener(listener); twitterStream.filter(fq); }
From source file:org.socialsketch.tool.rubbish.twitterstream.PrintFilterStream.java
License:Apache License
/** * Main entry of this application./*from w ww .j ava2 s . c om*/ * * @param args follow(comma separated user ids) track(comma separated filter terms) * @throws twitter4j.TwitterException */ public static void main(String[] args) throws TwitterException { // if (args.length < 1) { // System.out.println("Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]"); // System.exit(-1); // } 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(); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); ArrayList<Long> follow = new ArrayList<Long>(); ArrayList<String> track = new ArrayList<String>(); // for (String arg : args) { // if (isNumericalArgument(arg)) { // for (String id : arg.split(",")) { // follow.add(Long.parseLong(id)); // } // } else { // track.addAll(Arrays.asList(arg.split(","))); // } // } track.add("void setup draw"); track.add("void size"); long[] followArray = new long[follow.size()]; for (int i = 0; i < follow.size(); i++) { followArray[i] = follow.get(i); } String[] trackArray = track.toArray(new String[track.size()]); // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. twitterStream.filter(new FilterQuery(0, followArray, trackArray)); }
From source file:org.threeriverdev.twitterreporter.TwitterBot.java
License:Apache License
public static void main(String... args) throws Exception { FilterQuery query = new FilterQuery(); List<double[]> locations = new ArrayList<double[]>(); // Create a grid over the continental US. // TODO: Originally (2009ish), these were recommended by Twitter. Not sure if it's relevant now or not -- // could we achieve the same results with 1 big block? for (double swLat = 25.0; swLat <= 49.0; swLat = swLat + GRIDSIZE) { for (double swLon = -125.0; swLon <= -67.0; swLon = swLon + GRIDSIZE) { double neLat = swLat + GRIDSIZE; double neLon = swLon + GRIDSIZE; double[] swLocation = new double[2]; swLocation[0] = swLon;/*from w ww .j av a 2 s. c om*/ swLocation[1] = swLat; locations.add(swLocation); double[] neLocation = new double[2]; neLocation[0] = neLon; neLocation[1] = neLat; locations.add(neLocation); } } query.locations(locations.toArray(new double[0][0])); try { URL url = TwitterBot.class.getResource("/oauth.properties"); Properties p = new Properties(); InputStream inStream = url.openStream(); p.load(inStream); ConfigurationBuilder confBuilder = new ConfigurationBuilder(); confBuilder.setOAuthConsumerKey(p.getProperty("consumer.key")); confBuilder.setOAuthConsumerSecret(p.getProperty("consumer.secret")); confBuilder.setOAuthAccessToken(p.getProperty("access.token")); confBuilder.setOAuthAccessTokenSecret(p.getProperty("access.token.secret")); Configuration conf = confBuilder.build(); TwitterStream twitterStream = new TwitterStreamFactory(conf).getInstance(); twitterStream.addListener(new TweetProcessor()); twitterStream.filter(query); } catch (Exception e) { e.printStackTrace(); } }