The Code
The random numbers will be generated with
an instance of the Random class in Java. This can be used to generate
a pseudorandom sequence of numbers, which
is more than adequate for a dice-rolling application.
The goal is to create a bot that responds to the
!roll command by rolling a die and displaying the
value.
Create a file called DiceBot.java:
import org.jibble.pircbot.*;
import java.util.Random;
public class DiceBot extends PircBot {
private Random random = new Random( );
public DiceBot(String name) {
setName(name);
}
public void onMessage(String channel, String sender,
String login, String hostname, String message) {
message = message.trim( ).toLowerCase( );
if (message.equals("!roll")) {
sendMessage(channel, "I rolled a " + (random.nextInt(6) + 1));
}
else if (message.equals("!shoot")) {
if (random.nextInt(6) == 0) {
kick(channel, sender, "BANG!");
}
else {
sendMessage(channel, sender + ": click");
}
}
}
}
Notice that another feature has been introduced to the bot: a kind of
Russian roulette game. If a user sends the message
!shoot to the channel, there will be a one in six
chance of the bot kicking him from the channel with the reason,
"BANG!" If the user manages to
escape the bullet, the bot will just send
"click" to the channel.
For the Russian roulette feature to work properly, the bot must have
channel operator status in the appropriate channels. The bot is
capable of running in multiple channels.
A main method is required to tell the bot which server to connect to
and which channel or channels to join. Save the following as
DiceBotMain.java:
public class DiceBotMain {
public static void main(String[] args) throws Exception {
DiceBot bot = new DiceBot("Dice");
bot.setVerbose(true);
bot.connect("irc.freenode.net");
bot.joinChannel("#irchacks");
}
}