Example usage for twitter4j Twitter updateStatus

List of usage examples for twitter4j Twitter updateStatus

Introduction

In this page you can find the example usage for twitter4j Twitter updateStatus.

Prototype

Status updateStatus(String status) throws TwitterException;

Source Link

Document

Updates the authenticating user's status.

Usage

From source file:TimeLine.java

private void btTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTwitActionPerformed
    // Tombol update status, show setelah update
    txtStatus.setText("");

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();

    try {/*ww w  . j a va  2 s  .  c  om*/
        Status status = twitter.updateStatus(txStatus.getText());
        JOptionPane.showMessageDialog(rootPane, "Twit \n [ " + status.getText() + " ]\nTerkirim!");
    } catch (TwitterException ex) {
        JOptionPane.showMessageDialog(rootPane, "Tidak bisa mengirim : " + ex.getMessage());
        Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Status> statuses = null;
    try {
        statuses = twitter.getUserTimeline();

        statuses.stream().forEach((status) -> {
            txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });

        txStatus.setText(""); //reload field
    } catch (TwitterException te) {
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage());
    }
}

From source file:TwitterGateway.java

public void Tweet(String user, String paramStatusUpdate) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    int userLength = user.length();
    int maxTweet = 140 - (userLength + 2 + 9); // ditambah 2 untuk @ dan " ", ditambah 9 untuk waktu " HH:mm:ss";

    String[] tampung = paramStatusUpdate.split(" ", 0); //misahin semua kata jadi array of kata

    StatusUpdate[] statusUpdate = new StatusUpdate[(paramStatusUpdate.length() / maxTweet) + 1]; //panjang status dibagi batas maksimal huruf yang diperbolehkan, ditambah 1 karena 130/140 = 0
    String[] tampungStatusUpdate = new String[statusUpdate.length]; //bikin banyaknya array sepanjang tweet yang mau di tweet

    int increment = 0;
    int incTampung = 0;
    for (int i = 0; i < tampungStatusUpdate.length; i++) {
        tampungStatusUpdate[i] = "@" + user + " "; //setiap tweet harus dimasukin nama user yang dituju
    }/*from  ww w  .j  a v  a 2  s .c om*/

    while (increment < statusUpdate.length) {

        while (incTampung < tampung.length) {
            tampungStatusUpdate[increment] += tampung[incTampung]; //nambahin kata
            if (tampungStatusUpdate[increment].length() >= 131) { //melakukan cek apakah tweet sudah over 140 kata atau belom, 131 soalnya 140 dikurang 9 untuk waktu " HH:mm:ss";

                tampungStatusUpdate[increment] = tampungStatusUpdate[increment].substring(0,
                        tampungStatusUpdate[increment].length() - tampung[incTampung].length()); //ngebuang kata terakhir yang ditambahin
                tampungStatusUpdate[increment] += " " + dateFormat.format(date);
                System.out.println(tampungStatusUpdate[increment]);
                increment++;
                //tampungStatusUpdate[increment] += tampung[incTampung] + " "; //kata yang tadi dibuang dimasukin lagi ke tampungStatusUpdate index selanjutnya
                break;
            } else {
                tampungStatusUpdate[increment] += " "; //Jika belum 140 kata maka ditambahkan spasi
            }
            incTampung++;
            if (incTampung >= tampung.length) {
                tampungStatusUpdate[increment] += " " + dateFormat.format(date);
                System.out.println(tampungStatusUpdate[increment]);
                increment++; //kalo kata-kata sudah habis, keluarin dari statement
            }
        }
    }

    for (int i = 0; i < statusUpdate.length; i++) {
        statusUpdate[i] = new StatusUpdate(tampungStatusUpdate[i]);
    }
    try {
        for (int i = 0; i < statusUpdate.length; i++) {
            twitter.updateStatus(statusUpdate[i]);
        }
    } catch (TwitterException ex) {
        twitter.updateStatus("@" + user + " Maaf anda sudah penah melakukan pencarian ini sebelumnya. "
                + dateFormat.format(date));
        System.out.println("Error : " + ex);
    }
}

From source file:TwitterGateway.java

