Main.IrcBot.java Source code

Java tutorial

Introduction

Here is the source code for Main.IrcBot.java

Source

package Main;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.Object;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author 
 */
public class IrcBot {
    public String name;
    public String hostName;
    public int portNumber;
    public String channel;

    public IrcBot(String ircBotName, String hostName, int portNumber, String channel) {
        this.name = ircBotName;
        this.hostName = hostName;
        this.portNumber = portNumber;
        this.channel = channel;

        this.serverConnect();
    }

    public void printName() {
        System.out.println(this.name);
    }

    public static void postGit(String pasteBinSnippet, PrintWriter out) {
        try {
            String url = "https://api.github.com/gists";
            URL obj = new URL(url);
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

            //add reuqest header
            JSONObject x = new JSONObject();
            JSONObject y = new JSONObject();
            JSONObject z = new JSONObject();
            z.put("content", pasteBinSnippet);
            y.put("index.txt", z);
            x.put("public", true);
            x.put("description", "LPBOT");
            x.put("files", y);
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "public=true&description=LPBOT";

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(x.toString());
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            JSONObject gitResponse = new JSONObject(response.toString());
            String newGitUrl = gitResponse.getString("html_url");

            if (newGitUrl.length() > 0) {
                out.println("PRIVMSG #learnprogramming :The paste on Git: " + newGitUrl);
            }
            System.out.println(newGitUrl);
        } catch (Exception p) {

        }
    }

    public static void postRequest(String pasteCode, PrintWriter out) {
        try {
            String url = "http://pastebin.com/raw.php?i=" + pasteCode;
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "";

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine + "\n");
            }
            in.close();

            //print result
            System.out.println(response.toString());

            if (response.length() > 0) {
                IrcBot.postGit(response.toString(), out);
            } else {
                out.println("PRIVMSG #learnprogramming :The PasteBin URL is not valid.");
            }
        } catch (Exception p) {

        }
    }

    public void serverConnect() {
        try {
            Socket ircSocket = new Socket(this.hostName, this.portNumber);

            if (ircSocket.isConnected()) {
                final PrintWriter out = new PrintWriter(ircSocket.getOutputStream(), true);
                final BufferedReader in = new BufferedReader(new InputStreamReader(ircSocket.getInputStream()));
                final BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

                String userInput;
                String pass = "PASS *";
                String nick = "NICK " + this.name;
                String user = "USER " + this.name + " 8 * :" + this.name;
                String channel = "JOIN " + this.channel;
                Timer channelChecker = new Timer();

                out.println(pass);
                System.out.println("echo: " + in.readLine().toString());
                out.println(nick);
                System.out.println("echo: " + in.readLine().toString());
                out.println(user);
                System.out.println("echo: " + in.readLine().toString());
                out.println(channel);

                channelChecker.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            String userIn = in.readLine().toString();
                            ;
                            System.out.println(userIn);

                            if (userIn.contains("PING")) {
                                out.println("PONG hobana.freenode.net");
                            }

                            if (userIn.contains("http://pastebin.com")) {
                                //String[] urlCode = userIn.split("[http://pastebin.com]");

                                String url = "http://pastebin.com";
                                int indexStart = userIn.indexOf(url);
                                int indexStop = userIn.indexOf(" ", indexStart);
                                String urlCode = userIn.substring(indexStart, indexStop);
                                String pasteBinId = urlCode.substring(urlCode.indexOf("/", 9) + 1,
                                        urlCode.length());
                                System.out.println(pasteBinId);

                                IrcBot.postRequest(pasteBinId, out);
                            }

                        } catch (Exception j) {

                        }
                    }
                }, 100, 100);

            } else {
                System.out.println("There was an error connecting to the IRC server: " + this.hostName
                        + " using port " + this.portNumber);
            }
        } catch (Exception e) {
            //System.out.println(e.getMessage());
        }
    }
}