O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
IRC Hacks
By Paul Mutton
July 2004
More Info

HACK
#58
A DiceBot
If you're an adventure gamer who likes to use IRC, make your own bot to roll the dice for you and your friends
The Code
[Discuss (0) | Link to this hack]

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");
    }
    
}


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.