public void Tweet2(String user, String paramStatusUpdate) throws TwitterException {
    Twitter twitter = new TwitterFactory().getInstance();
    int userLength = user.length();
    int maxTweet = 140 - (userLength + 2); // ditambah 2 untuk @ dan " ", ditambah 9 untuk waktu " HH:mm:ss";

    String[] tampung = paramStatusUpdate.split(" ", 0); //misahin semua kata jadi array of kata

    StatusUpdate[] statusUpdate = new StatusUpdate[(paramStatusUpdate.length() / maxTweet) + 1]; //panjang status dibagi batas maksimal huruf yang diperbolehkan, ditambah 1 karena 130/140 = 0
    String[] tampungStatusUpdate = new String[statusUpdate.length]; //bikin banyaknya array sepanjang tweet yang mau di tweet

    int increment = 0;
    int incTampung = 0;
    for (int i = 0; i < tampungStatusUpdate.length; i++) {
        tampungStatusUpdate[i] = "@" + user + " "; //setiap tweet harus dimasukin nama user yang dituju
    }/*from   w w w .  j a  v a2s  . c  om*/

    while (increment < statusUpdate.length) {

        while (incTampung < tampung.length) {
            tampungStatusUpdate[increment] += tampung[incTampung]; //nambahin kata
            if (tampungStatusUpdate[increment].length() >= 140) { //melakukan cek apakah tweet sudah over 140 kata atau belom, 131 soalnya 140 dikurang 9 untuk waktu " HH:mm:ss";

                tampungStatusUpdate[increment] = tampungStatusUpdate[increment].substring(0,
                        tampungStatusUpdate[increment].length() - tampung[incTampung].length()); //ngebuang kata terakhir yang ditambahin
                System.out.println(tampungStatusUpdate[increment]);
                increment++;
                //tampungStatusUpdate[increment] += tampung[incTampung] + " "; //kata yang tadi dibuang dimasukin lagi ke tampungStatusUpdate index selanjutnya
                break;
            } else {
                tampungStatusUpdate[increment] += " "; //Jika belum 140 kata maka ditambahkan spasi
            }
            incTampung++;
            if (incTampung >= tampung.length) {
                System.out.println(tampungStatusUpdate[increment]);
                increment++; //kalo kata-kata sudah habis, keluarin dari statement
            }
        }
    }

    for (int i = 0; i < statusUpdate.length; i++) {
        statusUpdate[i] = new StatusUpdate(tampungStatusUpdate[i]);
    }
    try {
        for (int i = 0; i < statusUpdate.length; i++) {
            twitter.updateStatus(statusUpdate[i]);
        }
    } catch (TwitterException ex) {
        twitter.updateStatus("@" + user + " Maaf anda sudah penah melakukan pencarian ini sebelumnya. ");
        System.out.println("Error : " + ex);
    }
}

From source file:RandomPicBot.java

License:Open Source License

public static void main(String[] args) {
    /*/*  w w  w  .  j a  va 2s  .  co m*/
     * initialize the yaml setup
     * reads from keys.yml in the classpath, or same directory as the program
     */
    Yaml yaml = new Yaml();
    InputStream fileInput = null;
    try {
        fileInput = new FileInputStream(new File("keys.yml"));
    } catch (FileNotFoundException e1) {
        System.out.println("keys.yml not found!");
        e1.printStackTrace();
        System.exit(0);
    }
    @SuppressWarnings("unchecked") //unchecked cast, who cares.
    Map<String, String> map = (Map<String, String>) yaml.load(fileInput);

    /*
     * extracts values from the map
     */

    String CONSUMER_KEY = map.get("CONSUMER_KEY");
    String CONSUMER_SECRET = map.get("CONSUMER_SECRET");
    String TOKEN = map.get("TOKEN");
    String TOKEN_SECRET = map.get("TOKEN_SECRET");
    long USER_ID = Long.parseLong(map.get("USER_ID"));

    /*
     * initialize Twitter using the keys we got from the yaml file
     */

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    twitter.setOAuthAccessToken(new AccessToken(TOKEN, TOKEN_SECRET, USER_ID));

    /*
     * set up our picture folder
     * gets the folder from the command line argument
     * may change this to yaml too in the future
     */
    File directory = new File(args[0]);
    File[] pictures = directory.listFiles(new FileFilter() {
        /*
         * check to make sure the file is under 3mb(with some wiggle room) and is an acceptable image(non-Javadoc)
         * @see java.io.FileFilter#accept(java.io.File)
         */
        public boolean accept(File pathname) {
            if (pathname.isFile() && pathname.length() < 3000000 && isImage(pathname)) {
                return true;
            } else
                return false;
        }
    });

    System.out.println(pictures.length + " usable files found.");

    Random rand = new Random();

    /*
     * convert our minute value into milliseconds since thats what Thread.sleep() uses
     */

    int WAIT_TIME = Integer.parseInt(args[1]) * 60 * 1000;

    String statusText = "";
    if (args[2] != null) {
        for (int i = 2; i < args.length; i++) {
            statusText += args[i] + " ";
        }
        statusText.trim();
    }

    if (statusText.length() > 117) {
        System.out.println("Your message is too long!");
        System.out.println("Only messages up to 117 characters are supported!");
        System.exit(5);
    }

    StatusUpdate status = new StatusUpdate(statusText);

    /*
     * main loop
     * generate a random number to choose our image with
     * then upload the image to twitter
     * then wait for the defined time(gotten from the command line in minutes)
     */

    while (true) {
        int index = rand.nextInt(pictures.length);
        status.setMedia(pictures[index]);

        try {
            System.out.print("uploading picture: " + pictures[index].getName());
            if (!statusText.equals(""))
                System.out.println(" with text: " + statusText);
            else
                System.out.println();
            twitter.updateStatus(status);
        } catch (TwitterException e) {
            System.out.println("Problem uploading the file!");
            e.printStackTrace();
        }
        try {
            Thread.sleep(WAIT_TIME);
        } catch (InterruptedException e) {
            System.out.println("Program was interrupted!");
            e.printStackTrace();
        }
    }
}

