Example usage for twitter4j StatusUpdate StatusUpdate

List of usage examples for twitter4j StatusUpdate StatusUpdate

Introduction

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

Prototype

public StatusUpdate(String status) 

Source Link

Usage

From source file:TwitterSend2.java

License:BEER-WARE LICENSE

public void tweet(String _tweetMessage) {
    try {//from www. ja v a 2 s  . co  m
        StatusUpdate status = new StatusUpdate(tweetMessage);
        status.setMedia(
                new File("/Users/Fabax/Pro/Processing/Processing-snippets/Twitter/TwitterSend2/data/nbd.jpg"));// BY SPECIFYING FILE PATH
        //status.setMedia("File name", new FileInputStream("")); // By InputStream
        Status updateStatus = twitter.updateStatus(status);
        // Status status = twitter.updateStatus(_tweetMessage);
        // println("Status updated to [" + status.getText() + "].");
    } catch (TwitterException te) {
        System.out.println("Error: " + 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  w  w  w . j a v  a 2 s.  co m

    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
    }//  w  ww .j av a2 s  . c  o m

    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) {
    /*/*from w w w.  j a va  2s .  c om*/
     * 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:au.com.tyo.services.sn.twitter.SNTwitter.java

License:Apache License

private Status postTweet(Tweet tweet) throws TwitterException {
    StatusUpdate what = new StatusUpdate(tweet.getText());
    if (tweet.hasMedia())
        what.setMediaIds(tweet.getMediaIds());
    return twitter.updateStatus(what);
}

From source file:au.com.tyo.sn.twitter.SNTwitter.java

License:Apache License

public Status postTweet(Tweet tweet, String[] mediaUrls) throws TwitterException {
    StatusUpdate what = new StatusUpdate(tweet.getText());

    if (null == tweet.getMediaIds() && null != mediaUrls && mediaUrls.length > 0) {
        for (int i = 0; i < 4 && i < mediaUrls.length; ++i) {
            UploadedMedia media = null;/*from   www.j a  v a  2 s.c o m*/
            String imgUrl = mediaUrls[i];
            Uri uri = Uri.parse(imgUrl);
            String imgTitle = uri.getLastPathSegment();
            try {
                URL url = new URL(imgUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                InputStream is = url.openStream();

                /*
                 * can't do it, it is deprecated
                 */
                //what.setMedia(imgTitle, is);
                media = twitter.uploadMedia(imgTitle, is);
            } catch (Exception ex) {
                /*
                 * Something wrong, but that is ok, just ignore it
                 */
                ex.printStackTrace();
            } finally {
                if (null != media) {
                    tweet.setMediaId(media.getMediaId());
                }
            }
        }

    }

    if (null != mediaUrls)
        what.setMediaIds(tweet.getMediaIds());

    return twitter.updateStatus(what);
}

From source file:bluevia.SendSMS.java

License:Apache License

public static void setTwitterStatus(String userEmail, String tweet) {
    if (tweet != null) {
        try {/*from  ww  w .ja v a  2 s.com*/
            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()));
        }
    }
}

From source file:br.com.porcelli.hornetq.integration.twitter.outgoing.impl.OutgoingTwitterHandler.java

License:Apache License

@Override
public HandleStatus handle(final MessageReference ref) {
    System.out.println("Entrando no handle()");
    synchronized (this) {
        ref.handled();//from  ww w .jav a 2  s  .  c o m
        final ServerMessage message = ref.getMessage();
        try {
            String text2publish;
            if (message.containsProperty(TwitterConstants.KEY_TEXT)) {
                text2publish = message.getStringProperty(TwitterConstants.KEY_TEXT);
            } else {
                text2publish = message.getBodyBuffer().readString();
            }

            if (text2publish == null || text2publish.trim().length() <= 0) {
                log.error(ERROR_MESSAGE_NOT_FILLED);
                throw new Exception(ERROR_MESSAGE_NOT_FILLED);
            } else if (text2publish.length() > 140) {
                log.warn(ERROR_MESSAGE_SIZE_EXCEED);
                text2publish = text2publish.substring(0, 139);
            }

            MessageType type = MessageType.TWEET;
            try {
                if (message.containsProperty(TwitterConstants.KEY_MSG_TYPE)) {
                    type = MessageType
                            .valueOf(message.getStringProperty(TwitterConstants.KEY_MSG_TYPE).toUpperCase());
                }
            } catch (Exception e) {
                log.warn(ERROR_INVALID_MESSAGE_TYPE);
            }

            if (type == MessageType.DM) {
                if (!message.containsProperty(TwitterConstants.KEY_TO_USER_ID)
                        && !message.containsProperty(TwitterConstants.KEY_TO_USER_SCREEN_NAME)) {
                    log.error(ERROR_DM_DESTINY_NOT_FOUND);
                    throw new Exception(ERROR_DM_DESTINY_NOT_FOUND);
                }

                DirectMessage sentMessage = null;
                if (message.containsProperty(TwitterConstants.KEY_TO_USER_ID)) {
                    int userId = -1;
                    try {
                        userId = message.getIntProperty(TwitterConstants.KEY_TO_USER_ID);
                    } catch (PropertyConversionException e) {
                        userId = Integer.valueOf(message.getStringProperty(TwitterConstants.KEY_TO_USER_ID));
                    }
                    sentMessage = twitter.sendDirectMessage(userId, text2publish);
                    dmSent.incrementAndGet();
                    totalSent.incrementAndGet();
                } else if (message.containsProperty(TwitterConstants.KEY_TO_USER_SCREEN_NAME)) {
                    String userScreenName = message.getStringProperty(TwitterConstants.KEY_TO_USER_SCREEN_NAME);
                    sentMessage = twitter.sendDirectMessage(userScreenName, text2publish);
                    dmSent.incrementAndGet();
                    totalSent.incrementAndGet();
                }
                if (sentMessage != null && sentQueue != null) {
                    final ServerMessage msg = buildMessage(sentQueue.getName().toString(), sentMessage);
                    msg.setAddress(sentQueue.getName());
                    msg.setDurable(true);
                    postOffice.route(msg, false);
                }
            } else {
                final StatusUpdate status = new StatusUpdate(text2publish);

                if (message.containsProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID)) {
                    long reply2StatusId = 0L;
                    try {
                        reply2StatusId = message.getLongProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID);
                    } catch (PropertyConversionException e) {
                        reply2StatusId = Long
                                .valueOf(message.getStringProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID));
                    }
                    status.setInReplyToStatusId(reply2StatusId);
                }

                if (message.containsProperty(TwitterConstants.KEY_GEO_LATITUDE)
                        && message.containsProperty(TwitterConstants.KEY_GEO_LONGITUDE)) {
                    double geolat = 0.0D;
                    double geolong = 0.0D;
                    try {
                        geolat = message.getDoubleProperty(TwitterConstants.KEY_GEO_LATITUDE);
                    } catch (PropertyConversionException e) {
                        geolat = Double.valueOf(message.getStringProperty(TwitterConstants.KEY_GEO_LATITUDE));
                    }
                    try {
                        geolong = message.getDoubleProperty(TwitterConstants.KEY_GEO_LONGITUDE);
                    } catch (PropertyConversionException e) {
                        geolong = Double.valueOf(message.getStringProperty(TwitterConstants.KEY_GEO_LONGITUDE));
                    }

                    status.setLocation(new GeoLocation(geolat, geolong));
                }

                if (message.containsProperty(TwitterConstants.KEY_PLACE_ID)) {
                    status.setPlaceId(message.getStringProperty(TwitterConstants.KEY_PLACE_ID));
                }

                if (message.containsProperty(TwitterConstants.KEY_DISPLAY_COODINATES)) {
                    boolean displayCoordinated = false;
                    try {
                        displayCoordinated = message
                                .getBooleanProperty(TwitterConstants.KEY_DISPLAY_COODINATES);
                    } catch (PropertyConversionException e) {
                        displayCoordinated = Boolean
                                .valueOf(message.getStringProperty(TwitterConstants.KEY_DISPLAY_COODINATES));
                    }
                    status.setDisplayCoordinates(displayCoordinated);
                }
                Status sentMessage = twitter.updateStatus(status);
                tweetSent.incrementAndGet();
                totalSent.incrementAndGet();
                if (sentMessage != null && sentQueue != null) {
                    final ServerMessage msg = buildMessage(sentQueue.getName().toString(), sentMessage);
                    msg.setAddress(sentQueue.getName());
                    msg.setDurable(true);
                    postOffice.route(msg, false);
                }
            }
        } catch (Exception e) {
            mbean.notifyException(e);
            log.error("Error sending message.", e);
            if (errorQueue != null) {
                final ServerMessage msg = message.copy();
                msg.setAddress(errorQueue.getName());
                msg.setDurable(true);
                try {
                    postOffice.route(msg, false);
                } catch (Exception e1) {
                    mbean.notifyException(e1);
                }
            }
        }
        try {
            queue.acknowledge(ref);
        } catch (Exception e) {
            mbean.notifyException(e);
            log.error("Error acknowledging message.", e);
        }
        return HandleStatus.HANDLED;
    }
}

