Click here to close now.


Related Topics: Java IoT

Java IoT: 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 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) {

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("");
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 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 {
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) {
"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);
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 (

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" ( 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
DevOps is about increasing efficiency, but nothing is more inefficient than building the same application twice. However, this is a routine occurrence with enterprise applications that need both a rich desktop web interface and strong mobile support. With recent technological advances from Isomorphic Software and others, rich desktop and tuned mobile experiences can now be created with a single codebase – without compromising functionality, performance or usability. In his session at DevOps Su...
As organizations realize the scope of the Internet of Things, gaining key insights from Big Data, through the use of advanced analytics, becomes crucial. However, IoT also creates the need for petabyte scale storage of data from millions of devices. A new type of Storage is required which seamlessly integrates robust data analytics with massive scale. These storage systems will act as “smart systems” provide in-place analytics that speed discovery and enable businesses to quickly derive meaningf...
Most of the IoT Gateway scenarios involve collecting data from machines/processing and pushing data upstream to cloud for further analytics. The gateway hardware varies from Raspberry Pi to Industrial PCs. The document states the process of allowing deploying polyglot data pipelining software with the clear notion of supporting immutability. In his session at @ThingsExpo, Shashank Jain, a development architect for SAP Labs, discussed the objective, which is to automate the IoT deployment proces...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
In his General Session at 17th Cloud Expo, Bruce Swann, Senior Product Marketing Manager for Adobe Campaign, explored the key ingredients of cross-channel marketing in a digital world. Learn how the Adobe Marketing Cloud can help marketers embrace opportunities for personalized, relevant and real-time customer engagement across offline (direct mail, point of sale, call center) and digital (email, website, SMS, mobile apps, social networks, connected objects).
The buzz continues for cloud, data analytics and the Internet of Things (IoT) and their collective impact across all industries. But a new conversation is emerging - how do companies use industry disruption and technology enablers to lead in markets undergoing change, uncertainty and ambiguity? Organizations of all sizes need to evolve and transform, often under massive pressure, as industry lines blur and merge and traditional business models are assaulted and turned upside down. In this new da...
Countless business models have spawned from the IaaS industry – resell Web hosting, blogs, public cloud, and on and on. With the overwhelming amount of tools available to us, it's sometimes easy to overlook that many of them are just new skins of resources we've had for a long time. In his general session at 17th Cloud Expo, Harold Hannon, Sr. Software Architect at SoftLayer, an IBM Company, broke down what we have to work with, discussed the benefits and pitfalls and how we can best use them ...
In recent years, at least 40% of companies using cloud applications have experienced data loss. One of the best prevention against cloud data loss is backing up your cloud data. In his General Session at 17th Cloud Expo, Sam McIntyre, Partner Enablement Specialist at eFolder, presented how organizations can use eFolder Cloudfinder to automate backups of cloud application data. He also demonstrated how easy it is to search and restore cloud application data using Cloudfinder.
The Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, exploreed the current state of IoT connectivity and review key trends and t...
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessi...
With all the incredible momentum behind the Internet of Things (IoT) industry, it is easy to forget that not a single CEO wakes up and wonders if “my IoT is broken.” What they wonder is if they are making the right decisions to do all they can to increase revenue, decrease costs, and improve customer experience – effectively the same challenges they have always had in growing their business. The exciting thing about the IoT industry is now these decisions can be better, faster, and smarter. Now ...
The cloud. Like a comic book superhero, there seems to be no problem it can’t fix or cost it can’t slash. Yet making the transition is not always easy and production environments are still largely on premise. Taking some practical and sensible steps to reduce risk can also help provide a basis for a successful cloud transition. A plethora of surveys from the likes of IDG and Gartner show that more than 70 percent of enterprises have deployed at least one or more cloud application or workload. Y...
Discussions of cloud computing have evolved in recent years from a focus on specific types of cloud, to a world of hybrid cloud, and to a world dominated by the APIs that make today's multi-cloud environments and hybrid clouds possible. In this Power Panel at 17th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the importance of customers being able to use the specific technologies they need, through environments and ecosystems that expose their APIs to make true ...
Microservices are a very exciting architectural approach that many organizations are looking to as a way to accelerate innovation. Microservices promise to allow teams to move away from monolithic "ball of mud" systems, but the reality is that, in the vast majority of organizations, different projects and technologies will continue to be developed at different speeds. How to handle the dependencies between these disparate systems with different iteration cycles? Consider the "canoncial problem"...
Too often with compelling new technologies market participants become overly enamored with that attractiveness of the technology and neglect underlying business drivers. This tendency, what some call the “newest shiny object syndrome” is understandable given that virtually all of us are heavily engaged in technology. But it is also mistaken. Without concrete business cases driving its deployment, IoT, like many other technologies before it, will fade into obscurity.