Example usage for twitter4j StatusUpdate setInReplyToStatusId

List of usage examples for twitter4j StatusUpdate setInReplyToStatusId

Introduction

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

Prototype

public void setInReplyToStatusId(long inReplyToStatusId) 

Source Link

Usage

From source file:com.freshdigitable.udonroad.TweetInputFragment.java

License:Apache License

private Observable<Status> createSendObservable() {
    final String sendingText = binding.mainTweetInputView.getText().toString();
    if (!isStatusUpdateNeeded()) {
        return twitterApi.updateStatus(sendingText);
    }//from   w  w  w.  java 2s  .c om
    String s = sendingText;
    for (long q : quoteStatusIds) {
        final Status status = statusCache.find(q);
        if (status == null) {
            continue;
        }
        s += " https://twitter.com/" + status.getUser().getScreenName() + "/status/" + q;
    }
    final StatusUpdate statusUpdate = new StatusUpdate(s);
    if (replyEntity != null) {
        statusUpdate.setInReplyToStatusId(replyEntity.inReplyToStatusId);
    }
    return twitterApi.updateStatus(statusUpdate);
}

From source file:com.github.moko256.twitlatte.model.impl.twitter.PostTweetModelImpl.java

License:Apache License

@Override
public Completable postTweet() {
    return Completable.create(subscriber -> {
        try {//  w ww  .  ja  va  2s.c o  m
            StatusUpdate statusUpdate = new StatusUpdate(tweetText);
            if (uriList.size() > 0) {
                long ids[] = new long[uriList.size()];
                for (int i = 0; i < uriList.size(); i++) {
                    Uri uri = uriList.get(i);
                    InputStream image = contentResolver.openInputStream(uri);
                    ids[i] = twitter.uploadMedia(uri.getLastPathSegment(), image).getMediaId();
                }
                statusUpdate.setMediaIds(ids);
                statusUpdate.setPossiblySensitive(possiblySensitive);
            }
            if (isReply()) {
                statusUpdate.setInReplyToStatusId(inReplyToStatusId);
            }
            if (location != null) {
                statusUpdate.setLocation(location);
            }
            twitter.updateStatus(statusUpdate);
            subscriber.onComplete();
        } catch (FileNotFoundException | TwitterException e) {
            subscriber.tryOnError(e);
        }
    });
}

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

License:Apache License