From source file:cloudcomputebot.Input.Decipher.java

License:Open Source License

public static void handleInput(Status status, User sender)
        throws FileNotFoundException, IOException, TwitterException {
    String[] lines = argsNoComments(status.getText());
    if (lines.length > 0) {
        String cmd = lines[0];/*from   w  w  w. ja v a  2 s . c  om*/
        if (cmd.equalsIgnoreCase(validCmds[0]) || cmd.equalsIgnoreCase(validCmds[1])) {
            String[] fractalInputStream = new String[lines.length - 1];
            int c = 0;
            for (int i = 1; i < lines.length; i++) {
                fractalInputStream[c] = lines[i];
                c++;
            }
            ImageCreator fractalCreator = new ImageCreator();
            fractalCreator.setArgsForTwitter(fractalInputStream);
            BufferedImage fractal = fractalCreator.drawFractal();
            StatusUpdate retweet = new StatusUpdate("@" + sender.getScreenName());
            File img = new File("image.gif");
            ImageIO.write(fractal, "gif", img);
            retweet.setMedia(img);
            CloudComputeBot.t.updateStatus(retweet);
        }
    }
}

From source file:cmu.edu.homework.mediaUpload.TwitterVideoUpload.java

License:Apache License

@Override
public String upload(File video, String message) throws TwitterException {
    return twitter.updateStatus(new StatusUpdate(message).media(video)).getText();
}