Example usage for twitter4j StatusUpdate setMedia

List of usage examples for twitter4j StatusUpdate setMedia

Introduction

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

Prototype

public void setMedia(File file) 

Source Link

Usage

From source file:TwitterSend2.java

License:BEER-WARE LICENSE

public void tweet(String _tweetMessage) {
    try {//from w  ww  .j a 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:RandomPicBot.java

License:Open Source License

public static void main(String[] args) {
    /*/*ww  w  .j ava 2  s . 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: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   ww  w  .ja  v  a 2s  .  co m
        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:com.daiv.android.twitter.services.SendTweet.java

License:Apache License

public boolean sendTweet(AppSettings settings, Context context) {
    try {//from  w  w w.j ava  2 s .  c o m
        Twitter twitter = getTwitter();

        if (remainingChars < 0 && !pwiccer) {
            // twitlonger goes here
            TwitLongerHelper helper = new TwitLongerHelper(message, twitter);
            helper.setInReplyToStatusId(tweetId);

            return helper.createPost() != 0;
        } else {
            twitter4j.StatusUpdate reply = new twitter4j.StatusUpdate(message);
            reply.setInReplyToStatusId(tweetId);

            if (!attachedUri.equals("")) {

                File outputDir = context.getCacheDir(); // context being the Activity pointer
                File f = File.createTempFile("compose", "picture", outputDir);

                Bitmap bitmap = getBitmapToSend(Uri.parse(attachedUri), context);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] bitmapdata = bos.toByteArray();

                FileOutputStream fos = new FileOutputStream(f);
                fos.write(bitmapdata);
                fos.flush();
                fos.close();

                if (!settings.twitpic) {
                    reply.setMedia(f);
                    twitter.updateStatus(reply);
                    return true;
                } else {
                    TwitPicHelper helper = new TwitPicHelper(twitter, message, f, context);
                    helper.setInReplyToStatusId(tweetId);
                    return helper.createPost() != 0;
                }
            } else {
                // no picture
                twitter.updateStatus(reply);
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.djbrick.twitter_photo_uploader.MSTwitterService.java

License:Apache License

/**
 * Sets access token, sends tweet./*from  w ww .  java2  s.c  om*/
 * @category Helpers
 * @return result code
 */
private int sendTweet(String text, String imagePath, AccessToken accessToken) {
    int resultCode = MSTwitter.MST_RESULT_SUCCESSFUL;

    // check to make sure we have data and access before tweeting
    if (text == null && imagePath == null) {
        return MSTwitter.MST_RESULT_NO_DATA_TO_SEND;
    }
    if (accessToken == null) {
        return MSTwitter.MST_RESULT_NOT_AUTHORIZED;
    }

    // get twitter4j object
    Twitter twitter4j = null;
    try {
        twitter4j = new TwitterFactory().getInstance();
        twitter4j.setOAuthConsumer(MSTwitter.smConsumerKey, MSTwitter.smConsumerSecret);
    } catch (IllegalStateException e) {
        // No network access or token already available
        resultCode = MSTwitter.MST_RESULT_ILLEGAL_STATE_SETOAUTHCONSUMER;
        Log.e(MSTwitter.TAG, e.toString());
        return resultCode;
    }

    // Create and set twitter access credentials from token and or secret
    twitter4j.setOAuthAccessToken(accessToken);
    try {
        // finally update the status (send the tweet)
        StatusUpdate status = new StatusUpdate(text);
        if (imagePath != null) {
            status.setMedia(new File(imagePath));
        }
        twitter4j.updateStatus(status);
    } catch (TwitterException e) {
        return MSTwitter.getTwitterErrorNum(e, this);
    }

    return resultCode;
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Tweet with Image, Uploaded to Twitter
 *//*  w  w w.  j  a  v  a 2 s . com*/
@SimpleFunction(description = "This sends a tweet as the logged-in user with the "
        + "specified Text and a path to the image to be uploaded, which will be trimmed if it " + "exceeds "
        + MAX_CHARACTERS + " characters. "
        + "If an image is not found or invalid, only the text will be tweeted."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void TweetWithImage(final String status, final String imagePath) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "TweetWithImage", ErrorMessages.ERROR_TWITTER_SET_STATUS_FAILED,
                "Need to login?");
        return;
    }

    AsynchUtil.runAsynchronously(new Runnable() {
        public void run() {
            try {
                String cleanImagePath = imagePath;
                // Clean up the file path if necessary
                if (cleanImagePath.startsWith("file://")) {
                    cleanImagePath = imagePath.replace("file://", "");
                }
                File imageFilePath = new File(cleanImagePath);
                if (imageFilePath.exists()) {
                    StatusUpdate theTweet = new StatusUpdate(status);
                    theTweet.setMedia(imageFilePath);
                    twitter.updateStatus(theTweet);
                } else {
                    form.dispatchErrorOccurredEvent(Twitter.this, "TweetWithImage",
                            ErrorMessages.ERROR_TWITTER_INVALID_IMAGE_PATH);
                }
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "TweetWithImage",
                        ErrorMessages.ERROR_TWITTER_SET_STATUS_FAILED, e.getMessage());
            }
        }
    });

}

From source file:com.illusionaryone.TwitterAPI.java

License:Open Source License

public String updateStatus(String statusString, String filename) {
    if (accessToken == null) {
        return "false";
    }/*from  w  ww  . j  av a  2  s . c om*/

    try {
        StatusUpdate statusUpdate = new StatusUpdate(statusString.replaceAll("@", "").replaceAll("#", ""));
        statusUpdate.setMedia(new File(filename));
        Status status = twitter.updateStatus(statusUpdate);
        com.gmt2001.Console.debug.println("Success");
        return "true";
    } catch (TwitterException ex) {
        com.gmt2001.Console.err.println("Failed: " + ex.getMessage());
        return "false";
    }
}

From source file:com.klinker.android.twitter.services.SendTweet.java

License:Apache License

public boolean sendTweet(AppSettings settings, Context context) {
    try {//from  w  w w  .  j a  v  a  2 s  .  c om
        Twitter twitter = Utils.getTwitter(context, settings);

        if (remainingChars < 0 && !pwiccer) {
            // twitlonger goes here
            TwitLongerHelper helper = new TwitLongerHelper(message, twitter);
            helper.setInReplyToStatusId(tweetId);

            return helper.createPost() != 0;
        } else {
            twitter4j.StatusUpdate reply = new twitter4j.StatusUpdate(message);
            reply.setInReplyToStatusId(tweetId);

            if (!attachedUri.equals("")) {

                File outputDir = context.getCacheDir(); // context being the Activity pointer
                File f = File.createTempFile("compose", "picture", outputDir);

                Bitmap bitmap = getBitmapToSend(Uri.parse(attachedUri), context);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] bitmapdata = bos.toByteArray();

                FileOutputStream fos = new FileOutputStream(f);
                fos.write(bitmapdata);
                fos.flush();
                fos.close();

                if (!settings.twitpic) {
                    reply.setMedia(f);
                    twitter.updateStatus(reply);
                    return true;
                } else {
                    TwitPicHelper helper = new TwitPicHelper(twitter, message, f, context);
                    helper.setInReplyToStatusId(tweetId);
                    return helper.createPost() != 0;
                }
            } else {
                // no picture
                twitter.updateStatus(reply);
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.learnncode.demotwitterimagepost.HelperMethods.java

License:Apache License

public static void postToTwitterWithImage(Context context, final Activity callingActivity,
        final String imageUrl, final String message, final TwitterCallback postResponse) {
    if (!LoginActivity.isActive(context)) {
        postResponse.onFinsihed(false);/*from   www . j  av  a2s . c  o m*/
        return;
    }

    final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
    configurationBuilder
            .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
    configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken(context));
    configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
    final Configuration configuration = configurationBuilder.build();
    final Twitter twitter = new TwitterFactory(configuration).getInstance();

    final File file = new File(imageUrl);

    new Thread(new Runnable() {

        private double x;

        @Override
        public void run() {
            boolean success = true;
            try {
                x = Math.random();
                if (file.exists()) {
                    final StatusUpdate status = new StatusUpdate(message);
                    status.setMedia(file);
                    twitter.updateStatus(status);
                } else {
                    Log.d(TAG, "----- Invalid File ----------");
                    success = false;
                }
            } catch (final Exception e) {
                e.printStackTrace();
                success = false;
            }

            final boolean finalSuccess = success;

            callingActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    postResponse.onFinsihed(finalSuccess);
                }
            });

        }
    }).start();
}

