SYS-CON MEDIA Authors: Yeshim Deniz, William Schmarzo, Elizabeth White, Roger Strukhoff, Zakia Bouachraoui

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)

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.

Latest Stories
After years of investments and acquisitions, CloudBlue was created with the goal of building the world's only hyperscale digital platform with an increasingly infinite ecosystem and proven go-to-market services. The result? An unmatched platform that helps customers streamline cloud operations, save time and money, and revolutionize their businesses overnight. Today, the platform operates in more than 45 countries and powers more than 200 of the world's largest cloud marketplaces, managing mo...
Trend Micro Incorporated, a global leader in cybersecurity solutions, helps to make the world safe for exchanging digital information. Our innovative solutions for consumers, businesses, and governments provide layered security for data centers, cloud workloads, networks, and endpoints. All our products work together to seamlessly share threat intelligence and provide a connected threat defense with centralized visibility and investigation, enabling better, faster protection. With more than 6,00...
Industry after industry is under siege as companies embrace digital transformation (DX) to disrupt existing business models and disintermediate their competitor’s customer relationships. But what do we mean by “Digital Transformation”? The coupling of granular, real-time data (e.g., smartphones, connected devices, smart appliances, wearables, mobile commerce, video surveillance) with modern technologies (e.g., cloud native apps, big data architectures, hyper-converged technologies, artificial in...
Tapping into blockchain revolution early enough translates into a substantial business competitiveness advantage. Codete comprehensively develops custom, blockchain-based business solutions, founded on the most advanced cryptographic innovations, and striking a balance point between complexity of the technologies used in quickly-changing stack building, business impact, and cost-effectiveness. Codete researches and provides business consultancy in the field of single most thrilling innovative te...
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (, a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and Bi...
The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get tailored market studies; and more.
Take advantage of autoscaling, and high availability for Kubernetes with no worry about infrastructure. Be the Rockstar and avoid all the hurdles of deploying Kubernetes. So Why not take Heat and automate the setup of your Kubernetes cluster? Why not give project owners a Heat Stack to deploy Kubernetes whenever they want to? Hoping to share how anyone can use Heat to deploy Kubernetes on OpenStack and customize to their liking. This is a tried and true method that I've used on my OpenSta...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
CloudEXPO has been the M&A capital for Cloud companies for more than a decade with memorable acquisition news stories which came out of CloudEXPO expo floor. DevOpsSUMMIT New York faculty member Greg Bledsoe shared his views on IBM's Red Hat acquisition live from NASDAQ floor. Acquisition news was announced during CloudEXPO New York which took place November 12-13, 2019 in New York City.
Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
When you're operating multiple services in production, building out forensics tools such as monitoring and observability becomes essential. Unfortunately, it is a real challenge balancing priorities between building new features and tools to help pinpoint root causes. Linkerd provides many of the tools you need to tame the chaos of operating microservices in a cloud native world. Because Linkerd is a transparent proxy that runs alongside your application, there are no code changes required. I...
In his session at 23rd International CloudEXPO, Raju Shreewastava, founder of Big Data Trunk, will provide a fun and simple way to introduce Machine Leaning to anyone and everyone. Together we will solve a machine learning problem and find an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (, a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/busine...
ShieldX's CEO and Founder, Ratinder Ahuja, believes that traditional security solutions are not designed to be effective in the cloud. The role of Data Loss Prevention must evolve in order to combat the challenges of changing infrastructure associated with modernized cloud environments. Ratinder will call out the notion that security processes and controls must be equally dynamic and able to adapt for the cloud. Utilizing four key factors of automation, enterprises can remediate issues and impro...
ShieldX's CEO and Founder, Ratinder Ahuja, believes that traditional security solutions are not designed to be effective in the cloud. The role of Data Loss Prevention must evolve in order to combat the challenges of changing infrastructure associated with modernized cloud environments. Ratinder will call out the notion that security processes and controls must be equally dynamic and able to adapt for the cloud. Utilizing four key factors of automation, enterprises can remediate issues and impro...