Welcome!

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 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
Get deep visibility into the performance of your databases and expert advice for performance optimization and tuning. You can't get application performance without database performance. Give everyone on the team a comprehensive view of how every aspect of the system affects performance across SQL database operations, host server and OS, virtualization resources and storage I/O. Quickly find bottlenecks and troubleshoot complex problems.
"Dice has been around for the last 20 years. We have been helping tech professionals find new jobs and career opportunities," explained Manish Dixit, VP of Product and Engineering at Dice, in this SYS-CON.tv interview at 19th Cloud Expo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
An IoT product’s log files speak volumes about what’s happening with your products in the field, pinpointing current and potential issues, and enabling you to predict failures and save millions of dollars in inventory. But until recently, no one knew how to listen. In his session at @ThingsExpo, Dan Gettens, Chief Research Officer at OnProcess, discussed recent research by Massachusetts Institute of Technology and OnProcess Technology, where MIT created a new, breakthrough analytics model for ...
Internet of @ThingsExpo has announced today that Chris Matthieu has been named tech chair of Internet of @ThingsExpo 2017 New York The 7th Internet of @ThingsExpo will take place on June 6-8, 2017, at the Javits Center in New York City, New York. Chris Matthieu is the co-founder and CTO of Octoblu, a revolutionary real-time IoT platform recently acquired by Citrix. Octoblu connects things, systems, people and clouds to a global mesh network allowing users to automate and control design flo...
SYS-CON Events has announced today that Roger Strukhoff has been named conference chair of Cloud Expo and @ThingsExpo 2017 New York. The 20th Cloud Expo and 7th @ThingsExpo will take place on June 6-8, 2017, at the Javits Center in New York City, NY. "The Internet of Things brings trillions of dollars of opportunity to developers and enterprise IT, no matter how you measure it," stated Roger Strukhoff. "More importantly, it leverages the power of devices and the Internet to enable us all to im...
Rapid innovation, changing business landscapes, and new IT demands force businesses to make changes quickly. In the eyes of many, containers are at the brink of becoming a pervasive technology in enterprise IT to accelerate application delivery. In this presentation, attendees learned about the: The transformation of IT to a DevOps, microservices, and container-based architecture What are containers and how DevOps practices can operate in a container-based environment A demonstration of how ...
"At ROHA we develop an app called Catcha. It was developed after we spent a year meeting with, talking to, interacting with senior citizens watching them use their smartphones and talking to them about how they use their smartphones so we could get to know their smartphone behavior," explained Dave Woods, Chief Innovation Officer at ROHA, in this SYS-CON.tv interview at 19th Cloud Expo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
DevOps is being widely accepted (if not fully adopted) as essential in enterprise IT. But as Enterprise DevOps gains maturity, expands scope, and increases velocity, the need for data-driven decisions across teams becomes more acute. DevOps teams in any modern business must wrangle the ‘digital exhaust’ from the delivery toolchain, "pervasive" and "cognitive" computing, APIs and services, mobile devices and applications, the Internet of Things, and now even blockchain. In this power panel at @...
"Venafi has a platform that allows you to manage, centralize and automate the complete life cycle of keys and certificates within the organization," explained Gina Osmond, Sr. Field Marketing Manager at Venafi, in this SYS-CON.tv interview at DevOps at 19th Cloud Expo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Effectively SMBs and government programs must address compounded regulatory compliance requirements. The most recent are Controlled Unclassified Information and the EU's GDPR have Board Level implications. Managing sensitive data protection will likely result in acquisition criteria, demonstration requests and new requirements. Developers, as part of the pre-planning process and the associated supply chain, could benefit from updating their code libraries and design by incorporating changes. In...
"ReadyTalk is an audio and web video conferencing provider. We've really come to embrace WebRTC as the platform for our future of technology," explained Dan Cunningham, CTO of ReadyTalk, in this SYS-CON.tv interview at WebRTC Summit at 19th Cloud Expo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Financial Technology has become a topic of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 20th Cloud Expo at the Javits Center in New York, June 6-8, 2017, will find fresh new content in a new track called FinTech.
Whether your IoT service is connecting cars, homes, appliances, wearable, cameras or other devices, one question hangs in the balance – how do you actually make money from this service? The ability to turn your IoT service into profit requires the ability to create a monetization strategy that is flexible, scalable and working for you in real-time. It must be a transparent, smoothly implemented strategy that all stakeholders – from customers to the board – will be able to understand and comprehe...
Keeping pace with advancements in software delivery processes and tooling is taxing even for the most proficient organizations. Point tools, platforms, open source and the increasing adoption of private and public cloud services requires strong engineering rigor – all in the face of developer demands to use the tools of choice. As Agile has settled in as a mainstream practice, now DevOps has emerged as the next wave to improve software delivery speed and output. To make DevOps work, organization...
"Qosmos has launched L7Viewer, a network traffic analysis tool, so it analyzes all the traffic between the virtual machine and the data center and the virtual machine and the external world," stated Sebastien Synold, Product Line Manager at Qosmos, in this SYS-CON.tv interview at 19th Cloud Expo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.