From source file:Demo.java

/**
 * Main method./* w  w w . ja  va 2s  .  c o m*/
 *
 * @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:Register.java

License:Open Source License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 *
 * @param args message/*from   www  . j av a  2 s.  co  m*/
 */
public static void main(String[] args) {
    try {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("wIb1qVNc0CNXQJxduYIXw")
                .setOAuthConsumerSecret("vTES3U9862wYaxFRdMyD1LRatkq2R42mDyOjXLHIdk");

        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        AccessToken accessToken = null;
        try {
            // get request token.
            // this will throw IllegalStateException if access token is already available
            RequestToken requestToken = twitter.getOAuthRequestToken();

            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("Access granted to Twitter.");
            System.out.println("Access token: " + accessToken.getToken());
            System.out.println("Access token secret: " + accessToken.getTokenSecret());
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                System.out.println("OAuth consumer key/secret is not set.");
                System.exit(-1);
            }
        }
        twitter.updateStatus("Minecraft server successfully registered at " + (new Date()).toString());
        System.out.println("Successfully connected to Twitter.");

        // Write the properties file
        PrintWriter pw = new PrintWriter(new FileWriter("../TwitterEvents.properties"));
        pw.println("accessToken=" + accessToken.getToken());
        pw.println("accessTokenSecret=" + accessToken.getTokenSecret());
        pw.close();

        System.out.println("Your TwitterEvents.properties file has been created with your access tokens.");
        System.out.println("Start Minecraft server to load the remaining default values.");
        System.out.println("Then reload TwitterEvents if you make any changes.");
        System.exit(0);
    } catch (TwitterException te) {
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.out
                .println("Try revoking access to the hModEvents application from your Twitter settings page.");
        System.exit(-1);
    } catch (IOException ioe) {
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

From source file:App.PruebaTwitter.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException/*from   www .  j a  v a  2 s . c o m*/
 */
public static void main(String[] args) throws TwitterException {
    Twitter twitter = TwitterFactory.getSingleton();
    String message = "Probando a twittear desde java";
    Status status = twitter.updateStatus(message);

}

From source file:au.com.infiniterecursion.hashqanda.MainActivity.java

private void showTweetDialog() {

    app.setShowing_tweet_dialog(true);//from w w w  .  j av  a  2 s . c  o m

    // Launch Tweet Edit View
    LayoutInflater inflater = (LayoutInflater) getApplicationContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final View tweet_dialog_view = inflater.inflate(R.layout.tweet_dialog, null);

    final EditText tweet_edittext = (EditText) tweet_dialog_view.findViewById(R.id.EditTextTweet);

    final Dialog d = new Dialog(this);
    Window w = d.getWindow();
    w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    d.setTitle(R.string.tweet_dialog_title);
    // the edit layout defined in an xml file (in res/layout)
    d.setContentView(tweet_dialog_view);
    // Cancel
    Button cbutton = (Button) d.findViewById(R.id.button2Cancel);
    cbutton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            app.setShowing_tweet_dialog(false);
            d.dismiss();
        }
    });
    // Edit
    Button ebutton = (Button) d.findViewById(R.id.button1Edit);
    ebutton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // save title and description to DB.
            String tweet = tweet_edittext.getText().toString();

            int end = (tweet.length() > 133) ? 133 : tweet.length();
            String real_tweet = "#qanda " + tweet.substring(0, end);
            Log.d(TAG, "New tweet is " + tweet);
            Log.d(TAG, "real tweet is " + real_tweet);

            String twitterToken, twitterTokenSecret;
            String[] toks = twitterTokens();
            twitterToken = toks[0];
            twitterTokenSecret = toks[1];

            if (twitterToken != null && twitterTokenSecret != null) {

                // Ok, now we can tweet this URL
                AccessToken a = new AccessToken(twitterToken, twitterTokenSecret);
                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(TwitterOAuthActivity.consumerKey, TwitterOAuthActivity.consumerSecret);
                twitter.setOAuthAccessToken(a);

                try {
                    twitter.updateStatus(real_tweet);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(MainActivity.this, R.string.tweet_posted, Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (TwitterException e) {
                    // 
                    e.printStackTrace();
                    Log.e(TAG, " twittering failed " + e.getMessage());
                }
            } else {

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MainActivity.this, R.string.tweet_not_posted, Toast.LENGTH_LONG).show();
                    }
                });

            }

            app.setShowing_tweet_dialog(false);
            d.dismiss();
        }
    });
    d.show();
}

From source file:au.com.infiniterecursion.vidiom.activity.MainActivity.java

public void finishedUploading(boolean success) {
    // not uploading anymore.

    // Auto twittering.
    ///*w w  w .j  ava2s. c  o m*/
    if (twitterPreference && success) {

        new Thread(new Runnable() {
            public void run() {

                // Check there is a hosted URL for a start..

                // XXX get which URL from user if more than one!!

                String[] hosted_urls_to_tweet = db_utils
                        .getHostedURLsFromID(new String[] { Long.toString(latestsdrecord_id) });

                Log.d(TAG, " checking " + hosted_urls_to_tweet[0] + " in auto twitter publishing");

                if (hosted_urls_to_tweet != null && hosted_urls_to_tweet[0] != null
                        && hosted_urls_to_tweet[0].length() > 0) {

                    // Check there is a valid twitter OAuth tokens.
                    String twitterToken = prefs.getString("twitterToken", null);
                    String twitterTokenSecret = prefs.getString("twitterTokenSecret", null);

                    if (twitterToken != null && twitterTokenSecret != null) {

                        // Ok, now we can tweet this URL
                        AccessToken a = new AccessToken(twitterToken, twitterTokenSecret);
                        Twitter twitter = new TwitterFactory().getInstance();
                        twitter.setOAuthConsumer(TwitterOAuthActivity.consumerKey,
                                TwitterOAuthActivity.consumerSecret);
                        twitter.setOAuthAccessToken(a);

                        String status = "New video:" + hosted_urls_to_tweet[0];
                        try {
                            twitter.updateStatus(status);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(MainActivity.this, R.string.tweeted_ok, Toast.LENGTH_LONG)
                                            .show();
                                }
                            });
                        } catch (TwitterException e) {
                            //
                            e.printStackTrace();
                            Log.e(TAG, "Auto twittering failed " + e.getMessage());
                        }
                    }

                }

            }
        }).start();

    }

    mainapp.setNotUploading();
}

From source file:bluevia.SendSMS.java

License:Apache License

public static void setTwitterStatus(String userEmail, String tweet) {
    if (tweet != null) {
        try {// www.j  av  a  2 s  . c  om
            Properties twitterAccount = Util.getNetworkAccount(userEmail, "TwitterAccount");

            if (twitterAccount != null) {
                String consumer_key = twitterAccount.getProperty("TwitterAccount.consumer_key");
                String consumer_secret = twitterAccount.getProperty("TwitterAccount.consumer_secret");
                String access_key = twitterAccount.getProperty("TwitterAccount.access_key");
                String access_secret = twitterAccount.getProperty("TwitterAccount.access_secret");

                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(consumer_key, consumer_secret);
                twitter.setOAuthAccessToken(new AccessToken(access_key, access_secret));

                StatusUpdate status = new StatusUpdate(tweet);
                twitter.updateStatus(status);
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            log.severe(te.getMessage());
        } catch (Exception e) {
            log.severe(String.format("Error sending SMS: %s", e.getMessage()));
        }
    }
}