LIITE 2 CoffeeBot class package fi.tkk.automationit.coffeebot; / A CoffeeBot class. CoffeeBot is aplication for communication between the Coffee Maker bundele and the IRC-channel. CoffeeBot uses the class PircBot. With its methods CoffeeBot joins to the given server and channel. CoffeeBot is listening the conversation in the channel and reacts if any sentence written to the channel begins with mark!. CoffeeBot converts the orders so that the Coffee Maker bundle can understand them and then sends them to it. CoffeeBot prints to the channel the events that it gets from Coffee Maker Bundle. @author Juha Sironen & Henri Nieminen / import java.io.ioexception; public class CoffeeBot extends PircBot { private BotListener BL = null; //Variable class BotListener private CoffeeService cservice = null; //Variable Coffee Maker service private BotActivator BA = null; //Variable class BotActivator private UsersList Users = null; //Variable table that are permitted to order private String channel; //Variable what channel the bot connects private String server; //Variable what server the bot connects private String param1; //Variable that is build from message to the bot private String param2; //Variable that is build from message to the bot public int Try = 0; //Parameter contains the number of connection attempts public int TryLimit = 2016; //Parameter that contains the number of connection attempts will be made public long WaitTime = 300000; //Parameter the time (ms) that will be waited between connection attempts public int Nicks = 0; //Variable running number that will be added at the end of the nick if the nick is all ready in use public String OrginalName = ""; //Variable for the original name of the Bot public long GotOnline = 0; //Variable the time when the connection succeed / Constructs a new CoffeeBot. The constructor creates new CoffeeBot and overwrites the variable OriginalName with the desired name of the CoffeBot. @param BotName the desired name for the CoffeeBotille. @param channel the channel that the CoffeeBot will connect to. @param server the server that the CoffeeBot will connect to. @param BA Bundle Activator /
public CoffeeBot(String BotName,String channel, String server, BotActivator BA) { this.setname(botname); this.channel = channel; this.server = server; this.ba = BA; OrginalName = this.getname(); / Adds service CoffeeService to the CoffeeBot. @param cservice CoffeeService / public void insertcservice(coffeeservice cservice){ this.cservice = cservice; / Adds BotListener for the CoffeeBot. @param BL BotListener / public void insertbl(botlistener BL){ this.bl = BL; / This method is called whenever a message is sent to a channel. <p> If the message begins with mark! and the Coffee Maker bundle is running the message will be checked. The message is parsed to three parts from the spaces The first word is command and the two following are the parameters of the command. The command is compared to known kommands and if it exicts the method for the command will be executed. Some of the methods are allowed to be used for authorizated users only. @param channel The channel to which the message was sent. @param sender The nick of the person who sent the message. @param login The login of the person who sent the message. @param hostname The hostname of the person who sent the message. @param message The actual message sent to the channel. / public void onmessage(string channel, String sender,string login, String hostname, String message) { String s0 = Character.toString(message.charAt(0)); begins with mark! if(s0.equals("!")){ //checks if the message String name = this.getname(); String word = ""; this.param1 = ""; this.param2 = ""; int length = message.length(); int i1 = 1; String shouter = sender + "," + login;
if(bl!=null){ //Checks that the BotListener is created. if(bl.getcoffeemakeronline()){ //Checks that the Coffee Maker bundle is available. do{ char c1 = message.charat(i1); String s1 = Character.toString(c1); //Creates command from the beginning of the sentence, untill there is space. if(s1.equals(" ")){ i1++; do{ char c2 = message.charat(i1); // pace. String s2 = Character.toString(c2); //Creates paremeter from the message between first and the second if(s2.equals(" ")){ i1++; do{ //Create parameter from the end of the message char c3 = message.charat(i1); String s3 = Character.toString(c3); param2 = param2 + s3; i1++; while (i1!= length); break; s1; param1 = param1 + s2; i1++; while (i1!= length); break; word = word + i1++; while (i1!= length); if(word.equals("order")){
if(users.isuser(shouter)){ //If the command is order and the user is permitted user then it calls OrderCoffee method. this.ordercoffee(param1, param2, name, sender, login); else{ send(sender + ", " + login + ", " + hostname + " et ole " + "sallittu käyttäjä tilaamaan kahvia."); else if(word.equals("last")){ //If the command is last then call Last method. this.last(); else if(word.equals("cmonline")){ //If the command is cmonlien then call cmonline method. this.cmonline(); if(word.equals("botonline")){ BotOnline method. this.botonline(); if(word.equals("listusers")){ ListUsers method. else //If the command is botonline then call else //If the command is listusers then call this.listusers(); else if(word.equals("adduser")){ //If the command is adduser and the user is permitted user then call AddUser method. if(users.isuser(shouter)){ this.adduser(param1,param2,sender); else{ send(sender + ", " + login + ", " + hostname + " et ole " + "sallittu käyttäjä lisäämään uutta käyttäjää."); else if(word.equals("removeuser")){ //If the command is removeuser and the user is permitted user then call RemoveUser method. if(users.isuser(shouter)){ this.removeuser(param1,param2,sender); else{ send(sender + ", " + login + ", " + hostname + " et ole " + "sallittu käyttäjä poistamaan toista käyttäjää."); else if(word.equals("help")){ //If the command is help then call Help method. this.help(param1); //In other cases the command is not known else{
"!"+ word + " ei ole olemassa oleva komento. " + "Katso komennolla!help olemassa olevat komennot."; String fault = send(fault); palvelu ei ole saatavilla."); käynnistetty."); else{ else{ send("coffee Maker send("coffee Maker palvelua ei ole / Sends message that is given by parameters to the channel where CoffeeBot is @param message message to be sent / public void send(string message){ sendmessage(channel, message); / Coffee order. Method sends Coffee order to Coffee Maker bundle in the correct form. If the parameters are in correct form and inside correct boundaries then the coffee order is made. @param param1 The amount of cups to be boiled @param param2 The strength of the coffee to be boiled @param name The name of the CoffeeBotin @param login The IRC-login of the orderer @param hostname The IRC-hostname of the orderer / public void OrderCoffee(String param1, String param2, String name, String login, String hostname){ int cups = 0; //The amount of cups ordered int strength = 0; //the strength of the coffee ordered int cupsll = 1; //lower boundary of the cups to be ordered, set this to <0 if U dont want CoffeeBots boundaries to be in effect. int cupsul = 10; //upper boundary of the cups to be ordered, set this to >9999 if U dont want CoffeeBots boundaries to be in effect. int strengthll = 50; //lower boundary of the strength of the coffee order, set this to <0 if U dont want CoffeeBots boundaries to be in effect. int strengthul = 150; //lower boundary of the strength of the coffee order, set this to >9999 if U dont want CoffeeBots boundaries to be in effect. String cupsulstring = Integer.toString(cupsUL); //Changes the amounts upper boundary to string form. String cupsllstring = Integer.toString(cupsLL); //Changes the amounts lower boundary to string form. String strengthulstring = Integer.toString(strengthUL); //changes the strengths upper boundary to string form.
String strengthllstring = Integer.toString(strengthLL); //changes the strengths lower boundary to string form. try{ //changes the amount and strength to string form. cups = Integer.parseInt(param1); strength = Integer.parseInt(param2); catch (NumberFormatException e){ send(login + " komento ei ollut oikein. Selviittääksesi kuinka sen tulis olla " + "kirjoita kanavalle komento!help."); return; if(cups>=cupsll&&cups<=cupsul){ //Check that the amounth is inside the boundaries. if(strength>=strengthll&&strength<=strengthul){ //Check that the strength is inside the boundaries. try{ cservice.ordercoffee(cups, strength, this.getname(), login, hostname); //tilataan kahvia! catch (CoffeeException e){ send(login +" order " + e.getmessage()); else{ send(login + " vahvuus ei ollut rajoissa " + strengthllstring + " - " + strengthulstring + "."); else{ send(login + " määrä ei ollut rajoissa " + cupsllstring + " - " + cupsulstring + "."); / Method counts the time that have past since the last finished coffee making and send the time to the channel. / public void Last(){ long now = System.currentTimeMillis()/1000; long since = now - cservice.getlastcoffeereadytimestamp()/1000; long longh = since/3600; long jh = since%3600; long longmin = jh/60; long jmin = jh%60; long longsec = jmin; int h = (int)longh; int min = (int)longmin; int sec = (int)longsec; String LCRT = "0"; LCRT = "Viimeisin keitto valmistui " + Integer.toString(h) + " tuntia" + Integer.toString(min) + " minuuttia " + Integer.toString(sec) + " sekunttia sitten."; send(lcrt);
/ Method counts how long the Coffee Maker bundle has been on and send the time to the channel. / public void cmonline(){ long longut = cservice.getuptime()/1000; long longh = longut/3600; long jh = longut%3600; long longmin = jh/60; long jmin = jh%60; long longsec = jmin; int h = (int)longh; int min = (int)longmin; int sec = (int)longsec; String UT = ""; UT = "Coffee Maker palvelu on ollut saatavilla " + Integer.toString(h) + " tuntia " + Integer.toString(min) + " minuuttia " + Integer.toString(sec) + " sekunttia."; send(ut); / Method counts how long the CoffeeBot has been in the channel and sends the time to the channel. / public void BotOnline(){ long now = System.currentTimeMillis()/1000; long since = now - this.gotonline/1000; long longh = since/3600; long jh = since%3600; long longmin = jh/60; long jmin = jh%60; long longsec = jmin; int h = (int)longh; int min = (int)longmin; int sec = (int)longsec; String TIO = ""; TIO = this.getname() + " on ollut kanavalla " + Integer.toString(h) + " tuntia " + Integer.toString(min) + " minuuttia " + Integer.toString(sec) + " sekunttia."; send(tio); / Print to the channel the users that are permitted to use the coffee maker. / public void ListUsers(){ String List = ""; int i = 0; do{ String temp = Users.getCell(i); List = List + temp; List = List + "; ";
i++; while(users.getcell(i)!=null); send(list); / Adds new user with method adduser from class UserList that is build from param1 and param2. @param param1 The Nick of the new user @param param2 The Login of the new user @param sender The Nick of the person that adds the new person. / public void AddUser(String param1, String param2, String sender){ if(param1.equals("") param2.equals("")){ send("komento!adduser " + param1 + " " + param2 + " ei ollut niin kuin sen kuuluisi olla."); else{ String NewUser = param1 + ",n=" + param2; if(users.adduser(newuser)){ send(sender +" added new user " + NewUser + "."); else{ String maxusers = Integer.toString(Users.MaxUsers); send("emme pystyneet lisäämään käyttäjää " + NewUser + ". Joko käyttäjä oli jo olemassa " + "tai käyttäjiä on jo maksimimäärä " + maxusers + "."); / Removes user with method removeuser from class UserList. @param param1 The Nick of the user thats going to be removed. @param param2 The Login of the user thats going to be removed @param sender The Nick of the person that removes the person. / public void RemoveUser(String param1, String param2, String sender){ String RemovedUser = param1 + ",n=" + param2; if(users.removeuser(removeduser)){ send(sender + " poisti käyttäjän " + RemovedUser + "."); else{ send("emme pystyneet poistamaan käyttääjää " + RemovedUser + ". Tarkista komentosi."); / Prints instructions to the channel about the command given in parameters. @param param1 the command that needs instructions. / public void Help(String param1){ String help = ""; if(param1.equals("order")){
help = "!order komennolla voivat sallitut käyttäjät tilata kahvia. " + "Tilaus tulee olla muodossa:!order määrä vahvuus. " + "Esim:!order 10 100."; else if(param1.equals("last")){ help = "!last komennolla voit selvittää kuinka kauan sitten viimeisin kahvinkeitto on valmistunut."; else if(param1.equals("cmonline")){ help = "!cmonline komennolla voit selvittää kuinka kauan Coffee Maker " + "palvelu on ollut saatavilla."; else if(param1.equals("botonline")){ help = "!botonline komennolla voit selvittää kuinka kauan " + this.getname() + " on ollut kanavalla " + this.channel + "."; else if(param1.equals("listusers")){ help = "!listusers komennolla voi selvittää ketkä ovat sallittuja käyttäjiä."; else if(param1.equals("adduser")){ help = "!adduser komennolla voivat sallitut käyttäjät lisätä uusia käyttäjiä. " + "Komento tulee olla muodossa:!adduser nick login."; else if(param1.equals("removeuser")){ help = "!removeuser komennolla voivat sallitut käyttäjät poistaa toisia käyttäjiä. " + "Komento tulee olla muodossa:!removeuser nick login."; else{ help = "Olemassa olevat komennot ovat:!order,!last,!cmonline,!botonline,!listusers, " + "!adduser,!removeuser ja!help. Käyttääksesesi komentoja, kirjoita se kanavalle" + "tarvittavien parametrien kanssa. Saadaksesi lisää tietoja komennoista," + " kirjoita kanavalle!help komento. Esim:!help order."; send(help); / This method is called whenever someone joins a channel which CoffeeBot are on. <p> The implementation of this method in the PircBot abstract class performs no actions and may be overridden as required. Prints well come message to the channel. / public void onjoin(string channel, String sender, String login, String hostname){ if(!sender.equals(this.getname())){ String Join = sender + ", " + login + ", " + hostname + " tervetuloa kanavalle " + this.channel + ". Olen " + this.getname() + ". Minun avulla " + "voit keittää kahvia kahvinkeittimellä joka sijaitsee AS-laitoksella." +
komento!help kanavalle."; " Saadaksesi lisää tietoa komennoista, kirjoita send(join); / Tries to connect to the server and the channel. Method uses PircBots mathods setverbose, connect ja JoinChannel. If the connection dont succeed and its not the first attemption and not reached the maximum attempts it waits the waithing time and tries to connect again. If Nick is allready in use the channel adds running number at the end of the Nick. @param FirstTry is the CoffeeBot trying to connect to the channel for the first time since the bot has been started. @throws IOException if it was not possible to connect to the server. @throws IrcException if the server would not let us join it. @throws NickAlreadyInUseException if our nick is already in use on the server. / public void TryConnect(boolean FirstTry){ try { this.try++; this.setverbose(true); this.connect(server); this.joinchannel(channel); this.try = 0; this.gotonline = System.currentTimeMillis(); Nicks = 0; String Join = "Terve! Olen " + this.getname() + ". Minun avulla " + "voit keittää kahvia kahvinkeittimellä joka sijaitsee AS-laitoksella." + " Saadaksesi lisää tietoa komennoista, kirjoita komento!help kanavalle."; send(join); catch (NickAlreadyInUseException e) { e.printstacktrace(); Nicks++; String NewName = OrginalName + Integer.toString(Nicks); this.setname(newname); TryConnect(FirstTry); catch (IOException e) { e.printstacktrace(); catch (IrcException e) { e.printstacktrace(); if(!this.isconnected()&&!firsttry){ if(try<=trylimit){ System.out.println(this.getName() + " couldn't make " +
this.waittime/1000 +"sec " + again."); times " + down. " + else{ in available."); "a connection. Bot will wait " + "and going to try connection this.waitbeforeconnect(this.waittime); TryConnect(false); System.out.println(this.getName() + " attempted too many BA.StopUsingBundle(); "to get connection and shut him self "Find out why the connection was not attempt. / Wait time that the CoffeeBot waits until it makes new connection @param msecs odotusaika. / public void WaitBeforeConnect(long msecs){ long start = new Date().getTime(); long cur = start; while(cur - start < msecs){ cur = new Date().getTime(); / This method carries out the actions to be performed when the CoffeeBot gets disconnected. This may happen if the CoffeeBot quits from the server, or if the connection is unexpectedly lost. <p> Disconnection from the IRC server is detected immediately if either we or the server close the connection normally. If the connection to the server is lost, but neither we nor the server have explicitly closed the connection, then it may take a few minutes to detect (this is commonly referred to as a "ping timeout"). <p> If the connection is lost the its tried to put back with method TryConnect. <p> The implementation of this method in the PircBot abstract class performs no actions and may be overridden as required. / public void ondisconnect(){ System.out.println(this.getName() + " lost connection and try establish it again."); this.tryconnect(false); / Method is used to create new userlist for the CoffeeBot. @return true if the list creation succeed. /
public boolean getuserslist(){ boolean ListOK = true; this.users = new UsersList(); if(!this.users.readfromfile()){ System.out.println("Userlist does not exist or it is empty. Make sure that list exist and is not empty and try to start the Bot again."); ListOK = false; return ListOK;