Twitter Bot - Java Social Media

Java examples for Social Media:Twitter

Description

Twitter Bot

Demo Code



import java.lang.Exception;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.Status;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import com.sun.syndication.feed.synd.SyndEntry;
import java.net.URL;
import java.io.InputStreamReader;
import java.util.List;

import com.sun.syndication.feed.synd.SyndLinkImpl;
import com.sun.syndication.feed.synd.SyndCategoryImpl;
import com.sun.syndication.feed.synd.SyndContentImpl;

public class NewsBot {

    public static Properties getCredentials() throws FileNotFoundException {
        String propFilename = "twitter.properties";
        InputStream inStream = null;
        Properties prop = new Properties();

        inStream = NewsBot.class.getClassLoader().getResourceAsStream(
                propFilename);/*w  ww. ja  v  a  2 s .c  o m*/
        if (inStream == null) {
            throw new FileNotFoundException("property file '"
                    + propFilename + "' not found.");
        }

        try {
            prop.load(inStream);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("ERROR: " + ex.getMessage());
        }

        return prop;
    }

    public static Twitter connectTwitterAPI(String consumerKey,
            String consumerSecret, String token, String tokenSecret) {

        try {
            Twitter twitter = new TwitterFactory().getSingleton();

            twitter.setOAuthConsumer(consumerKey, consumerSecret);
            AccessToken accessToken = new AccessToken(token, tokenSecret);

            twitter.setOAuthAccessToken(accessToken);

            return twitter;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("ERROR: " + ex.getMessage());
        }

        return null;
    }

    public static SyndEntry readFeed(String urlString) {
        try {
            URL feedUrl = new URL(urlString);

            SyndFeedInput input = new SyndFeedInput();
            SyndFeed feed = input.build(new XmlReader(feedUrl));
            List<SyndEntry> entries = feed.getEntries();
            SyndEntry entry = entries.get(0);

            return entry;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("ERROR: " + ex.getMessage());
        }

        return null;
    }

    public static void main(String[] args) {
        Properties p = null;

        //get keys to access the api
        try {
            p = getCredentials();
        } catch (FileNotFoundException fnfe) {
            fnfe.getMessage();
        }

        Twitter myTwitter = connectTwitterAPI(
                p.getProperty("consumer_key"),
                p.getProperty("consumer_api"),
                p.getProperty("access_token_key"),
                p.getProperty("access_token_secret"));

        Feed rssFeed = new Feed();
        FeedAtom atomFeed = new FeedAtom();

        Status status = null;
        String tweet = null;
        DateFormat df = new SimpleDateFormat("yyyy-M-d HH:mm:ss z");

        while (true) {
            //for RSS Feeds
            rssFeed.parseFeed();
            if (rssFeed.isUpdated()) {
                System.out.println("Most recent rss entry: "
                        + df.format(rssFeed.mostRecent));

                for (SyndEntry e : rssFeed.getEntries()) {
                    try {
                        tweet = new String("\"" + e.getTitle() + "\" "
                                + e.getUri() + " "
                                + "#news #BBC #CNN #Reuters");

                        status = myTwitter.updateStatus(tweet);
                        System.out
                                .println("Successfully updated the status to ["
                                        + status.getText() + "].");
                    } catch (TwitterException te) {
                        te.printStackTrace();
                        System.out.println("ERROR: " + te.getMessage());
                    }
                }

            }

            //for Atom Feeds
            atomFeed.parseFeed();
            if (atomFeed.isUpdated()) {
                System.out.println("Most recent atom entry: "
                        + df.format(atomFeed.mostRecent));
                for (SyndEntry e : atomFeed.getEntries()) {
                    List<SyndLinkImpl> links = e.getLinks();
                    SyndLinkImpl firstLink = links.get(0);

                    try {
                        tweet = new String("\"Magnituede: " + e.getTitle()
                                + "\" " + firstLink.getHref() + " "
                                + df.format(e.getUpdatedDate()) + " "
                                + "#news #earthquakes #quakes");

                        status = myTwitter.updateStatus(tweet);
                        System.out
                                .println("Successfully updated the status to ["
                                        + status.getText() + "].");
                    } catch (TwitterException te) {
                        te.printStackTrace();
                        System.out.println("ERROR: " + te.getMessage());
                    }
                }
            }

            try {
                Thread.sleep(10000); //wait 10 seconds
            } catch (InterruptedException ie) {
                //call to Thread.sleep
                ie.printStackTrace();
                System.out.println("ERROR: " + ie.getMessage());
            }
        } //end while polling loop

    } //end main
} //end NewsBot

Related Tutorials