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:public_streaming.SampleStream.java

License:Apache License

public void onStatus(Status status) {
    System.out.println("tweet:" + status.getText());//
    System.out.println(status.getFavoriteCount());
    System.out.println("User" + status.getUser().getName() + "@" + status.getUser().getScreenName());//??,?(@xx)
    System.out.println("Posted Time:" + status.getCreatedAt());//
    System.out.println("Application Name:" + status.getSource());//
    System.out.println("Time Zone:" + status.getUser().getTimeZone());//
    System.out.println("Created Date:" + status.getUser().getCreatedAt());//?
    System.out.println("GeoLocation:" + status.getUser().getLocation());//?
    System.out.println("postID:" + status.getId());//ID
    System.out.println("UserID" + status.getUser().getId());//ID
    System.out.println("Language:" + status.getUser().getLang());//
    System.out.println("Follow:" + status.getUser().getFriendsCount());//
    System.out.println("Follower:" + status.getUser().getFollowersCount());//
}

From source file:reo7sp.socn.social.TwitterManager.java

License:Apache License

private void startListener() {
    new Thread("Twitter-Listener") {
        @Override// ww w. ja  v  a  2s  . c  o  m
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(75000);
                    try {
                        Status status = twitter.getMentionsTimeline().get(0);
                        if (status.getId() != lastMentionID) {
                            if (lastMentionID != 0) {
                                UiModule.getInstance().notify(TwitterManager.this,
                                        status.getUser().getName() + ": " + status.getText());
                            }
                            lastMentionID = status.getId();
                            saveSettings();
                        }
                        connected = true;
                    } catch (Exception err) {
                        if (connected) {
                            Log.e("TwitterManager", "Error in twitter listener. Trying to reconnect", err);
                        } else {
                            Log.e("TwitterManager", "Error in twitter listener. Trying to reconnect. " + err);
                        }
                        connected = false;
                    }
                }
            } catch (InterruptedException ignored) {
            }
        }
    }.start();
}

From source file:rtb.PopularTweetCollector.java

License:Apache License

private String getTweetURL(Status status) {
    return "https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId();
}

From source file:sentimentanalysis.Twitter.GetTweets.java

