List of usage examples for twitter4j Status getText
String getText();
From source file:twitterGateway_v2_06.java
License:Creative Commons License
public void OscToTwitter(String OscToTwitterMessage) { ActivityLogAddLine("OSC RECV " + OscRecvAddress + " " + OscToTwitterMessage); try {/*w ww . j a v a2 s . c o m*/ if (twitterOut.getAuthorization().isEnabled()) { Status status = twitterOut.updateStatus(OscToTwitterMessage); System.out.println("Successfully updated the status to [" + status.getText() + "]."); } else { println("ERROR Check authorisation!"); } } catch (TwitterException ex) { println(ex); } ActivityLogAddLine("TWITTER SEND " + OscToTwitterMessage); }
From source file:DumpRetrievedTweet.java
private void GetTweetData() throws TwitterException, IOException { System.out.println("Seting up twitter"); Twitter twitter = new TwitterFactory().getInstance(); // String CONSUMER_KEY = "9zVRlQTXlTKf4QeYMiucyXqg9"; // String CONSUMER_SECRET = "xH0H2SfcXj914z1DGB7HgZZ012ntSqRbfnLFw5A6v1TB94Y2O1"; // String TWITTER_TOKEN = "753222147695259648-QnzInB98PtwpFb75dqlP1J7SSOQMcMX"; // String TWITTER_TOKEN_SECRET = "uxJHGE1e2kFBJYoNRRFfy5gBLXYaRrzCUycRncSkoLsle"; // String CONSUMER_KEY = "nNV9KxWFVmdI0a2shhJImcEGk"; // String CONSUMER_SECRET = "I4AvaGOZRFtLFTqAkpKrfFOnV13Ej2seiwnNQ47z0qE9ORoBhW"; // String TWITTER_TOKEN = "753222147695259648-kY3Gq1O6FqHw6LQViuTQAhLbEQLZRZX"; // String TWITTER_TOKEN_SECRET = "a6hsmYipeGvqJcrIUUZah4ZhH7B8wbY77hqNWwojQysiO"; // String CONSUMER_KEY = "PBMKK9P2YD9MFgDfdANQt2Zzc"; // String CONSUMER_SECRET = "ldB0FybCQIjfYLzuYE4CeGtvcevaSkFxPENGbFd19Yn2crXa5R"; // String TWITTER_TOKEN = "753222147695259648-ZWqj3CvdQAXeVl9zfa71BCRcxeD2yAi"; // String TWITTER_TOKEN_SECRET = "1bypYSL1D1t1Gt6nQLwEbyRg5rniOUHfJhTYuVWYWvAvP"; // String CONSUMER_KEY = "tf0Cbp3ZQcJh9vwkQ9vInw6WS"; // String CONSUMER_SECRET = "gRmcjuqrSH40K47CkRFEO5OVthUtExEW7xrZU2oWiRcpPmzRz9"; // String TWITTER_TOKEN = "126239739-qaXgO4urp91PXLT2RgkxlyONwAQyXnq236dhqtTe"; // String TWITTER_TOKEN_SECRET = "AIykIeAKGFHRucTPgNYZd9bqdbZEJQhMsF5cGiyBLUII7"; String CONSUMER_KEY = "EmmSsTEML5XrB3SYBUOOKxqn6"; String CONSUMER_SECRET = "J1TrjmcqhBd1cURBTjUCwNqcf5IxCfdInAs74TVT9axvSwLnlJ"; String TWITTER_TOKEN = "126239739-ktoaE8NhM4S9CjFhrktTdpuvY7fkbqj1nYxfaQsD"; String TWITTER_TOKEN_SECRET = "a5fFQbKO9meoqnY31wwlZF0nqDHtqfxlwUla1uaAT8Y0p"; twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); AccessToken accesstoken = new AccessToken(TWITTER_TOKEN, TWITTER_TOKEN_SECRET); twitter.setOAuthAccessToken(accesstoken); writer.write("\n"); for (int i = 0; i < tweet_ids.size(); i++) { Long tweet_id = tweet_ids.get(i); System.out.println("[" + i + "] Getting Tweet id " + tweet_id); Status status = twitter.showStatus((long) tweet_ids.get(i)); if (status == null) { System.out.println("[FAILED] Doesnot exist twitter with tweet id : " + tweet_id); } else {/* www . j ava2 s .com*/ System.out.println("status asli : " + status.getText()); writer.write(tweet_id + "\t" + status.getText().replaceAll("\n", " ")); writer.write("\n"); updateIsLabelledAnotator3(tweet_id); } } }
From source file:Trending.java
public boolean validate(Status stat) { for (int i = 0; i < size; i++) { if (stat.getPlace().getCountry().equals(countries[i])) { for (int n = 0; n < limit; n++) { if ((stat.getText().indexOf((bank[i][n]))) != -1) { return true; }/*from w ww . j av a 2s . c o m*/ } } } return false; }
From source file:StreamToFiles.java
License:Apache License
public static void main(String[] args) throws TwitterException, FileNotFoundException { String oAuthFileName = "mjlauKeys.auth"; outFile = args[0];//from ww w.j av a2 s.c om ConfigurationBuilder cb = Utils.createConfigurationBuilder(new File(oAuthFileName)); if (cb == null) { throw new IllegalArgumentException("Configuration File Issues"); } TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { long counter = 0; PrintWriter outputWriter = new PrintWriter(new File(outFile)); @Override public void onStatus(Status status) { // System.out.println("@" + status.getUser().getScreenName() // + " - " + status.getText()); if (status.getText().contains("#")) { Utils.sanitizeAndWriteTweet(status.getText(), outputWriter); counter++; if (counter % 1000 == 0) { System.out.println("done with " + counter); } if (counter >= NUM_TWEETS) { twitterStream.cleanUp(); twitterStream.shutdown(); outputWriter.close(); } } } @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); twitterStream.sample("en"); }
From source file:Demo.java
/** * Main method.//from w w w . jav a 2s.c om * * @param args * @throws TwitterException */ public static void main(String[] args) throws TwitterException, IOException { // The TwitterFactory object provides an instance of a Twitter object // via the getInstance() method. The Twitter object is the API consumer. // It has the methods for interacting with the Twitter API. TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance(); boolean keepItGoinFullSteam = true; do { // Main menu Scanner input = new Scanner(System.in); System.out.print("\n--------------------" + "\nH. Home Timeline\nS. Search\nT. Tweet" + "\n--------------------" + "\nA. Get Access Token\nQ. Quit" + "\n--------------------\n> "); String choice = input.nextLine(); try { // Home Timeline if (choice.equalsIgnoreCase("H")) { // Display the user's screen name. User user = twitter.verifyCredentials(); System.out.println("\n@" + user.getScreenName() + "'s timeline:"); // Display recent tweets from the Home Timeline. for (Status status : twitter.getHomeTimeline()) { System.out.println("\n@" + status.getUser().getScreenName() + ": " + status.getText()); } } // Search else if (choice.equalsIgnoreCase("S")) { // Ask the user for a search string. System.out.print("\nSearch: "); String searchStr = input.nextLine(); // Create a Query object. Query query = new Query(searchStr); // Send API request to execute a search with the given query. QueryResult result = twitter.search(query); // Display search results. result.getTweets().stream().forEach((Status status) -> { System.out.println("\n@" + status.getUser().getName() + ": " + status.getText()); }); } // Tweet else if (choice.equalsIgnoreCase("T")) { boolean isOkayLength = true; String tweet; do { // Ask the user for a tweet. System.out.print("\nTweet: "); tweet = input.nextLine(); // Ensure the tweet length is okay. if (tweet.length() > 140) { System.out.println("Too long! Keep it under 140."); isOkayLength = false; } } while (isOkayLength == false); // Send API request to create a new tweet. Status status = twitter.updateStatus(tweet); System.out.println("Just tweeted: \"" + status.getText() + "\""); } // Get Access Token else if (choice.equalsIgnoreCase("A")) { // First, we ask Twitter for a request token. RequestToken reqToken = twitter.getOAuthRequestToken(); System.out.println("\nRequest token: " + reqToken.getToken() + "\nRequest token secret: " + reqToken.getTokenSecret()); AccessToken accessToken = null; while (accessToken == null) { // The authorization URL sends the request token to Twitter in order // to request an access token. At this point, Twitter asks the user // to authorize the request. If the user authorizes, then Twitter // provides a PIN. System.out .print("\nOpen this URL in a browser: " + "\n " + reqToken.getAuthorizationURL() + "\n" + "\nAuthorize the app, then enter the PIN here: "); String pin = input.nextLine(); try { // We use the provided PIN to get the access token. The access // token allows this app to access the user's account without // knowing his/her password. accessToken = twitter.getOAuthAccessToken(reqToken, pin); } catch (TwitterException te) { System.out.println(te.getMessage()); } } System.out.println("\nAccess token: " + accessToken.getToken() + "\nAccess token secret: " + accessToken.getTokenSecret() + "\nSuccess!"); } // Quit else if (choice.equalsIgnoreCase("Q")) { keepItGoinFullSteam = false; GeoApiContext context = new GeoApiContext() .setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y"); System.out.println(GeocodingApi.geocode(context, "Sigma Phi Epsilon, Lincoln, Nebraska, USA") .await()[0].geometry.location.toString()); System.out.println(GeocodingApi.geocode(context, "16th and R, Lincoln, Nebraska, USA") .await()[0].geometry.location.toString()); File htmlFile = new File("map.html"); Desktop.getDesktop().browse(htmlFile.toURI()); } // Bad choice else { System.out.println("Invalid option."); } } catch (IllegalStateException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { System.out.println(ex.getMessage()); } } while (keepItGoinFullSteam == true); }
From source file:PrintFilterStream.java
License:Apache License
/** * Main entry of this application.//from w w w.ja v a2s .c o m * * @param args follow(comma separated user ids) track(comma separated filter terms) * @throws TwitterException when Twitter service or network is unavailable */ 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(); } }; ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true); cb.setOAuthConsumerKey(""); cb.setOAuthConsumerSecret(""); cb.setOAuthAccessToken(""); cb.setOAuthAccessTokenSecret(""); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).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(","))); } } 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:TwitterPull.java
public void retrieveTweets() { try {/*from w w w .ja va 2s . c o m*/ Query query = new Query(this.queryString); query.setLang("en"); query.setCount(100); QueryResult result; int i = 0; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); // int i = 0; for (Status tweet : tweets) { System.out.println(tweet.getText().replaceAll("\n", "").replaceAll("\r", "")); // appendTweetDocument(tweet.getText()); } i++; } while ((query = result.nextQuery()) != null && i < 10); // setTwitterFeed(tweets); // System.exit(0); } catch (TwitterException te) { Logger.getLogger(TwitterPull.class.getName()).log(Level.SEVERE, null, te); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } }
From source file:GetTweetsAndSaveToFile.java
License:Apache License
/** * Usage: java twitter4j.examples.user.ShowUser [screen name] * * @param args message//from w w w . j a va 2s . com * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.user.ShowUser [screen name]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer("men2JyLEaAsxcbfmgzOAwUnTp", "2AGN0ie9TfCDJyWeH8qhTLtMhqRvRlNBtQU3lAP2M8k3Xk1KWl"); RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Authorization URL: \n" + requestToken.getAuthorizationURL()); AccessToken accessToken = new AccessToken("2811255124-zigkuv8MwDQbr5s9HdjLRSbg8aCOyxeD2gYGMfH", "D7jFABWHQa8QkTWwgYj1ISUbWP8twdfbzNgYkXI3jwySR"); twitter.setOAuthAccessToken(accessToken); /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } */ System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); User user = twitter.showUser(args[0]); if (user.getStatus() != null) { System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText()); } else { // the user is protected System.out.println("@" + user.getScreenName()); } FileWriter file = new FileWriter("./" + user.getScreenName() + "_Tweets.txt"); List<Status> list = twitter.getHomeTimeline(); for (Status each : list) { file.write("Sent by: @" + each.getUser().getScreenName() + " - " + each.getUser().getName() + "---" + each.getText() + "\n"); } file.close(); System.exit(0); } catch (Exception te) { te.printStackTrace(); System.exit(-1); } }
From source file:sampleController.java
@FXML private void onStartButtonActionPerformed(ActionEvent event) { System.out.println("You clicked me!"); //Create a runnable object for handling event outside of the UI thread Runnable r = new Runnable() { @Override/*from w ww. jav a 2 s. c om*/ public void run() { try { //Set isRunning to true.. isRunning = true; String searchTerm = flagTermTextField.getText(); String fileName = fileNameTextField.getText(); //Check if filename length is > 0 if (fileName.length() == 0) { appendConsoleTextAreaText("You must enter a valid file name"); return; } //Check if search term or flag term is not empty. if (searchTerm.length() > 0) { //Get a twitter object from TwitterUtil class Twitter twitter = TwitterUtil.getTwitterInstance(CONSUMERKEY, CONSUMERSECRET, TOKENKEY, TOKENSECRET); appendConsoleTextAreaText("Fetching search results for: " + searchTerm); //Get tweets matching search term in statuses list from TwitterUtils class List<Status> statuses = TwitterUtil.searchStatuses(searchTerm, twitter); appendConsoleTextAreaText("Fetched Search Results: " + statuses.size()); appendConsoleTextAreaText("Now Writing results to file: "); //iterate through all statuses and append the tweet to file. for (Status s : statuses) { FileIOUtils.appendTextToFile(fileName, s.getText()); FileIOUtils.appendTextToFile(fileName, TWEETSEPARATOR); } appendConsoleTextAreaText("File written successfully: " + fileName); //Send email code if (sendEmailCheckBox.isSelected()) { appendConsoleTextAreaText("Now attempting to send email: "); //Set credentials String username = usernameTextField.getText(); String password = passwordField.getText(); String recipientId = recipientEmailTextField.getText(); if (username.length() == 0 || password.length() == 0 || recipientId.length() == 0) { appendConsoleTextAreaText("Invalid entries to email.Please check again!!"); } else { //Send emails to the recipient with attachment. boolean sent = MailUtils.sendGmail(username, password, recipientId, fileName); if (sent) { appendConsoleTextAreaText("Email Sent Successfully!"); } else { appendConsoleTextAreaText( "Email sending failed. Please check your internet connections and/or credentials"); } } } } else { appendConsoleTextAreaText("You must enter a valid flag term!!"); } } catch (Exception e) { e.printStackTrace(); } finally { isRunning = false; } } }; if (!isRunning) { Thread t = new Thread(r); t.setDaemon(true); t.start(); } else { appendConsoleTextAreaText("Already Running!!"); } }
From source file:SearchTweets.java
License:Apache License
/** * Usage: java twitter4j.examples.search.SearchTweets [query] * * @param args/*w w w . ja v a 2s. co m*/ */ public static void main(String[] args) { if (args.length < 1) { System.out.println("java twitter4j.examples.search.SearchTweets [query]"); System.exit(-1); } Twitter twitter = new TwitterFactory().getInstance(); try { Query query = new Query(args[0]); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } }