SYS-CON MEDIA Authors: Xenia von Wedel, Peter Silva, Glenn Rossman, Ava Smith, Elizabeth White

Related Topics: Java

Java: Article

PircBot 1.2.5 Java IRC API

Have Fun with Java

Internet Relay Chat (IRC) is a system that allows groups of people to collaborate and chat from anywhere in the world. Clearly defined by several RFC documents, it's arguably the most standard real-time chat system currently in use. An IRC network consists of a set of servers that people can use to connect to IRC. Typically each network is comprised of several servers to help increase the performance and resilience of the system.

In addition to being able to send messages directly from one user to another, IRC users can join a set of channels, which are analogous to rooms. Each channel has a unique name and is usually inhabited by users with a common interest. These users may participate in the shared discussions.

Since its introduction by Jarkko Oikarinen in 1988, IRC has steadily grown in popularity and currently has more than a million users worldwide at any one moment. The IRC protocol was clearly defined five years later in RFC 1459, making the system more accessible. As a result of this, there are now many client programs that allow users to connect to an IRC network. Some of these client programs are called bots, a term commonly used to describe an automated IRC client (bot is a contraction of robot).

PircBot is a Java framework for writing IRC clients quickly and easily. It has an event-driven architecture to handle common IRC events, flood protection, DCC resuming, ident, and more. Its comprehensive log file format is suitable for use with programs that generate channel statistics for communities. PircBot can be used to create standalone IRC bots and clients, or be rapidly incorporated into any existing Java program, adding useful functionality while avoiding the need to reinvent the wheel. It can also play an important role in education by making it fun to learn Java. Several unique ideas for both research and plain fun have been implemented using the PircBot package.

Creating your first IRC bot with the PircBot framework takes only a couple of minutes. Simply download PircBot and its documentation from www.jibble.org/pircbot.php and import the org.jibble.pircbot package in the classes that will be using it. This package contains an abstract class named PircBot, which implements common IRC functionality and leaves the rest up to you. Several other classes in the package allow easy access to more advanced features, such as file transfers. Writing a bot is a simple case of extending the abstract PircBot class.

import org.jibble.pircbot.*;

public class MyBot extends PircBot {

public MyBot(String name) {
this.setName(name);
}

}
All methods in the PircBot class are fully detailed in the supplied Javadoc documentation, with examples of usage where appropriate. The first methods that you're likely to use are the connect methods, which allow you to connect to an IRC server (with an option to specify the port number or a password to join password-protected servers). Another prominent method is the sendMessage method, which lets you send messages to other users or channels.

After connecting to an IRC server, users typically join one or more channels, each of which contains a set of users. Messages sent to a channel can only be seen by those in that channel. PircBot automatically monitors the channels and users that it has seen, so it's possible to discover which channels your bot is in and, more usefully, who is in each of those channels. This provides important functionality for channel management, where a bot may be responsible for guarding a particular channel against misuse from spamming or some other abuse. Channel management with PircBot is easy, as it becomes trivial to monitor topic and mode changes or even grant operator status to other users.

1 MyBot bot = new MyBot("Billy");
2 bot.setVerbose(true);
3 bot.connect("irc.freenode.net");
4 bot.joinChannel("#bots");
5 bot.sendMessage("#bots", "Hello!");
Having created the MyBot class, it's not too hard to get it to join a channel on an IRC server. The preceding code demonstrates how to get the bot to connect to the server irc.freenode.net. The connect method can throw an IOException or IrcException, so you'll need to use a try-catch block here, or allow the exceptions to propagate if appropriate. After the bot has connected to the server, it will join the channel #bots and send a message to all users in that channel. Take note of line 2, where the verbose mode has been activated. This causes all events to and from the server to be logged to the standard output, which is useful for debugging purposes. The destination of this output can be changed by overriding the log method, inherited from the PircBot class.

An "out of the box" feature that's included in PircBot is the ability to create log files by redirecting the default verbose output to a file. Such log files can then be easily processed by tools like pisg (Perl IRC Statistics Generator) to generate interesting and often amusing statistics about a channel (see Figure 1).

 

Event-Driven Architecture
As the term "bot" is a contraction of "robot," our IRC bot must be independent of direct human control and able to think for itself. IRC bots usually behave semi-autonomously, performing tasks when certain events occur, or responding to commands supplied by authorized users. PircBot allows you to detect events as and when they happen by overriding the appropriate method. All event-driven methods in PircBot have names that begin with "on". For example, overriding the onDisconnect method enables us to know when our bot has been disconnected from the IRC server so we can perform remedial actions. The following code shows this event-driven method being overridden.

public void onDisconnect() {
try {
reconnect();
}
catch (Exception e) {
// Could not reconnect.System.out.println(e);
}
}
Another example of the event-driven behavior of PircBot shows how to welcome new users to a channel. When a user joins a channel, PircBot calls its onJoin method. This method doesn't do anything unless you explicitly override it in a subclass. The following code shows how you would use the sendMessage method to publicly welcome newcomers to a channel.

public void onJoin(String channel,
String sender,
String login,
String hostname) {
sendMessage(channel,
"Hi, " + sender + "!");
}
To further enhance the functionality of MyBot, we can make it respond to some simple commands from users. Some care is required when parsing messages from other users, as they may include special characters that are used to render colors and other formatting. These spurious characters can be removed by using the helper methods in the Colors class, leaving just the plain text. The Colors class also allows you to format text using a selection of colors and formatting attributes, including bold, underline, and italic, although the appearance of such formatting will depend on the IRC client you are using to view the channel.

The java.util.regex package is ideal for parsing commands from other users for keywords and their arguments. However, PircBot is compatible with JRE 1.1.8, so be careful which other classes you make use of if you intend to develop an applet or client for small PDA devices where it is essential to restrict yourself to the classes available in Java 1.1.

Most IRC servers impose restrictions on how rapidly data can be sent. The server often disconnects clients if they attempt to send too much data in one go. PircBot provides a solution to this problem by enqueuing all outgoing messages, so single messages are sent as soon as possible, with a minimum delay between each subsequent message. The length of the delay can be set by calling the setMessageDelay method.

Sending messages to a user through a network of IRC servers imposes the aforementioned delays; however, another way around this problem is to make use of the DCC (Direct Client to Client) protocol. A DCC request is made via the IRC server as usual, but it asks the recipient to connect directly to your machine to carry out further actions. PircBot supports DCC CHAT, which allows a pair of clients to chat to each other over a direct TCP connection, bypassing the IRC server. DCC SEND is also supported, which allows PircBot to send and receive files.

File file = new File("./music.mp3");
DccFileTransfer t = dccSendFile(file,
"Dave", 120000);
t.setPacketDelay(100);
When PircBot requests to send a file to another client, the recipient can accept the file transfer by connecting directly to the PircBot and downloading the file; so it's important to ensure that there will be no problems posed by NAT or a firewall. The recipient can also choose to resume the download if he or she already has part of the file. The timeout value of 120000 in the above code is the number of milliseconds to wait for the user to accept the request, after which the server socket will close and the user will lose the chance to download the file.

Each file transfer is represented by a DccFileTransfer object. This class allows you to monitor the progress of a file transfer and throttle the speed of the connection if required. Files are sent according to the IRC RFC documentation, that is, in 1KB chunks with acknowledgments. Each DccFile Transfer object allows you to include a delay between each "chunk" or "packet." The previous code sample shows a delay of 100 milliseconds being set between each packet, limiting the speed of the transfer to a maximum of 10KB/sec. PircBot can also receive file transfers from other clients. Resuming is supported in both directions, so handling large files is not so problematic on unreliable connections.

Most IRC servers try to establish your identity by contacting the ident server on the machine that you are connecting from. Not everybody runs an ident server, particularly Windows users. A small number of IRC servers will actually refuse to accept connections from clients if they can't find an ident server. PircBot gives you the option of running a "fake" ident server just to appease these types of IRC servers. The ident server is shut down as soon as it has been used.

The PircBot class contains a large number of methods to support and process the IRC protocol as transparently as possible. Some IRC servers implement additional functionality that is not specified in any of the IRC RFC documents. In these circumstances, you'll still be able to make use of the undocumented features by sending raw lines to the server with the sendRawLine method (this method also bypasses the outgoing message queue, which is sometimes useful). You can also handle undocumented events received from the server as they'll be sent to the onUnknown method if they're not recognized by PircBot as valid commands.

Many people ask (without thinking) whether PircBot supports multiple servers. The answer is yes, of course. This is achieved simply by creating a new instance of PircBot for each server that you wish to connect to. A controller class should be used to maintain a collection of PircBot objects, if they're required to interact with each other. Interesting things can be achieved with multiple server connectivity, such as Steve Jolly's bridgebot. This uses the PircBot framework to bridge infobots on two IRC servers, giving two communities access to each other's shared memory.

Adding to Existing Applications
There are many situations where it can be beneficial to spend a little time adding PircBot functionality to an existing application. Say you've used Java to implement a program to stream MP3 audio. Multiple clients can connect to it and listen to the music you're playing. Your listeners start to complain that they don't know what track they're listening to and would like more control over what gets played next. What do you do? An easy solution would be to integrate PircBot into your streaming server so it can announce to an IRC channel what track is being played. It could even be used to parse commands from other users to handle requests for the next track. Adding such extra functionality can be done in a matter of minutes.

PircBot in Education
One of the most appealing aspects of PircBot is that there's so much scope to the applications for which it can be used. This is why it has gained so much interest among undergraduate students who are in the process of learning Java. Students find that PircBot is a good way to apply their learning to an actual application that may even end up doing something useful. There remains the opportunity to explore and understand inheritance, string manipulation, handling exceptions, and so on - but it's a lot more fun this way.

The PircBot Web site has a link to some introductory lecture slides, available in both PDF and Microsoft PowerPoint format. These give a general overview of what IRC is and demonstrate how to make a simple IRC bot, as well as provide a few examples to inspire ideas and discussion. Experience has shown that these are very good at encouraging students to be creative and learn more than the minimal set of information they'll need to pass their Java course.

PircBot Implementations
By providing an IRC framework that's so accessible and easy to use, PircBot has steadily grown in popularity, receiving tens of thousands of downloads. As you would expect, there have been some interesting implementations of PircBot seen along the way.

NewsBot sends messages to all the channels it's in whenever there's a breaking news story. It retrieves the BBC's UK and World RSS feeds every minute and passes on the title of each article as it appears, along with a URL to the full article.

A number of IRC clients have been built using PircBot. TundraIRC was written to fill the gap in suitable IRC clients for Mac OS X. ScreenIRC is another IRC client that implements PircBot and is designed to be run permanently on a server. A novel feature is that you can then "attach" to this with a separate program with a graphical interface. This allows you to close the GUI without being disconnected from the IRC server and you can safely reattach at a later moment to see what you missed during your absence. PircBot Client (PBC) was the first ever IRC client built using the PircBot framework and uses AWT so that it can run on PDAs with JRE 1.1 installed (see Figure 2).

 

iscreamBot is a fine example of an IRC bot being put to good use. It's part of the i-scream distributed central monitoring system and is used to relay system alert information to a public channel on an IRC server. rpgBot is another bot designed to help out players of role-play games online and has a simple plugin system to add new commands. The bot is accompanied by some comprehensive documentation.

TrustBot is part of a project designed to build and maintain a trust network on the semantic Web. TrustBot uses PircBot to act as the current interface to the trust network. It analyzes the network and provides information and inferences about trust between pairs of nodes, ultimately calculating how much one person should trust another. This work was published as "Trust Networks on the Semantic Web" in the proceedings of Cooperative Intelligent Agents, 2003 (http://mindswap.org/papers/Trust.pdf).

PieSpy is a bot that got its name by lurking around in #pie, spying on the channel's inhabitants (see Figure 3). It uses PircBot to silently observe a set of channels, monitoring events to infer a social network. A modified spring embedder graph drawing algorithm is implemented in Java to produce an automatic layout, which is used to visualize the network. The implementation of this bot is described in the paper "Inferring and Visualizing Social Networks on IRC" (www.jibble.org/piespy/). ImageIO is used to write the visualization as a PNG file, or high-quality EPS output can be obtained by using the EpsGraphics2D package.

 

More and more people in the Java scene are starting to keep a blog of their activities. Scot is a bot that can create Weblogs for IRC communities. Scot uses PircBot to interact with the IRC server and stores its data in a MySQL database. PHP provides the Web interface to the database.

ComicBot is another bot that silently observes a channel (see Figure 4). Whenever it sees something that may have been amusing, it quickly generates a cartoon comic strip from one of several templates and places it on the Web. The frequency of output simply depends on how funny the IRC channel is!

 

Last, but not least, is Monty. This bot uses a modified Markov chain model to learn from what other people say and generate automatic responses. Some entertaining quotes from Monty are available on my Web site. This bot was originally written in Perl, but after stumbling across some limitations of the language, it was ported to Java (a move not regretted!). While this conversion was taking place, it became apparent that some parts of Monty would be useful to other people who want to make IRC bots in Java, so PircBot was conceived. PircBot and Monty were developed in tandem, which is perhaps why so many people find PircBot so easy to use - because I wanted it to be easy for me to use!

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
lxj 01/01/04 10:12:44 PM EST

a developer

Latest Stories
The term culture has had a polarizing effect among DevOps supporters. Some propose that culture change is critical for success with DevOps, but are remiss to define culture. Some talk about a DevOps culture but then reference activities that could lead to culture change and there are those that talk about culture change as a set of behaviors that need to be adopted by those in IT. There is no question that businesses successful in adopting a DevOps mindset have seen departmental culture change, ...
High-performing enterprise Software Quality Assurance (SQA) teams validate systems that are ready for use - getting most actively involved as components integrate and form complete systems. These teams catch and report on defects, making sure the customer gets the best software possible. SQA teams have leveraged automation and virtualization to execute more thorough testing in less time - bringing Dev and Ops together, ensuring production readiness. Does the emergence of DevOps mean the end of E...
"Verizon offers public cloud, virtual private cloud as well as private cloud on-premises - many different alternatives. Verizon's deep knowledge in applications and the fact that we are responsible for applications that make call outs to other systems. Those systems and those resources may not be in Verizon Cloud, we understand at the end of the day it's going to be federated," explained Anne Plese, Senior Consultant, Cloud Product Marketing at Verizon Enterprise, in this SYS-CON.tv interview at...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. Acco...
"Cloud consumption is something we envision at Solgenia. That is trying to let the cloud spread to the user as a consumption, as utility computing. We want to allow the people to just pay for what they use, not a subscription model," explained Ermanno Bonifazi, CEO & Founder of Solgenia, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using ...
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series dat...
"For the past 4 years we have been working mainly to export. For the last 3 or 4 years the main market was Russia. In the past year we have been working to expand our footprint in Europe and the United States," explained Andris Gailitis, CEO of DEAC, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps,...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect...
SYS-CON Media announced that Centrify, a provider of unified identity management across cloud, mobile and data center environments that delivers single sign-on (SSO) for users and a simplified identity infrastructure for IT, has launched an ad campaign on Cloud Computing Journal. The ads focus on security: how an organization can successfully control privilege for all of the organization’s identities to mitigate identity-related risk without slowing down the business, and how Centrify provides ...
SAP is delivering break-through innovation combined with fantastic user experience powered by the market-leading in-memory technology, SAP HANA. In his General Session at 15th Cloud Expo, Thorsten Leiduck, VP ISVs & Digital Commerce, SAP, discussed how SAP and partners provide cloud and hybrid cloud solutions as well as real-time Big Data offerings that help companies of all sizes and industries run better. SAP launched an application challenge to award the most innovative SAP HANA and SAP HANA...
"SAP had made a big transition into the cloud as we believe it has significant value for our customers, drives innovation and is easy to consume. When you look at the SAP portfolio, SAP HANA is the underlying platform and it powers all of our platforms and all of our analytics," explained Thorsten Leiduck, VP ISVs & Digital Commerce at SAP, in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"We help companies that are using a lot of Software as a Service. We help companies manage and gain visibility into what people are using inside the company and decide to secure them or use standards to lock down or to embrace the adoption of SaaS inside the company," explained Scott Kriz, Co-founder and CEO of Bitium, in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Ar...