public boolean sendTweet(AppSettings settings, Context context) {
    try {/*  www . ja v a 2 s  .c  o  m*/
        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.klinker.android.twitter.utils.api_helper.TwitPicHelper.java

License:Apache License

/**
 * posts the status onto Twitlonger, it then posts the shortened status (with link) to the user's twitter and updates the status on twitlonger
 * to include the posted status's id.//w ww. j av  a 2 s  .  c o  m
 *
 * @return id of the status that was posted to twitter
 */
public long createPost() {
    TwitPicStatus status = uploadToTwitPic();
    Log.v("talon_twitpic", "past upload");
    long statusId;
    try {
        Status postedStatus;
        StatusUpdate update = new StatusUpdate(status.getText());

        if (replyToStatusId != 0) {
            update.setInReplyToStatusId(replyToStatusId);
        }
        if (location != null) {
            update.setLocation(location);
        }

        postedStatus = twitter.updateStatus(update);

        statusId = postedStatus.getId();
    } catch (Exception e) {
        e.printStackTrace();
        statusId = 0;
    }

    // if zero, then it failed
    return statusId;
}

From source file:com.marpies.ane.twitter.functions.UpdateStatusFunction.java

License:Apache License

@Override
public FREObject call(FREContext context, FREObject[] args) {
    super.call(context, args);

    String text = (args[0] == null) ? null : FREObjectUtils.getString(args[0]);
    mCallbackID = FREObjectUtils.getInt(args[1]);
    long inReplyToStatusID = (args[2] == null) ? -1 : Long.valueOf(FREObjectUtils.getString(args[2]));
    final List<MediaSource> mediaSources = (args[3] == null) ? null
            : FREObjectUtils.getListOfMediaSource((FREArray) args[3]);

    final AsyncTwitter twitter = TwitterAPI.getAsyncInstance(TwitterAPI.getAccessToken());
    twitter.addListener(this);

    final StatusUpdate status = new StatusUpdate(text);
    if (inReplyToStatusID >= 0) {
        status.setInReplyToStatusId(inReplyToStatusID);
    }// ww  w  . ja  v  a  2 s .c o m
    /* If we have some media, system files must be created and uploaded to Twitter */
    if (mediaSources != null) {
        /* Save cache dir path before running the async task */
        AIR.setCacheDir(AIR.getContext().getActivity().getCacheDir().getAbsolutePath());
        /* Execute async task that creates files out of the given sources (URLs and Bitmaps) */
        createFilesFromSources(mediaSources, twitter, status);
        return null;
    }

    /* Posts status without media */
    twitter.updateStatus(status);

    return null;
}

From source file:com.michaelfitzmaurice.clocktwerk.TweetResponder.java

License:Apache License

public void respondToMentions(Collection<Status> mentions) {

    LOG.info("Responding to {} mentions on behalf of {}", mentions.size(), myScreenName);

    long latestMentionSeen = -1;
    for (Status mention : mentions) {
        String replyMessage = replyBody(myScreenName, mention, tweetDatabase.getNextTweet());
        StatusUpdate reply = new StatusUpdate(replyMessage);
        long mentionTweetId = mention.getId();
        reply.setInReplyToStatusId(mentionTweetId);
        LOG.debug("Replying to mention with ID {}", mentionTweetId);
        try {//from   w w  w  . ja v  a 2 s .  c o m
            twitterClient.updateStatus(reply);
            LOG.debug("Replied to mention with ID {}", mentionTweetId);
        } catch (TwitterException e) {
            LOG.error("Failed to reply to Tweet", e);
        }
        // even if we failed to reply, record the mention as seen
        if (mentionTweetId > latestMentionSeen) {
            latestMentionSeen = mentionTweetId;
        }
    }
    LOG.info("Finished replying to new mentions");
    updateLastMentionSeen(latestMentionSeen);
}

From source file:com.narvis.frontend.twitter.output.Output.java

License:Open Source License

@Override
public void setOuput(MessageInOut m) {
    try {/*from   ww w  . j  a  va  2  s .  co  m*/
        for (String s : this.getTweetList(m)) {
            StatusUpdate status = new StatusUpdate(s);
            status.setInReplyToStatusId(((TwitterMessageInOut) m).getIdResponseTo());
            this.twitterLink.updateStatus(status);
        }
    } catch (TwitterException ex) {
        NarvisLogger.logException(ex);
    }
}

From source file:com.rhymestore.twitter.commands.ReplyCommand.java

License:Open Source License

@Override
public void execute() throws TwitterException {
    String rhyme = null;/* w  w  w  .ja  v a 2  s.  co  m*/
    String targetUser = status.getUser().getScreenName();

    try {
        rhyme = rhymeStore.getRhyme(status.getText());

        if (rhyme == null) {
            // Try to rhyme with the user screen name
            if (wordParser.isWord(targetUser)) {
                LOGGER.info("Trying to rhyme with the screen name: {}", targetUser);
                rhyme = rhymeStore.getRhyme(targetUser);
            }
        }

        if (rhyme == null) {
            rhyme = wordParser.getDefaultRhyme();

            LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme);
        }
    } catch (IOException ex) {
        LOGGER.error("An error occured while connecting to the rhyme store. Could not reply to {}", targetUser,
                ex);
    }

    try {
        String tweet = TwitterUtils.reply(targetUser, rhyme);

        LOGGER.info("Replying to {} with: {}", targetUser, tweet);

        // Reply to the user
        StatusUpdate newStatus = new StatusUpdate(tweet);
        newStatus.setInReplyToStatusId(status.getId());
        twitter.updateStatus(newStatus);
    } catch (TwitterException ex) {
        LOGGER.error("Could not send reply to tweet " + status.getId(), ex);
    }
}

From source file:de.vanita5.twittnuker.service.BackgroundOperationService.java

License:Open Source License

private List<SingleResponse<ParcelableStatus>> updateStatus(final Builder builder,
        final ParcelableStatusUpdate statusUpdate) {
    final ArrayList<ContentValues> hashtag_values = new ArrayList<ContentValues>();
    final Collection<String> hashtags = extractor.extractHashtags(statusUpdate.text);
    for (final String hashtag : hashtags) {
        final ContentValues values = new ContentValues();
        values.put(CachedHashtags.NAME, hashtag);
        hashtag_values.add(values);//w  ww  .  j a v  a  2  s  . c  o  m
    }
    boolean notReplyToOther = false;
    mResolver.bulkInsert(CachedHashtags.CONTENT_URI,
            hashtag_values.toArray(new ContentValues[hashtag_values.size()]));

    final List<SingleResponse<ParcelableStatus>> results = new ArrayList<SingleResponse<ParcelableStatus>>();

    if (statusUpdate.accounts.length == 0)
        return Collections.emptyList();

    try {
        final boolean hasMedia = statusUpdate.medias != null && statusUpdate.medias.length > 0;
        final String imagePath = hasMedia ? getImagePathFromUri(this, Uri.parse(statusUpdate.medias[0].uri))
                : null;
        final File imageFile = imagePath != null ? new File(imagePath) : null;

        String uploadResultUrl = null;

        if (mUseUploader && imageFile != null && imageFile.exists()) {
            uploadResultUrl = uploadMedia(imageFile, statusUpdate.accounts, statusUpdate.text);
        }

        final String unshortenedContent = mUseUploader && uploadResultUrl != null
                ? getImageUploadStatus(new String[] { uploadResultUrl.toString() }, statusUpdate.text)
                : statusUpdate.text;

        final boolean shouldShorten = mValidator.getTweetLength(unshortenedContent) > mValidator
                .getMaxTweetLength();
        Map<Long, ShortenedStatusModel> shortenedStatuses = null;

        if (shouldShorten && mUseShortener) {
            if (mShortener.equals(SERVICE_SHORTENER_HOTOTIN)) {
                shortenedStatuses = postHototIn(statusUpdate);
                if (shortenedStatuses == null)
                    throw new ShortenException(this);
            } else if (mShortener.equals(SERVICE_SHORTENER_TWITLONGER)) {
                shortenedStatuses = postTwitlonger(statusUpdate);
                if (shortenedStatuses == null)
                    throw new ShortenException(this);
            } else {
                throw new IllegalArgumentException("BackgroundOperationService.java#updateStatus()");
            }
        }

        if (shouldShorten) {
            if (!mUseShortener)
                throw new StatusTooLongException(this);
            else if (unshortenedContent == null)
                throw new ShortenException(this);
        }
        if (!mUseUploader && statusUpdate.medias != null) {
            for (final ParcelableMediaUpdate media : statusUpdate.medias) {
                final String path = getImagePathFromUri(this, Uri.parse(media.uri));
                final File file = path != null ? new File(path) : null;
                if (file != null && file.exists()) {
                    Utils.downscaleImageIfNeeded(file, 95);
                }
            }
        }
        for (final Account account : statusUpdate.accounts) {
            String shortenedContent = "";
            ShortenedStatusModel shortenedStatusModel = null;
            final Twitter twitter = getTwitterInstance(this, account.account_id, true, true);

            if (shouldShorten && mUseShortener && shortenedStatuses != null) {
                shortenedStatusModel = shortenedStatuses.get(account.account_id);
                shortenedContent = shortenedStatusModel.getText();
            }
            final StatusUpdate status = new StatusUpdate(
                    shouldShorten && mUseShortener ? shortenedContent : unshortenedContent);
            status.setInReplyToStatusId(statusUpdate.in_reply_to_status_id);
            if (statusUpdate.location != null) {
                status.setLocation(ParcelableLocation.toGeoLocation(statusUpdate.location));
            }
            if (!mUseUploader && hasMedia) {
                final BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                final long[] mediaIds = new long[statusUpdate.medias.length];
                try {
                    for (int i = 0, j = mediaIds.length; i < j; i++) {
                        final ParcelableMediaUpdate media = statusUpdate.medias[i];
                        final String path = getImagePathFromUri(this, Uri.parse(media.uri));
                        if (path == null)
                            throw new FileNotFoundException();
                        BitmapFactory.decodeFile(path, o);
                        final File file = new File(path);
                        final ContentLengthInputStream is = new ContentLengthInputStream(file);
                        is.setReadListener(new StatusMediaUploadListener(this, mNotificationManager, builder,
                                statusUpdate));
                        final MediaUploadResponse uploadResp = twitter.uploadMedia(file.getName(), is,
                                o.outMimeType);
                        mediaIds[i] = uploadResp.getId();
                    }
                } catch (final FileNotFoundException e) {

                } catch (final TwitterException e) {
                    final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e);
                    results.add(response);
                    continue;
                }
                status.mediaIds(mediaIds);
            }
            status.setPossiblySensitive(statusUpdate.is_possibly_sensitive);

            if (twitter == null) {
                results.add(new SingleResponse<ParcelableStatus>(null, new NullPointerException()));
                continue;
            }
            try {
                final Status twitter_result = twitter.updateStatus(status);

                //Update Twitlonger statuses
                if (shouldShorten && mUseShortener && mShortener.equals(SERVICE_SHORTENER_TWITLONGER)) {
                    TweetShortenerUtils.updateTwitlonger(shortenedStatusModel, twitter_result.getId(), twitter);
                }

                if (!notReplyToOther) {
                    final long inReplyToUserId = twitter_result.getInReplyToUserId();
                    if (inReplyToUserId <= 0) {
                        notReplyToOther = true;
                    }
                }
                final ParcelableStatus result = new ParcelableStatus(twitter_result, account.account_id, false);
                results.add(new SingleResponse<ParcelableStatus>(result, null));
            } catch (final TwitterException e) {
                final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e);
                results.add(response);
            }
        }
    } catch (final UpdateStatusException e) {
        final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e);
        results.add(response);
    }
    return results;
}

From source file:es.portizsan.twitrector.tasks.TweetReplyTask.java

License:Open Source License

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String message = null;//w  w  w.jav  a 2s.com
    if (req.getParameter("message") != null) {
        message = req.getParameter("message");
    } else {
        logger.log(Level.WARNING, "message is null.");
        return;
    }
    long inReplyToStatusId = 0;
    if (req.getParameter("statusId") != null) {
        try {
            inReplyToStatusId = Long.parseLong(req.getParameter("statusId"));
        } catch (NumberFormatException nfe) {
            logger.log(Level.WARNING, "Invalid statusId.", nfe);
            return;
        }
    } else {
        logger.log(Level.WARNING, "statusId is null.");
        return;
    }
    try {
        logger.info("repling: " + message + " , " + inReplyToStatusId);
        Twitter twitter = new TwitterService().getTwitterInstance();
        StatusUpdate su = new StatusUpdate(message);
        su.setInReplyToStatusId(inReplyToStatusId);
        twitter.updateStatus(su);
    } catch (TwitterException te) {
        logger.log(Level.WARNING, "Failed to search tweets: ", te);
    }
}