RandomPicBot.java Source code

Java tutorial

Introduction

Here is the source code for RandomPicBot.java

Source

/*
 * Copyright (c) 2015 Talha Ishakbeyoglu
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See the COPYING file for more details.
 */

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import java.util.Random;

import org.yaml.snakeyaml.Yaml;

import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class RandomPicBot {

    /*
     * Checks to see if the file is a jpeg or png file
     * checks if the file extension is jpg, jpeg or png
     * returns true if file is a jpeg or png file, false otherwise
     */
    private static boolean isImage(File file) {
        String fileName = file.getName();
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("jpeg")
                    || extension.equalsIgnoreCase("png"))
                return true;
        }

        return false;
    }

    public static void main(String[] args) {
        /*
         * initialize the yaml setup
         * reads from keys.yml in the classpath, or same directory as the program
         */
        Yaml yaml = new Yaml();
        InputStream fileInput = null;
        try {
            fileInput = new FileInputStream(new File("keys.yml"));
        } catch (FileNotFoundException e1) {
            System.out.println("keys.yml not found!");
            e1.printStackTrace();
            System.exit(0);
        }
        @SuppressWarnings("unchecked") //unchecked cast, who cares.
        Map<String, String> map = (Map<String, String>) yaml.load(fileInput);

        /*
         * extracts values from the map
         */

        String CONSUMER_KEY = map.get("CONSUMER_KEY");
        String CONSUMER_SECRET = map.get("CONSUMER_SECRET");
        String TOKEN = map.get("TOKEN");
        String TOKEN_SECRET = map.get("TOKEN_SECRET");
        long USER_ID = Long.parseLong(map.get("USER_ID"));

        /*
         * initialize Twitter using the keys we got from the yaml file
         */

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(new AccessToken(TOKEN, TOKEN_SECRET, USER_ID));

        /*
         * set up our picture folder
         * gets the folder from the command line argument
         * may change this to yaml too in the future
         */
        File directory = new File(args[0]);
        File[] pictures = directory.listFiles(new FileFilter() {
            /*
             * check to make sure the file is under 3mb(with some wiggle room) and is an acceptable image(non-Javadoc)
             * @see java.io.FileFilter#accept(java.io.File)
             */
            public boolean accept(File pathname) {
                if (pathname.isFile() && pathname.length() < 3000000 && isImage(pathname)) {
                    return true;
                } else
                    return false;
            }
        });

        System.out.println(pictures.length + " usable files found.");

        Random rand = new Random();

        /*
         * convert our minute value into milliseconds since thats what Thread.sleep() uses
         */

        int WAIT_TIME = Integer.parseInt(args[1]) * 60 * 1000;

        String statusText = "";
        if (args[2] != null) {
            for (int i = 2; i < args.length; i++) {
                statusText += args[i] + " ";
            }
            statusText.trim();
        }

        if (statusText.length() > 117) {
            System.out.println("Your message is too long!");
            System.out.println("Only messages up to 117 characters are supported!");
            System.exit(5);
        }

        StatusUpdate status = new StatusUpdate(statusText);

        /*
         * main loop
         * generate a random number to choose our image with
         * then upload the image to twitter
         * then wait for the defined time(gotten from the command line in minutes)
         */

        while (true) {
            int index = rand.nextInt(pictures.length);
            status.setMedia(pictures[index]);

            try {
                System.out.print("uploading picture: " + pictures[index].getName());
                if (!statusText.equals(""))
                    System.out.println(" with text: " + statusText);
                else
                    System.out.println();
                twitter.updateStatus(status);
            } catch (TwitterException e) {
                System.out.println("Problem uploading the file!");
                e.printStackTrace();
            }
            try {
                Thread.sleep(WAIT_TIME);
            } catch (InterruptedException e) {
                System.out.println("Program was interrupted!");
                e.printStackTrace();
            }
        }
    }

}