List of usage examples for twitter4j Status getId
long getId();
From source file:traffickarmasent.TweetCollection.java
public static void main(String[] args) throws FileNotFoundException, IOException, Exception { // loading slang dictionary with key as slang and value as its full form slangMap = new HashMap<String, String>(); BufferedReader slangRead = new BufferedReader(new FileReader("extras/out.txt")); String line = ""; while ((line = slangRead.readLine()) != null) { String parts[] = line.split("\t"); slangMap.put(parts[0], parts[1]); }//from w w w.j a v a 2 s. c o m slangRead.close(); //loading entity list BufferedReader htm_in = new BufferedReader(new FileReader("extras/html_ent.txt")); entityList = new ArrayList<String>(); while ((line = htm_in.readLine()) != null) { entityList.add(line); } FileInputStream fos1 = new FileInputStream(new File("extras/hash1.dat")); // loading emoticon dictionary, with key as emoticon and value as its sentiment score ObjectInputStream out1 = new ObjectInputStream(fos1); emohash1 = (HashMap<String, Double>) out1.readObject(); //System.out.println(hm1); FileInputStream fos2 = new FileInputStream(new File("extras/hash2.dat")); // loading emoticon dictionary, with key as emoticon and value as its sentiment score ObjectInputStream out2 = new ObjectInputStream(fos2); emohash2 = (HashMap<String, Double>) out2.readObject(); //System.out.println(hm2); //loading senti-wordnet FileReader fr2 = new FileReader("extras/SentiWordNet_scores_final.txt"); BufferedReader br2 = new BufferedReader(fr2); String str2; senti_map = new HashMap<String, Double>(); while ((str2 = br2.readLine()) != null) { StringTokenizer st = new StringTokenizer(str2, "^"); senti_map.put(st.nextToken(), Double.parseDouble(st.nextToken())); } String serializedClassifier = "english.all.3class.distsim.crf.ser.gz"; //NER configuration AbstractSequenceClassifier classifier = CRFClassifier.getClassifierNoExceptions(serializedClassifier); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); MaxentTagger tagger = new MaxentTagger("taggers/english-left3words-distsim.tagger"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true); cb.setOAuthConsumerKey("ufulV3imKoYNzdh58LotTC1YD"); cb.setOAuthConsumerSecret("2A781ma736HTenAXXYn9tRIelQYJkbCqY0GLi7W71ZwwDmNU59"); cb.setOAuthAccessToken("2564905075-MY9osfHabaRnonQVHHhHeA1vCLSOhuHWjBNBiIY"); cb.setOAuthAccessTokenSecret("JsD8Woc7iiFiDSwoCwjNAb6KNEurz7tBqSj9pJV8WXabr"); twitter4j.TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { double score = 0.0; double count = 0; ArrayList<String> locArray = new ArrayList<String>(); @Override public void onStatus(Status status) { String text = status.getText(); double geoLat = 0.0; double geoLng = 0.0; String tweetId = status.getId() + ""; String userName = status.getUser().getName(); String userId = status.getUser().getId() + ""; if (status.getGeoLocation() != null) { geoLat = status.getGeoLocation().getLatitude(); geoLng = status.getGeoLocation().getLongitude(); } tweetClean(text, status.getGeoLocation()); System.out.println(text + "\n" + tweetId + " " + userName + " " + userId); } @Override public void onDeletionNotice(StatusDeletionNotice sdn) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void onTrackLimitationNotice(int i) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void onScrubGeo(long l, long l1) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void onException(Exception excptn) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void tweetClean(String message, GeoLocation loc) { try { // URL removal message = removeUrl(message); System.out.println("lalala" + message); //removing user mentions message = userMentions(message); //slang removal String[] acro = slangRemoval(message); //entity removal String[] finaldata = entityRemoval(acro); message = ""; for (String word : finaldata) { message += word + " "; } //System.out.println(message); //Ner Taggging String XmlData = classifier.classifyWithInlineXML(message); message = XmlData; //handling words to the spell_checked String[] data = message.split("<"); String val = ""; for (String word : data) { if (word.startsWith("PER") || word.startsWith("LOC")) { word = word.replaceAll("PERSON>", ""); word = word.replaceAll("/PERSON>", ""); word = word.replaceAll("LOCATION>", ""); word = word.replaceAll("/LOCATION>", ""); //insert word into database here locArray.add(word); } else { word = word.replaceAll("/PERSON>", ""); word = word.replaceAll("/LOCATION>", ""); //System.out.println(word); val += word; } } //System.out.println("see" + val); if (loc != null || locArray.size() > 0) { val = val.replaceAll("\\s+", " "); String[] temp = val.split(" "); String match = ""; //spell_check for (String word : temp) { //System.out.println(word); if (emohash2.containsKey(word)) { score += emohash2.get(word); count++; message = message.replace(word, ""); } Process p = Runtime.getRuntime().exec("python extras/text_blob.py " + word); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); //System.out.println(in.readLine()); match = in.readLine(); //match = spell_check(word); //System.out.println(match); if (!match.equals(word)) { message = message.replaceAll(word, match); } } System.out.println(message); //UTF-8 emoji's emojiDetection(message); //handle NerTags message = af_spellcheck(message); //System.out.println(a); //removing irrelevant chars message = removeChars(message); //System.out.println(a); //POS- TAGGING message = posTagging(message); // removing prepositions and nouns message = removePrepn(message); //System.out.println(a); sentiScores(message); System.out.println(score); System.out.println(score / count); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } public String removeUrl(String message) { String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; Pattern p = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(message); int i = 0; while (m.find()) { message = message.replaceAll(m.group(i), "").trim(); i++; } return message; } public String af_spellcheck(String message) { message = message.replaceAll("<PERSON>", ""); message = message.replaceAll("</PERSON>", ""); message = message.replaceAll("<LOCATION>", ""); message = message.replaceAll("</LOCATION>", ""); return message; } public String removeChars(String message) { message = message.replaceAll("\\.", ""); message = message.replaceAll("\\!", ""); message = message.replaceAll("\\$", ""); message = message.replaceAll("\\%", ""); message = message.replaceAll("\\^", ""); message = message.replaceAll("\\|", ""); message = message.replaceAll("\\+", ""); message = message.replaceAll("\\:", ""); message = message.replaceAll("\\(", ""); message = message.replaceAll("\\)", ""); message = message.replaceAll("\\*", ""); message = message.replaceAll("\\{", ""); return message; } public void sentiScores(String message) { message = message.replaceAll("_NNS", "_n"); message = message.replaceAll("_NN", "_n"); message = message.replaceAll("_RBR", "_r"); message = message.replaceAll("_RBS", "_r"); message = message.replaceAll("_RB", "_r"); message = message.replaceAll("_JJR", "_a"); message = message.replaceAll("_JJS", "_a"); message = message.replaceAll("_JJ", "_a"); message = message.replaceAll("_VBD", "_v"); message = message.replaceAll("_VBG", "_v"); message = message.replaceAll("_VBN", "_v"); message = message.replaceAll("_VBP", "_v"); message = message.replaceAll("_VBZ", "_vs"); message = message.replaceAll("_VB", "_v"); message = message.replaceAll("\\s+", " "); // System.out.println(message); String[] senti_token = message.split(" "); for (String word : senti_token) { word = word.toLowerCase(); System.out.println(word); if (senti_map.containsKey(word)) { score += senti_map.get(word); //System.out.println(score); count++; } } } public void emojiDetection(String message) { Pattern emo = Pattern.compile("[\\uD83D\\uDE01-\\uD83D\\uDE4F]"); Matcher m_emo = emo.matcher(message); while (m_emo.find()) { if (emohash1.containsKey(m_emo.group())) //System.out.println("llalala"); { score += emohash1.get(m_emo.group()); } count++; } } public String userMentions(String message) { Pattern p = Pattern.compile("\\@\\w+"); Matcher m = p.matcher(message); while (m.find()) { //System.out.println(m.group()); message = message.replaceAll(m.group(), ""); } return message; } public String[] slangRemoval(String message) { ArrayList<String> slangRemovalList = new ArrayList<String>(); String[] words = message.split(" "); for (String single : words) { if (slangMap.containsKey(single.toUpperCase())) { slangRemovalList.add(slangMap.get(single.toUpperCase())); } else { slangRemovalList.add(single); } } String[] myArray = new String[slangRemovalList.size()]; slangRemovalList.toArray(myArray); return myArray; } public String posTagging(String message) throws Exception { String tagged = tagger.tagString(message); return tagged; } public String removePrepn(String message) { String delims = " "; String[] tokens = message.split(delims); for (String word : tokens) { if (word.endsWith("_IN") || word.endsWith("_NNP") || word.endsWith("_NNPS")) { message = message.replace(word, ""); } } return message; } public String[] entityRemoval(String[] message) { List<String> finalList = new ArrayList<String>(); for (String word : message) { if (!entityList.contains(word.trim())) { finalList.add(word); } } String[] myArray = new String[finalList.size()]; finalList.toArray(myArray); return myArray; } }; FilterQuery fq = new FilterQuery(); String keywords[] = { "Mumbai traffic", "@TrafflineMUM", "TrafficMum", "MumbaiTrafficPol", "avoid traffic Mumbai", "Breakdown Mumbai traffic", "@smart_mumbaikar", "@TrafficBOM", "#StreetSmartWithTraffline mumbai", "#mumbai #TRAFFICALERT ", "#mumbai #TRAFFIC" }; fq.track(keywords); twitterStream.addListener(listener); twitterStream.filter(fq); }
From source file:tv.phantombot.cache.TwitterCache.java
License:Open Source License
private void handleRetweetRewards(long lastTime, long presentTime) { if (presentTime - lastTime < 300) { return;/*w w w . j av a 2s . c om*/ } updateDBLong("lastpoll_retweets_reward", presentTime); long lastID = getDBLong("lastid_retweets_reward", true, 0L); List<Status> statuses = TwitterAPI.instance().getRetweetsOfMe(lastID); if (statuses == null) { return; } /* This seems redundant but, Twitter provides the Tweet content of the Retweets in the * getRetweetsOfMe() call. So, walk that list of Tweets to get at the Retweet information * that includes the Screen Name (@screenName) of the person that performed the Retweet. */ ArrayList<String> userNameList = new ArrayList<String>(); for (Status status : statuses) { List<Status> retweetStatuses = TwitterAPI.instance().getRetweets(status.getId()); if (retweetStatuses != null) { for (Status retweetStatus : retweetStatuses) { userNameList.add(retweetStatus.getUser().getScreenName()); } } } if (!userNameList.isEmpty()) { EventBus.instance() .post(new TwitterRetweetEvent(userNameList.toArray(new String[userNameList.size()]))); } /* Update DB with the last Tweet ID processed. */ long twitterID = statuses.get(0).getId(); updateDBLong("lastid_retweets_reward", twitterID); }
From source file:tweet.Miner.java
License:Apache License
/** * Usage: java twitter4j.examples.search.SearchTweets [query] * * @param toSearch /*from w w w .ja v a 2s.c o m*/ */ public List<Status> mine(String toSearch) { List<Status> results = new ArrayList<Status>(); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET) .setOAuthAccessToken(OAUTH_ACCESS_TOKEN).setOAuthAccessTokenSecret(OAUTH_ACCESS_TOKEN_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Query query = new Query(toSearch); query.setCount(100); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); results.addAll(result.getTweets()); for (Status tweet : tweets) { System.out.println( tweet.getId() + " @ " + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); } catch (Exception e) { e.printStackTrace(); } return results; }
From source file:tweetcrawling.TweetCrawler.java
public ArrayList<String> getValueToWrite(Status status) { // Getting the value to be written Long tid = status.getId(); String tweetid = tid.toString(); ArrayList<String> valueToWrite = new ArrayList<String>(); User user = status.getUser();/*from w w w . j ava 2s . co m*/ String screenname = user.getScreenName(); String name = user.getName(); String url = getTweetUrl(screenname, tweetid); String body = status.getText().replace("\n", " "); valueToWrite.add(body.replace(",", " ")); // element: body valueToWrite.add(url); // element: id valueToWrite.add(screenname); // element: userid valueToWrite.add(name); // element: user // element: gender if (name != null && !name.isEmpty()) { valueToWrite.add(getUserGender(name)); } else if (screenname != null && !screenname.isEmpty()) { valueToWrite.add(getUserGender(screenname)); } else { valueToWrite.add(""); } valueToWrite.add(user.getLocation()); // element: location valueToWrite.add("" + user.getFollowersCount()); // element: followercount valueToWrite.add("" + user.getFriendsCount()); // element: friendscount valueToWrite.add("" + user.getStatusesCount()); // element: statuscount try { List<String> coor = new ArrayList<String>(); String latitude = "" + status.getGeoLocation().getLatitude(); String longitude = "" + status.getGeoLocation().getLongitude(); coor.add(latitude); coor.add(longitude); if (coor != null && !coor.isEmpty() && coor.size() > 0) { valueToWrite.add(coor.get(0)); // element: latitude valueToWrite.add(coor.get(1)); // element: longitude valueToWrite.add(coor.get(0) + "," + coor.get(1)); } else { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } try { String geoname = status.getPlace().getName(); String country = status.getPlace().getCountry(); if (geoname != null) { valueToWrite.add(geoname); } else { valueToWrite.add(null); } if (country != null) { valueToWrite.add(country); } else { valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date date = status.getCreatedAt(); valueToWrite.add(dateFormat.format(date)); // element: date valueToWrite.add(getDateCrawler()); // element: datecrawler valueToWrite.add(status.getInReplyToScreenName()); // element: replyto String tooltip = ""; try { String geoname = status.getPlace().getName(); if (geoname != null) { tooltip = "user = " + name + ", geoname = " + geoname; } } catch (Exception e) { tooltip = ""; } valueToWrite.add(tooltip.trim()); // element: tooltip valueToWrite.add(SOURCE); // element: source return valueToWrite; }
From source file:tweetcrawling.TweetCrawler.java
public void printTweets(String csvOut) throws IOException, TwitterException { for (Status status : getStatuses()) { // Getting the value to be written Long tid = status.getId(); String tweetid = tid.toString(); ArrayList<String> valueToWrite = new ArrayList<String>(); User user = status.getUser();//from w w w.j a v a2 s . c o m String screenname = user.getScreenName(); String name = user.getName(); String url = getTweetUrl(screenname, tweetid); valueToWrite.add(url); // element: id valueToWrite.add(screenname); // element: userid valueToWrite.add(name); // element: user // element: gender if (name != null && !name.isEmpty()) { valueToWrite.add(getUserGender(name)); } else if (screenname != null && !screenname.isEmpty()) { valueToWrite.add(getUserGender(screenname)); } else { valueToWrite.add(""); } valueToWrite.add(user.getLocation()); // element: location valueToWrite.add("" + user.getFollowersCount()); // element: followercount valueToWrite.add("" + user.getFriendsCount()); // element: friendscount valueToWrite.add("" + user.getStatusesCount()); // element: statuscount try { List<String> coor = new ArrayList<String>(); String latitude = "" + status.getGeoLocation().getLatitude(); String longitude = "" + status.getGeoLocation().getLongitude(); coor.add(latitude); coor.add(longitude); if (coor != null && !coor.isEmpty() && coor.size() > 0) { valueToWrite.add(coor.get(0)); // element: latitude valueToWrite.add(coor.get(1)); // element: longitude valueToWrite.add(coor.get(0) + "," + coor.get(1)); } else { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } try { String geoname = status.getPlace().getName(); String country = status.getPlace().getCountry(); if (geoname != null) { valueToWrite.add(geoname); } else { valueToWrite.add(null); } if (country != null) { valueToWrite.add(country); } else { valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date date = status.getCreatedAt(); valueToWrite.add(dateFormat.format(date)); // element: date valueToWrite.add(getDateCrawler()); // element: datecrawler valueToWrite.add(status.getText()); // element: body valueToWrite.add(status.getInReplyToScreenName()); // element: replyto String tooltip = ""; try { String geoname = status.getPlace().getName(); if (geoname != null) { tooltip = "user = " + name + ", geoname = " + geoname; } } catch (Exception e) { tooltip = ""; } valueToWrite.add(tooltip.trim()); // element: tooltip valueToWrite.add(SOURCE); // element: source // Write valueToWrite to csv external file FileWriter fw = new FileWriter(csvOut, true); PrintWriter pw = new PrintWriter(fw); String content = "'"; for (int i = 0; i < valueToWrite.size() - 1; i++) { content += valueToWrite.get(i) + "','"; } content += valueToWrite.get(valueToWrite.size()) + "'"; pw.print(content); pw.flush(); pw.close(); fw.close(); } }
From source file:tweetdownloader.cnr_stable.version.TweetDownload.java
/** * this method return an ArrayList of dataOfTweets * @param allMyTweets//from w ww . jav a 2 s.c om * @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:tweets.Tweets.java
/** * @param args the command line arguments *//*w ww. ja v a 2 s.c o m*/ public static void main(String[] args) throws Exception { ConfigurationBuilder configurtacion = new ConfigurationBuilder(); configurtacion.setDebugEnabled(true).setOAuthConsumerKey("KdVOb7h8mqcjWIfkXXED2G6sJ") .setOAuthConsumerSecret("EXImfgfGCYIbWZIOSEeYVvaDE5oxwJZY7UIuwUusbyRWf2ds7l") .setOAuthAccessToken("785481406654722049-aRARaHgZujPZIdpYla4mVZIMMlvzJRb") .setOAuthAccessTokenSecret("YWWQwbFw8K7rxsnivwpBRZVoQlUhMYy7gOs7KUWOb8Rvy"); Twitter twitter = new TwitterFactory(configurtacion.build()).getInstance(); twitter.getUserTimeline(); String hashtag = "#ElectionNight"; Query busqueda = new Query(hashtag); int numeroTweets = 1500; long ultimo = Long.MAX_VALUE; ArrayList<Status> tweets = new ArrayList<Status>(); while (tweets.size() < numeroTweets) { if (numeroTweets - tweets.size() > 255) { busqueda.setCount(255); } else { busqueda.setCount(numeroTweets - tweets.size()); } try { QueryResult result = twitter.search(busqueda); tweets.addAll(result.getTweets()); System.out.println("Generados " + tweets.size() + " tweets" + "\n"); for (Status t : tweets) { if (t.getId() < ultimo) { ultimo = t.getId(); } System.out.println("Generados " + tweets.size() + " tweets" + "\n"); } } catch (TwitterException excepcion) { System.out.println("Sin conexin " + excepcion); } ; busqueda.setMaxId(ultimo - 1); } // guardamos los datos java.util.Date fecha = new Date(); int hora = fecha.getHours(); int minuto = fecha.getMinutes(); System.out.println(); String nombre = "Datos_" + hashtag + " " + hora + " " + minuto + ".txt"; File f = new File(nombre); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); System.out.println("identificador\tUsuario\ttweet\n"); for (int i = 0; i < tweets.size(); i++) { Status estadoTweet = (Status) tweets.get(i); GeoLocation loc = estadoTweet.getGeoLocation(); String user = estadoTweet.getUser().getScreenName(); String msg = estadoTweet.getText(); Boolean sensitive = estadoTweet.isPossiblySensitive(); int fav = estadoTweet.getFavoriteCount(); System.out.println("Id: " + i + "| User: " + user + "| Texto: " + msg + "| SentimientoPositivo: " + sensitive + "$\n"); int id = i + 1; bw.append(msg + " | " + sensitive + ";"); bw.newLine(); } bw.close(); }
From source file:twit.Twit.java
public static void onStatus(Status status, int kode) { Twitter tf = new TwitterFactory().getInstance(); //kode 1 : Format benar if (kode == 1) { StatusUpdate st = new StatusUpdate("Hi @" + status.getUser().getScreenName() + ", terima kasih telah membantu monitoring harga Cabe Indonesia :D"); st.inReplyToStatusId(status.getId()); try {/*from w ww .j a v a 2 s. co m*/ tf.updateStatus(st); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } //kode 2 : Format salah } else if (kode == 2) { StatusUpdate st = new StatusUpdate( "Hi @" + status.getUser().getScreenName() + ", terima kasih atas laporan Anda! :)"); st.inReplyToStatusId(status.getId()); try { tf.updateStatus(st); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } //kode 2 : Format salah } else { System.out.println("error"); } }
From source file:twit.Twit.java
public void userMention() throws SQLException, ParseException { Twitter twitter = new TwitterFactory().getInstance(); try {//from w w w .ja v a 2s .c o m Long since_id = cek_last_mention(); Paging paging = new Paging().sinceId(since_id); List<Status> statuses = twitter.getMentionsTimeline(paging); for (twitter4j.Status status : statuses) { long ID_TWEET = status.getId(); String USERNAME = status.getUser().getScreenName(); String TWEET = status.getText().replace("'", "\\'"); save_user(USERNAME); String ID_MASYARAKAT = cekMasyarakat(USERNAME); if (USERNAME.equals("tahupongcode")) { //reply akun sendiri save_data_mentions(ID_TWEET); } else { if (Regex(TWEET)[0].equals("harga")) { //masukkan hasil regex pada array String[] hasil = Regex(TWEET); //ambil isi array int KOMODITAS = cekKomoditas(hasil[2]); String TITIK_DISTRIBUSI = cekTitik(hasil[3]); String HARGA = hasil[4]; save_harga(KOMODITAS, TITIK_DISTRIBUSI, ID_MASYARAKAT, USERNAME, HARGA); if (cek_replied(ID_TWEET) == false) { save_data_mentions(ID_TWEET); onStatus(status, 1); } } else if (Regex(TWEET)[0].equals("keluhan")) { //masukkan hasil regex pada array String[] hasil = Regex(TWEET); //ambil isi array String SUBJECT = hasil[2]; String KELUHAN = hasil[3]; String KABUPATEN = cekKabupaten(hasil[4]); insertKeluhan(ID_MASYARAKAT, SUBJECT, KELUHAN, KABUPATEN); if (cek_replied(ID_TWEET) == false) { save_data_mentions(ID_TWEET); onStatus(status, 2); } } else { System.out.println("error"); } } } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } }
From source file:twitbak.MentionBak.java
License:Open Source License
public void statusToJson(Status status) throws TwitterException, JSONException { JSONObject result = new JSONObject(); User poster = status.getUser();//from w w w .j a va 2 s .c o m result.put("Poster ID", poster.getId()); result.put("Poster", poster.getScreenName()); result.put("Poster Name", poster.getName()); 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); }