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
#62
An Artificial Intelligence Bot
Use the JMegaHal package in a PircBot-based IRC bot that learns from and chats with other users
The Code
[Discuss (0) | Link to this hack]

The Code

In this hack, we use the JMegaHal package to learn sentences and generate replies. We will then combine it with the PircBot package to create an IRC bot that can learn from other IRC users and hold wacky conversations with them.

Combining JMegaHal and PircBot

Combining JMegaHal and PircBot is very easy. If anybody utters the bot's nickname, it should respond with a randomly generated sentence from the JMegaHal object. All other messages that do not contain the bot's nickname will be used to teach it more sentences. In the following simple implementation, the bot is seeded with a starting sentence in the constructor, so it will always be able to respond with this if it has not learned anything else.

Create a file called JMegaHalBot.java:

import org.jibble.pircbot.*;
import org.jibble.jmegahal.*;

public class JMegaHalBot extends PircBot {
    
    private String name;
    private JMegaHal hal;
    
    public JMegaHalBot(String name) {
        setName(name);
        hal = new JMegaHal( );
        // Add at least one sentence so the bot can always form a reply.
        hal.add("What is the weather like today?");
    }
    
    public void onMessage(String channel, String sender,
            String login, String hostname, String message) {
        
        if (message.toLowerCase( ).indexOf(getNick( ).toLowerCase( )) >= 0) {
            // If the bot's nickname was mentioned, generate a random reply.
            String sentence = hal.getSentence( );
            sendMessage(channel, sentence);
        }
        else {
            // Otherwise, make the bot learn the message.
            hal.add(message);
        }
    }
    
}

Now you just need to create a main method to construct the bot and tell it what nickname to use. The main method will also tell the bot which server to use and which channel to join.

This bot can run in multiple channels, but bear in mind that sentences learned in one channel could end up appearing in other channels.

Create the fileJMegaHalBotMain.java:

public class JMegaHalBotMain {
    
    public static void main(String[] args) throws Exception {
        JMegaHalBot bot = new JMegaHalBot("Chatty");
        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.