public static void main(String args[]) {

    Twitter4JConfig t4jConfig = new Twitter4JConfig();
    ConfigurationBuilder cb = t4jConfig.getConfigurationBuilder();

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();//  w  ww. j a v  a  2  s . c  o m
    String keyword = "Trump";

    ArrayList<Post> TweetResultList = new ArrayList<Post>();
    int count = 0;
    try {

        Query query = new Query(keyword + "+exclude:retweets+lang:en").until("2016-11-19");
        QueryResult result;

        do {
            result = twitter.search(query);
            ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();

            for (Status tweet : tweets) {
                count++;

                String user = tweet.getUser().getScreenName();
                String content = tweet.getText();
                Date time = tweet.getCreatedAt();
                System.out.println(time.getTime());
                String tweet_url = "https://twitter.com/" + tweet.getUser().getScreenName() + "/status/"
                        + tweet.getId();
                System.out.println(tweet.getLang());
                Post tr = new Post(user, content, tweet_url, new java.sql.Date(time.getTime()));
                TweetResultList.add(tr);

                //                    System.out.println("[user]@" + tweet.getUser().getScreenName() 
                //                        + "[/user][tweet]" + tweet.getText()+"[/tweet][link]"+tweet_url+"[/link]");
            }

        } while (((query = result.nextQuery()) != null) && (count < 500));

        try {
            SaveToDB.savePosts(TweetResultList);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(GetTweets.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (TwitterException te) {
        te.printStackTrace();
    }

}

From source file:sentinets.ParseTweet.java

License:Open Source License

public ParseTweet(Status tweet) {
    this(tweet.getText());
    this.tweet = tweet;
    this.url = "http://twitter.com/" + tweet.getUser().getScreenName() + "/status/" + tweet.getId();
    this.user = tweet.getUser().getScreenName();
    this.published_date = tweet.getCreatedAt().toString();
}

From source file:Situational_Awareness.TwitterSearch.java

public ArrayList<Information> twitterFeed(String twitterURL) {
    ArrayList<Information> informationList = new ArrayList<>();

    try {//from  w  ww.j  a  v  a  2s  .c  o  m
        Query query = new Query(twitterURL);
        QueryResult result;
        result = twitter.search(query);
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {
            System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());

            Date tweeted = tweet.getCreatedAt();

            if (tweeted.getTime() >= java.lang.System.currentTimeMillis() - 36000000) {
                Information newInfo = new Information(tweet.getId(), tweet.getUser().getScreenName(),
                        tweet.getText(), tweet.getUser().getLocation(), tweet.getUser().getProfileImageURL());
                informationList.add(newInfo);
            } else {
                System.out.println("information not relevant");
            }

        }
    } catch (Exception te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
    return informationList;
}

From source file:t.twitter.TTwitterModule.java

License:Open Source License

@Kroll.method
public void connect(HashMap args) {
    KrollDict arg = new KrollDict(args);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(arg.optString("apikey", ""))
            .setOAuthConsumerSecret(arg.optString("apisecret", ""))
            .setOAuthAccessToken(arg.optString("accesstoken", ""))
            .setOAuthAccessTokenSecret(arg.optString("accesssecret", ""));
    AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build());
    twitter = tf.getInstance();/*from   ww  w . jav  a2 s.  c  o  m*/

    twitter.addListener(new TwitterAdapter() {
        @Override
        public void updatedStatus(Status status) {
            Log.d("Twitter", "text: " + status.getText());
        }

        @Override
        public void searched(QueryResult result) {
            HashMap<String, KrollDict[]> event = new HashMap<String, KrollDict[]>();
            List<Status> tweets = result.getTweets();
            KrollDict[] dList = new KrollDict[tweets.size()];

            // sort tweets
            Collections.sort(tweets, new Comparator<Status>() {
                public int compare(Status o1, Status o2) {

                    if (desc) {
                        if (o2.getId() < o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else {
                        if (o2.getId() > o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }
                }
            });

            // return tweets to titanium
            int i = 0;
            for (Status tweet : tweets) {
                if (lastID == -1 || lastID < tweet.getId()) {
                    KrollDict d = new KrollDict();
                    d.put("username", tweet.getUser().getScreenName());
                    d.put("userimage", tweet.getUser().getProfileImageURL());
                    d.put("text", tweet.getText());
                    d.put("date", tweet.getCreatedAt());
                    d.put("id", Long.toString(tweet.getId()));
                    dList[i] = d;
                    lastID = tweet.getId();
                    i++;
                }
            }

            KrollDict[] dList2 = new KrollDict[i];

            // shorten array
            System.arraycopy(dList, 0, dList2, 0, i);

            event.put("tweets", dList2);
            success.call(getKrollObject(), event);

            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void verifiedCredentials(User user) {

            HashMap<String, KrollDict> event = new HashMap<String, KrollDict>();
            KrollDict d = new KrollDict();

            d.put("user_name", user.getName());
            d.put("screen_name", user.getScreenName());
            d.put("image_path", user.getProfileImageURL());
            event.put("user_info", d);
            success.call(getKrollObject(), event);
            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void onException(TwitterException e, TwitterMethod method) {
            synchronized (LOCK) {
                LOCK.notify();
            }
            Log.e("twitter", "error: " + e.getErrorMessage());
        }
    });
    Log.d("Twitter", "connected");
}

From source file:testtweet.TweetUsingTwitter4jExample.java

/**
 * @param args the command line arguments
 */// w  ww.  j a v  a2 s. com
public static void main(String[] args) throws IOException, TwitterException {

    //Instantiate a re-usable and thread-safe factory
    TwitterFactory twitterFactory = new TwitterFactory(Data.getConf().build());

    //Instantiate a new Twitter instance
    Twitter twitter = twitterFactory.getInstance();

    /*
    //setup OAuth Consumer Credentials
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
            
    //setup OAuth Access Token
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    */

    //Instantiate and initialize a new twitter status update
    StatusUpdate statusUpdate = new StatusUpdate(
            //your tweet or status message
            "Twitter API #Hacked");
    //attach any media, if you want to
    /*
    statusUpdate.setMedia(
    //title of media
    "http://h1b-work-visa-usa.blogspot.com"
    , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream());
    */
    //tweet or update status
    Status status = twitter.updateStatus(statusUpdate);

    //response from twitter server
    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.getRateLimitStatus().getRemainingHits() = "
                + status.getRateLimitStatus().getRemaining());
    }
    System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
    System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
}

From source file:timeline.CmdSearchTerm.java

License:Apache License

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, IOException {

    // Check how many arguments were passed in
    if ((args == null) || (args.length != 6)) {

        System.err.println("Please provide command as following.");
        System.err.println("java -cp twitter4j-multi-oauth-0.5.jar "
                + "timeline.CmdSearchTerm consumer_key consumer_secret" + " user_token user_secret output_path "
                + "term ");
        System.exit(-1);//w w w.jav  a  2  s  . com
    }

    AppOAuth AppOAuths = new AppOAuth();
    String endpoint = "/search/tweets";

    String consumer_key = null;
    try {
        consumer_key = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    String consumer_secret = null;
    try {
        consumer_secret = StringEscapeUtils.escapeJava(args[1]);
    } catch (Exception e) {
        System.err.println("Argument" + args[1] + " must be an String.");
        System.exit(-1);
    }
    String user_token = null;
    try {
        user_token = StringEscapeUtils.escapeJava(args[2]);
    } catch (Exception e) {
        System.err.println("Argument" + args[2] + " must be an String.");
        System.exit(-1);
    }
    String user_secret = null;
    try {
        user_secret = StringEscapeUtils.escapeJava(args[3]);
    } catch (Exception e) {
        System.err.println("Argument" + args[3] + " must be an String.");
        System.exit(-1);
    }

    String OutputDirPath = null;
    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[4]);
    } catch (Exception e) {
        System.err.println("Argument" + args[4] + " must be an String.");
        System.exit(-1);
    }

    String term = "";
    try {
        term = StringEscapeUtils.escapeJava(args[5]);
    } catch (Exception e) {
        System.err.println("Argument" + args[5] + " must be an String.");
        System.exit(-1);
    }

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, consumer_key, consumer_secret, user_token,
                user_secret);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls - 2;
        int RemainingCallsCounter = 0;
        System.out.println("Remianing Calls: " + RemainingCalls);

        // screen_name / user_id provided by arguments
        System.out.println("Trying to create output directory");
        String filesPath = OutputDirPath + "/";
        File theDir = new File(filesPath);

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

            try {
                theDir.mkdirs();

            } catch (SecurityException se) {

                System.err.println("Could not create output " + "directory: " + OutputDirPath);
                System.err.println(se.getMessage());
                System.exit(-1);
            }
        }

        String fileName = filesPath + term.replace(" ", "");
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");

        Query query = new Query(term);
        QueryResult result;

        List<Status> statuses = new ArrayList<>();
        int totalTweets = 0;
        int numberOfTweetsToGet = 5000;
        long lastID = Long.MAX_VALUE;

        while (totalTweets < numberOfTweetsToGet) {
            if (numberOfTweetsToGet - totalTweets > 100) {
                query.setCount(100);
            } else {
                query.setCount(numberOfTweetsToGet - totalTweets);
            }
            try {
                result = twitter.search(query);
                statuses.addAll(result.getTweets());

                if (statuses.size() > 0) {
                    for (Status status : statuses) {
                        String rawJSON = TwitterObjectFactory.getRawJSON(status);
                        writer.println(rawJSON);

                        totalTweets += 1;

                        if (status.getId() < lastID) {
                            lastID = status.getId();
                        }
                    }
                } else {
                    break;
                }
                System.out.println("totalTweets: " + totalTweets);
                statuses.clear();

            } catch (TwitterException e) {
                // e.printStackTrace();

                System.out.println("Tweets Get Exception: " + e.getMessage());

                // If rate limit reached then switch Auth user
                RemainingCallsCounter++;
                if (RemainingCallsCounter >= RemainingCalls) {

                    System.out.println("No more remianing calls");
                }

                if (totalTweets < 1) {
                    writer.close();
                    // Remove file if tweets not found
                    File fileToDelete = new File(fileName);
                    fileToDelete.delete();
                    break;
                }
            }
            query.setMaxId(lastID - 1);

            // If rate limit reached then switch Auth user
            RemainingCallsCounter++;
            if (RemainingCallsCounter >= RemainingCalls) {

                System.out.println("No more remianing calls");
                break;
            }
        }

        if (totalTweets > 0) {
            System.out.println("Total dumped tweets of " + term + " are: " + totalTweets);
        } else {

            // Remove file if tweets not found
            File fileToDelete = new File(fileName);
            fileToDelete.delete();
        }
        writer.close();
    } catch (TwitterException te) {
        // te.printStackTrace();
        System.out.println("Failed to get term results because: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");
}

From source file:toninbot.ToninStatusListener.java

@Override
public void onStatus(Status tweetRecibido) {
    if (tweetRecibido.getUser().getId() != 184742273L && tweetRecibido.getUser().getId() != 2841338087L) {
        return;/*  w w  w .ja v a2 s .  co m*/
    }
    System.out.println(tweetRecibido.getUser().getName() + " " + tweetRecibido.getText());
    Calendar cal = Calendar.getInstance();
    cal.setTime(tweetRecibido.getCreatedAt());
    long hora = cal.get(Calendar.HOUR_OF_DAY);
    System.out.println("Hora: " + cal.get(Calendar.HOUR_OF_DAY));

    //comprobar la hora
    if (hora > 7 || hora < 1) {
        return;
    }

    //comprobar que no sea una respuesta a alguien
    if (tweetRecibido.getText().contains("@")) {
        return;
    }

    StatusUpdate stat = new StatusUpdate(
            "@" + tweetRecibido.getUser().getScreenName() + " " + respuestaRandom());
    System.out.println("Fora de horario!");

    stat.inReplyToStatusId(tweetRecibido.getId());

    try {
        twitter.updateStatus(stat);
        System.out.println("Twitteado: " + stat.toString());
    } catch (TwitterException ex) {
        System.out.println("Error");
    }
}