List of usage examples for twitter4j Status isRetweeted
boolean isRetweeted();
From source file:kerguelenpetrel.RespondServlet.java
License:Apache License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { StringBuilder builder = new StringBuilder(); resp.setContentType("text/plain; charset=UTF-8"); try {/*w w w. j a v a 2s . c o m*/ //Get the Twitter object Twitter twit = TwitterFactory.getSingleton(); ResponseList<Status> mentions = twit.getMentionsTimeline(); lastPostIdEntity = datastore.get(KeyFactory.createKey("lastPostIDEntity", "ID")); lastPostId = Long.parseLong(lastPostIdEntity.getProperty("lastPostID").toString()); if (mentions.size() == 0) { resp.getWriter().println("No mentions so far...\n"); return; } for (Status mention : mentions) { if (lastPostId < mention.getId()) { if (mention.getUser().getId() == twit.getId()) ; //don't respond to myself else if (mention.isRetweeted()) mention = twit.createFavorite(mention.getId()); //mark the retweet as a favourite else if (mention.getText().toLowerCase().contains("bye")) { builder.setLength(0); builder.append("@"); builder.append(mention.getUser().getScreenName()); builder.append(" Bye"); } else { builder.setLength(0); //Add the screen name of the person we are responding to builder.append("@"); builder.append(mention.getUser().getScreenName() + " "); //Get feed title as content builder.append(getFeedTitle(resp)); //Get a Wordnik trend builder.append(getWordnikTrend(resp)); /* Tweets are maximum 280 characters */ if (builder.length() > 280) { builder.setLength(builder.lastIndexOf(" ", 270)); builder.append(end[(r.nextInt(end.length))]); } } //Set the status StatusUpdate status = new StatusUpdate(builder.toString()); //Post the status twit.updateStatus(status); resp.getWriter().println("Tweet posted: " + status.getStatus()); } } //Save last post ID lastPostIdEntity.setProperty("lastPostID", (Long.toString(mentions.get(0).getId()))); datastore.put(lastPostIdEntity); } catch (EntityNotFoundException e) { // Make new ResponseIDentity lastPostIdEntity = new Entity("lastPostIDEntity", "ID"); lastPostIdEntity.setProperty("lastPostID", "0"); datastore.put(lastPostIdEntity); resp.getWriter() .println("Made new lastPostId " + lastPostIdEntity.getProperty("lastPostID").toString()); } catch (TwitterException e) { resp.getWriter().println("Problem with Twitter \n"); e.printStackTrace(resp.getWriter()); } }
From source file:org.smarttechie.servlet.SimpleStream.java
public void getStream(TwitterStream twitterStream, String[] parametros, final Session session)//,PrintStream out) { listener = new StatusListener() { @Override/*from w w w . ja v a2s . co m*/ public void onException(Exception arg0) { // TODO Auto-generated method stub } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { // TODO Auto-generated method stub } @Override public void onScrubGeo(long arg0, long arg1) { // TODO Auto-generated method stub } @Override public void onStatus(Status status) { Twitter twitter = new TwitterFactory().getInstance(); User user = status.getUser(); // gets Username String username = status.getUser().getScreenName(); System.out.println(""); String profileLocation = user.getLocation(); System.out.println(profileLocation); long tweetId = status.getId(); System.out.println(tweetId); String content = status.getText(); System.out.println(content + "\n"); JSONObject obj = new JSONObject(); obj.put("User", status.getUser().getScreenName()); obj.put("ProfileLocation", user.getLocation().replaceAll("'", "''")); obj.put("Id", status.getId()); obj.put("UserId", status.getUser().getId()); //obj.put("User", status.getUser()); obj.put("Message", status.getText().replaceAll("'", "''")); obj.put("CreatedAt", status.getCreatedAt().toString()); obj.put("CurrentUserRetweetId", status.getCurrentUserRetweetId()); //Get user retweeteed String otheruser; try { if (status.getCurrentUserRetweetId() != -1) { User user2 = twitter.showUser(status.getCurrentUserRetweetId()); otheruser = user2.getScreenName(); System.out.println("Other user: " + otheruser); } } catch (Exception ex) { System.out.println("ERROR: " + ex.getMessage().toString()); } obj.put("IsRetweet", status.isRetweet()); obj.put("IsRetweeted", status.isRetweeted()); obj.put("IsFavorited", status.isFavorited()); obj.put("InReplyToUserId", status.getInReplyToUserId()); //In reply to obj.put("InReplyToScreenName", status.getInReplyToScreenName()); obj.put("RetweetCount", status.getRetweetCount()); if (status.getGeoLocation() != null) { obj.put("GeoLocationLatitude", status.getGeoLocation().getLatitude()); obj.put("GeoLocationLongitude", status.getGeoLocation().getLongitude()); } JSONArray listHashtags = new JSONArray(); String hashtags = ""; for (HashtagEntity entity : status.getHashtagEntities()) { listHashtags.add(entity.getText()); hashtags += entity.getText() + ","; } if (!hashtags.isEmpty()) obj.put("HashtagEntities", hashtags.substring(0, hashtags.length() - 1)); if (status.getPlace() != null) { obj.put("PlaceCountry", status.getPlace().getCountry()); obj.put("PlaceFullName", status.getPlace().getFullName()); } obj.put("Source", status.getSource()); obj.put("IsPossiblySensitive", status.isPossiblySensitive()); obj.put("IsTruncated", status.isTruncated()); if (status.getScopes() != null) { JSONArray listScopes = new JSONArray(); String scopes = ""; for (String scope : status.getScopes().getPlaceIds()) { listScopes.add(scope); scopes += scope + ","; } if (!scopes.isEmpty()) obj.put("Scopes", scopes.substring(0, scopes.length() - 1)); } obj.put("QuotedStatusId", status.getQuotedStatusId()); JSONArray list = new JSONArray(); String contributors = ""; for (long id : status.getContributors()) { list.add(id); contributors += id + ","; } if (!contributors.isEmpty()) obj.put("Contributors", contributors.substring(0, contributors.length() - 1)); System.out.println("" + obj.toJSONString()); insertNodeNeo4j(obj); //out.println(obj.toJSONString()); String statement = "INSERT INTO TweetsClassification JSON '" + obj.toJSONString() + "';"; executeQuery(session, statement); } @Override public void onTrackLimitationNotice(int arg0) { // TODO Auto-generated method stub } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; FilterQuery fq = new FilterQuery(); fq.track(parametros); twitterStream.addListener(listener); twitterStream.filter(fq); }
From source file:tweetdownloader.cnr_stable.version.TweetDownload.java
/** * this method return an ArrayList of dataOfTweets * @param allMyTweets/*from w w w.j a va 2 s. co m*/ * @return allMyTweet */ public ArrayList<dataOfTweet> downloadMyTweet(ArrayList<dataOfTweet> allMyTweets) { { try { Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets"); for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) { dataOfTweet tweet = new dataOfTweet(); //System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber); if (searchTweetsRateLimit.getRemaining() == 0) { try { //System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset()); Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l); } catch (InterruptedException ex) { java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex); } } Query q = new Query(SEARCH_TERM); q.setCount(TWEETS_PER_QUERY); q.setLang("it"); if (maxID != -1) { q.setMaxId(maxID - 1); } QueryResult r = twitter.search(q); if (r.getTweets().isEmpty()) { break; } for (Status s : r.getTweets()) { totalTweets++; if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } if (s.isRetweeted() == false) { tweet.setUsername(s.getUser().getScreenName()); tweet.setCreatedAt(s.getCreatedAt().toString()); tweet.setTweetText(s.getText()); if (s.getGeoLocation() != null) { tweet.setLat(s.getGeoLocation().getLatitude()); tweet.setLongi(s.getGeoLocation().getLongitude()); } } } allMyTweets.add(tweet); } } catch (TwitterException ex) { java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex); } } return allMyTweets; }
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 .ja va2 s. c o 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>"); } }