Example usage for twitter4j Status getId

List of usage examples for twitter4j Status getId

Introduction

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

Prototype

long getId();

Source Link

Document

Returns the id of the status

Usage

From source file:twitbak.StatusBak.java

License:Open Source License

/**
 * Adds a Status to statusArray as a JSONObject.
 * /*w w w.ja  v  a  2s . com*/
 * @param status
 * @throws TwitterException
 * @throws JSONException
 */
public void statusToJson(Status status) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    result.put("Created At", status.getCreatedAt().toString());
    result.put("ID", status.getId());
    result.put("Text", status.getText());
    long inReplyToStatusId = status.getInReplyToStatusId();
    if (inReplyToStatusId != -1) {
        result.put("In Reply To Status ID", status.getInReplyToStatusId());
    }
    long inReplyToUserID = status.getInReplyToUserId();
    result.put("In Reply To User ID", inReplyToUserID);
    if (inReplyToUserID != -1) {
        result.put("In Reply To Screen Name", status.getInReplyToScreenName());
    }
    boolean isFavorited = status.isFavorited();
    if (isFavorited) {
        result.put("Favorited", status.isFavorited());
    }
    statusArray.put(result);
}

From source file:twitfeedbot.RespondServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ResponseList<Status> mentions;
    Twitter twit;/*from  w  w  w .  j a v  a 2  s . co m*/
    StringBuilder builder = new StringBuilder();
    long lastPostId = 0;

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity lastPostIdEntity;

    resp.setContentType("text/html");
    resp.getWriter().println("<html>");
    resp.getWriter().println("<body>");
    try {
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
        mentions = twit.getMentionsTimeline();

        lastPostIdEntity = datastore.get(KeyFactory.createKey("lastPostIDEntity", "ID"));
        lastPostId = Long.parseLong(lastPostIdEntity.getProperty("lastPostID").toString());

        if (mentions.size() == 0 || mentions.get(0).getId() == lastPostId)
            resp.getWriter().println("No mentions so far...<br>");
        else {
            resp.getWriter().println("Responding to mentions...<br>");
            for (Status mention : mentions) {
                builder.setLength(0); // Clear the String Builder
                if (lastPostId < mention.getId()) {
                    //Figure out how to like a reply with certain words (best fuck etc)
                    if (mention.getUser().getId() == twit.getId())
                        ;//don't respond to myself
                    else if (mention.isRetweeted())
                        ; //don't respond to retweet
                    else if (mention.getText().toLowerCase().contains("bye")) // Say goodbye
                    {
                        builder.setLength(0); // Clear the String Builder 
                        builder.append("@").append(mention.getUser().getScreenName()).append(" Ok. Bye");
                    } else {
                        builder.setLength(0); // Clear the String Builder
                        builder.append("@").append(mention.getUser().getScreenName());
                        builder.append(" ");

                        //Append Wordnik example sentence
                        builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                        if (builder.length() > 140) {
                            if (builder.lastIndexOf(";", 110) > 0)
                                builder.setLength(builder.lastIndexOf(";", 110));
                            else if (builder.lastIndexOf(":", 110) > 0)
                                builder.setLength(builder.lastIndexOf(":", 110));
                            else if (builder.lastIndexOf(",", 110) > 0)
                                builder.setLength(builder.lastIndexOf(",", 110));
                            else
                                builder.setLength(110);
                        }
                    }
                    twit.updateStatus(builder.toString());
                    resp.getWriter().println("Reply posted: " + builder.toString() + "<br>");
                    builder.delete(0, builder.length()); //Clear the builder
                }
            }
            //Save last post ID
            lastPostIdEntity.setProperty("lastPostID", (Long.toString(mentions.get(0).getId())));
            datastore.put(lastPostIdEntity);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (EntityNotFoundException e) {
        resp.getWriter().println("lastPostID not found. Creating...<br>");
        lastPostIdEntity = new Entity("lastPostIDEntity", "ID");
        //lastPostIdEntity.setProperty("lastPostID", 0);
        lastPostIdEntity.setProperty("lastPostID", "883352596160946176");
        datastore.put(lastPostIdEntity);

    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}

From source file:twitter.TweetGet.java

public List<MyStatus> getTweet() {
    List<MyStatus> stats = new ArrayList<>();
    SellerClassifier sc = new SellerClassifier();
    try {/*from  ww  w . j a  v  a 2s.  co  m*/
        File file = new File(".");
        System.out.println("PATH: " + file.getAbsolutePath());
        sc.initModel("data\\training.arff");
    } catch (Exception ex) {
        Logger.getLogger(TweetGet.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (Status tweet : tweets) {
        MyStatus myStatus = new MyStatus();
        myStatus.setTweet(tweet.getText());
        myStatus.setStatusId(tweet.getId());
        myStatus.setUsername(tweet.getUser().getName());
        myStatus.setUserScreenName(tweet.getUser().getScreenName());
        myStatus.setImageUrl(tweet.getUser().getProfileImageURLHttps());

        int classRes = (int) sc.classifyTweet(myStatus);

        if (classRes == 1) {
            myStatus.setClassification(classRes);
            stats.add(myStatus);
        }
    }

    return stats;
}

From source file:twitter4j.examples.tweets.UploadMultipleImages.java

License:Apache License

/**
 * Usage: java twitter4j.examples.tweets.UploadMultipleImages [text] [file1] [file2] ...
 *
 * @param args message//w w w .j  a v a 2s . c om
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println(
                "Usage: java twitter4j.examples.tweets.UploadMultipleImages [text] [file1] [file2] ...");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();

        long[] mediaIds = new long[args.length - 1];
        for (int i = 1; i < args.length; i++) {
            System.out.println("Uploading...[" + i + "/" + (args.length - 1) + "][" + args[i] + "]");
            UploadedMedia media = twitter.uploadMedia(new File(args[i]));
            System.out.println("Uploaded: id=" + media.getMediaId() + ", w=" + media.getImageWidth() + ", h="
                    + media.getImageHeight() + ", type=" + media.getImageType() + ", size=" + media.getSize());
            mediaIds[i - 1] = media.getMediaId();
        }

        StatusUpdate update = new StatusUpdate(args[0]);
        update.setMediaIds(mediaIds);
        Status status = twitter.updateStatus(update);
        System.out.println(
                "Successfully updated the status to [" + status.getText() + "][" + status.getId() + "].");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to update status: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:TwitterAnalytics.Analyze.java

License:Open Source License

private void parseCategories() {
    StringMatcher mr = new StringMatcher();
    for (Status st : twitter.getStatusCache()) {
        boolean match = false;

        int j = 0;
        while (!match && j < category.size()) {
            match = category.get(j).isMatch(st.getText(), matchMethod);
            if (match) {
                StatusView svw = new StatusView(st);
                category.get(j).add(svw.getStatus(),
                        "https://twitter.com/" + svw.getUsername() + "/status/" + svw.getId(),
                        mr.extractLocation(svw.getStatus()));
            }//from   w w w  . ja  va  2  s.c o m
            j++;
        }
        if (j == category.size()) {
            unknown.add(st.getText(),
                    "https://twitter.com/" + st.getUser().getScreenName() + "/status/" + st.getId(),
                    mr.extractLocation(st.getText()));
        }
    }
}

From source file:TwitterAnalytics.StatusView.java

License:Open Source License

public StatusView(Status stat) {
    this.username = stat.getUser().getScreenName();
    this.status = stat.getText();
    this.id = stat.getId();
}

From source file:twitterAPI.Twitter_testing.java

public void getSearchTweets(String regex) {
    //String queryStr = "@RobotGrrl";
    try {/* w  w w.  j  a  va  2 s. c o  m*/
        //Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(regex);
        query.count(100);
        System.out.println(query.getCount());

        QueryResult result = twitter.search(query);
        for (Status status : result.getTweets()) {

            searchHandler sh = new searchHandler();
            sh.nama = status.getUser().getScreenName();
            sh.tweet = status.getText();

            StringBuffer address = new StringBuffer();
            address.append("http://twitter.com/#!/");
            address.append(sh.nama);
            address.append("/status/");
            address.append(status.getId());

            String theAddressYouWant = address.toString();
            sh.URL = theAddressYouWant;
            shholder.add(sh);
            //System.out.println(theAddressYouWant); ini buat test bener apa ga url nya , udah bener
            //System.out.println("@" + sh.nama + ":" + sh.tweet);
        }
    } catch (TwitterException e) {
        System.out.println("Search tweets: " + e);
    }
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(/*  w w  w.jav a2s.com*/
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:twitterbot.TwitterActions.java

public void retweetTweet(Status status) throws TwitterException {
    this.twitter.retweetStatus(status.getId());
}

From source file:TwitterDownload.TwitterExel.java

public static String writeTweets(long ID, List<Status> tweets, String path) {
    try {//from   w  w w . ja  v a 2s  . com
        path = path + "Tweets";

        File theDir = new File(path);

        // if the directory does not exist, create it
        if (!theDir.exists()) {
            theDir.mkdir();
        }

        String exlPath = path + "/" + ID + ".xls";

        File exlFile = new File(exlPath);
        WritableWorkbook writableWorkbook = null;
        WritableSheet writableSheet = null;
        int i = 0;
        while (exlFile.exists()) {
            i++;

            exlPath = path + "/" + ID + "_" + i + ".xls";

            exlFile = new File(exlPath);
        }

        writableWorkbook = Workbook.createWorkbook(exlFile);

        writableSheet = writableWorkbook.createSheet("FerretData", 0);

        try {
            Workbook existing = Workbook.getWorkbook(exlFile);
            writableWorkbook = Workbook.createWorkbook(exlFile, existing);

            writableSheet = writableWorkbook.getSheet(0);
        } catch (BiffException be) {

        }

        //Create Cells with contents of different data types.
        //Also specify the Cell coordinates in the constructor

        i = 0;
        i = writableSheet.getRows();

        if (i == 0) {
            Label text = new Label(0, 0, "Tweeted Text");
            Label date = new Label(1, 0, "Tweeted Date");
            Label reTweets = new Label(2, 0, "ReTweet Count");
            Label favor = new Label(3, 0, "Favourite Count");
            Label place = new Label(4, 0, "Place");
            Label geo = new Label(5, 0, "GeoLocation");
            Label link = new Label(6, 0, "Link");
            Label user = new Label(7, 0, "User");

            //Add the created Cells to the sheet
            writableSheet.addCell(text);
            writableSheet.addCell(date);
            writableSheet.addCell(reTweets);
            writableSheet.addCell(favor);
            writableSheet.addCell(place);
            writableSheet.addCell(geo);
            writableSheet.addCell(link);
            writableSheet.addCell(user);

            i = 1;
        }

        for (int j = 0; j < tweets.size(); j++) {
            Status s = tweets.get(j);

            String placeString = s.getPlace() != null ? s.getPlace().toString() : "";
            if (placeString.contains("{"))
                placeString = placeString.substring(placeString.indexOf("{"), placeString.length() - 1);

            Label text = new Label(0, i + j, s.getText());
            DateTime date = new DateTime(1, i + j, s.getCreatedAt());
            Number reTweets = new Number(2, i + j, s.getRetweetCount());
            Number favor = new Number(3, i + j, s.getFavoriteCount());
            Label place = new Label(4, j + 1, placeString);
            Label geo = new Label(5, j + 1, s.getGeoLocation() != null ? s.getGeoLocation().toString() : "");

            String link = "https://twitter.com/" + s.getUser().getScreenName() + "/status/" + s.getId();
            URL url = new URL(link);

            WritableHyperlink hl = new WritableHyperlink(6, j + 1, url);

            Label user = new Label(7, j + 1, s.getUser().getScreenName());

            //Add the created Cells to the sheet
            writableSheet.addCell(text);
            writableSheet.addCell(date);
            writableSheet.addCell(reTweets);
            writableSheet.addCell(favor);
            writableSheet.addCell(place);
            writableSheet.addCell(geo);
            writableSheet.addHyperlink(hl);
            writableSheet.addCell(user);
        }

        //Write and close the workbook
        writableWorkbook.write();
        writableWorkbook.close();

        return exlPath;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (RowsExceededException e) {
        e.printStackTrace();
    } catch (WriteException e) {
        e.printStackTrace();
    }
    return null;
}