Web DevCenter
oreilly.comSafari Books Online.Conferences.
MySQL Conference and Expo April 14-17, 2008, Santa Clara, CA

Sponsored Developer Resources

Web Columns
Adobe GoLive
Essential JavaScript
Megnut

Web Topics
All Articles
Browsers
ColdFusion
CSS
Database
Flash
Graphics
HTML/XHTML/DHTML
Scripting Languages
Tools
Weblogs

Atom 1.0 Feed RSS 1.0 Feed RSS 2.0 Feed

Learning Lab






O'Reilly Book Excerpts: IRC Hacks

Hacking IRC, Part 2

Author's note: If you're a hardened IRC addict, you'll no longer have to start up a separate process to perform a mathematical calculation, nor will you have to scramble across your desk to find a real calculator. The answers can lie much closer to home on IRC.

Moderate Hack #61

Perform Feats of Math


Lose your calculator. Evaluate mathematical expressions with a bot that uses the Java Expression Parser.

How many times have you been desperate to find out the answer to a simple sum, only to discover that you can't remember where you left your calculator? One solution could be to fire up a calculator application on your computer, but for IRC users, a solution can be found even closer to home.

Java Expression Parser

The Java Expression Parser (JEP) is an excellent tool for parsing and evaluating mathematical expressions. This is ideal for use by bots, because it can take a string as input, parse it, and evaluate the answer. This hack is based on the 2.24 release, which is available for free at http://www.singularsys.com/jep.

JEP input can contain the usual +, -, *, and / symbols, along with ^ to raise powers. JEP contains a set of standard constants, such as pi, e, and i, and a standard set of functions, such as sqrt, sin, abs, and so on. JEP supports implicit multiplication, where 2pi is automatically interpreted as meaning 2* pi. Expressions like sqrt(-1) will not break JEP, as it can handle complex arithmetic and give answers with both a real and imaginary part.

The Code

This bot will make use of the JEP and PircBot packages. It will respond to any channel messages of the form calcexpression. If it is able to parse the expression correctly, it will give the answer; otherwise, it will say it is unable to do so.

Save the following code as MathBot.java:

import org.jibble.pircbot.*;
import org.nfunk.jep.*;

public class MathBot extends PircBot {
    
    // This JEP object will be used for the calculations.
    private JEP jep;
    
    public MathBot(String name) {
        setName(name);

        // Set up the JEP object's capabilities.
        jep = new JEP( );
        jep.addStandardConstants( );
        jep.addStandardFunctions( );
        jep.setAllowUndeclared(false);
        jep.setImplicitMul(true);
        jep.addComplex( );
    }
    
    public void onMessage(String channel, String sender,
            String login, String hostname, String message) {
    
        message = message.trim( ).toLowerCase( );

        // Check for the "calc" command.
        if (message.startsWith("calc ")) {
            String expression = message.substring(5);
            
            // Default answer.
            String answer = "Unable to parse your input.";
            
            try {
                jep.parseExpression(expression);
                if (!jep.hasError( )) {
                    String real = String.valueOf(jep.getValue( ));
                    String complex = String.valueOf(jep.getComplexValue( ));
                    answer = real;
                    
                    // Remove the decimal point if the number is integral.
                    if (real.endsWith(".0")) {
                        answer = real.substring(0, real.length( ) - 2);
                    }
                    
                    if (!complex.endsWith(" 0.0)")) {
                        answer = "Complex " + complex;
                    }
                }
            }
            catch (Exception e) {
                // Do nothing.
            }
            
            sendMessage(channel, sender + ": " + answer);
        }
        
    }

}

A main method is required to create the bot and tell it to join a channel; we'll call it MathBotMain.java:

public class MathBotMain {
    
    public static void main(String[] args) throws Exception {
        MathBot bot = new MathBot("MathBot");
        bot.setVerbose(true);
        bot.connect("irc.freenode.net");
        bot.joinChannel("#irchacks");
    }
    
}

Running the Hack

Compile the bot:

C:\java\MathBot> javac -classpath jep-2.24.jar;pircbot.jar;. *.java

Run it like so:

C:\java\MathBot> java -classpath jep-2.24.jar;pircbot.jar;. MathBotMain

You can see the bot in action in Figure 9-4.


Figure 9-4. Using MathBot in a channel

Pages: 1, 2, 3

Next Pagearrow