From source file:com.learnncode.twitter.async.TweetActionAsync.java

License:Apache License

@Override
protected Void doInBackground(Void... arg0) {

    try {/* ww  w . ja  va2 s. c  o m*/
        if (mActionType == ActionType.favorite) {
            mStatusObject.setTweetStatusObject(
                    TwitterHelper.getTwitterInstance(mContext).createFavorite(mTweetId), mPosition,
                    mActionType);

        } else if (mActionType == ActionType.unfavorite) {
            mStatusObject.setTweetStatusObject(
                    TwitterHelper.getTwitterInstance(mContext).destroyFavorite(mTweetId), mPosition,
                    mActionType);

        } else if (mActionType == ActionType.retweet) {

            mStatusObject.setTweetStatusObject(
                    TwitterHelper.getTwitterInstance(mContext).retweetStatus(mTweetId), mPosition, mActionType);

        } else if (mActionType == ActionType.reply) {
            Twitter twitter = TwitterHelper.getTwitterInstance(mContext);
            StatusUpdate statusUpdate = new StatusUpdate(mReplyText);
            statusUpdate.inReplyToStatusId(mTweetId);
            mStatusObject.setTweetStatusObject(twitter.updateStatus(statusUpdate), mPosition, mActionType);

        } else if (mActionType == ActionType.tweet) {
            Twitter twitter = TwitterHelper.getTwitterInstance(mContext);
            StatusUpdate statusUpdate = new StatusUpdate(mReplyText);
            if (imageFile != null) {
                statusUpdate.setMedia(imageFile);
            }

            mStatusObject.setTweetStatusObject(twitter.updateStatus(statusUpdate), mPosition, mActionType);
        }

    } catch (Exception e) {
        mStatusObject.setTweetStatusObject(null, mPosition, mActionType);
    }
    return null;
}