A Perl script logs chat sessions
Minutes Taker
The IRC (Internet Relay Chat) protocol lets you program bots as automatic helpers. In this month's column, we let a bot log a session and store the results in a database.
At conferences, when supporting open source products, or whenever you need to coordinate a large number of project contributors, IRC is still the number one choice among instant messaging tools. None of its competitors – Yahoo, Microsoft, or the open Google Talk protocol – have been able to send the dinosaur among group communication tools into retirement.
The Bot::BasicBot module, which I introduced in a previous article [2] with a thermal sensor, handles communication between a Perl script and the IRC server so intelligently that programming the bot takes fewer than 10 lines of code. Bot::BasicBot::Pluggable takes this concept a stage further by adding plugin support to your bots so participants in a chat session can send messages to enable them. If a plugin is triggered, it performs the task assigned to it and sends the response back to the chat session.
Desperately Seeking …
The CPAN module has a handful of fully functional sample plugins that you can easily enable with load(). Listing 1 shows an implementation of a script that joins an IRC channel and enables two different plugins.
Listing 1
botstart
The Seen plugin remembers the participants that log on and off and responds to the !seen username command with the time the participant was last online (Figure 1). This query is particularly useful if the user is no longer involved in the chat session. The second plugin enabled by botstart is DNS, which implements a simple interface to the Unix nslookup command and responds to !nslookup hostname commands with the IP address for the specified hostname as returned by the nslookup command-line utility (Figure 2).
The modularly extensible bot even accepts commands to load new plugins from the participants. If you configure the bot with $bot->load('Loader'), any participant can mess around with the bot's loading mechanism. When it receives a !load DNS message, the bot loads the DNS module; !unload DNS disables it again. Of course, this is risky, and although Bot::BasicBot::Pluggable tries to restrict users' options by providing an Auth module, this mechanism is easy to work around, as the documentation admits, and thus not recommended.
Can You Take a Message?
New plugins are easy to code. Bot authors can base new plugin classes on Bot::BasicBot::Pluggable. As you can see in Listing 2, you only need to overload a couple of methods to create a fully functional plugin. The init() method is called by the plugin framework once a script starts to bind the plugin. Because a pointer to the plugin object is passed into init(), it takes this opportunity to initialize its persistent data memory. For this purpose, it uses Cache::Historical from CPAN and stores a reference to it in the plugin's object data hash.
Listing 2
Log.pm
Later on, in the told() method, it picks up the reference again to store conversation snippets that it has captured. Cache::Historical was actually written to handle historical share prices, which it stores along with the date in an SQLite database, but the format is just as useful for chat messages, which are stored with a key (the name of the chat room – or "channel" in IRC lingo) and the current timestamp. The $SQLITE_FILE variable in line 8 of Listing 2 specifies the path to the SQLite file in the filesystem and might need to be converted to an absolute path or modified in some other way to match the local environment.
The help() method is mandatory and returns a short help text to tell the user what the plugin does.
Finally, the told() method in line 30 is called by the plugin framework whenever somebody says something in the chat room. Besides a pointer to the plugin object, told() is given a message hash with the sender ID and message content in the who and body keys. The module then calls the DateTime object's now() method to get the current time as a DateTime object – which is exactly the format in which Cache::Historical expects its timestamps. The time_zone parameter is set to "local" for the now() method to make sure that the timestamp is based in the current time zone. The told() method returns an empty string to the framework to indicate that it is not sending a message back to the chat room. The plugin is only interested in silently logging the conversation.
The script in Listing 3 starts a bot that loads the new log module and then joins a channel on the IRC server. Optionally, you can specify an array of channels that the bot joins at the same time. The load() method in line 23 will find the Log.pm module either in the current directory or in the framework's plugin directory, which is typically /usr/local/lib/perl5/site_perl/5.x/Bot/BasicBot/Pluggable. Log4perl sets the script's logging level to $ERROR in line 8; if you want the script to print the details of incoming messages and how it stored them for debugging purposes, you can change the level to $DEBUG.
Listing 3
logbot
If you want to see what the database content looks like on disk, you can peek behind the storage module's drapes: As you can see in Figure 4, it creates an SQLite database and a matching schema – without any intervention on the part of the bot programmer – and stores each incoming message in one line of a table. The entries are numbered sequentially with IDs and have a timestamp in column two, the chat room in column four, and the message itself in column five. The third column, upd_time, is not really interesting because Cache::Historical uses it for internal purposes. Because the module only provides one field in which to store the value, Log.pm simply bundles the sender and the message into a string, adding a colon and a blank to distinguish the two.
However, this format is not of much interest because Cache::Historical offers a values() method that returns all the messages stored under a specific key (the chat room) in reverse chronological order. Listing 4 shows the implementation, and Figure 5 shows the output from the script.
Listing 4
logdump
Installation
The required modules, Bot::BasicBot:: Pluggable, Cache::Historical, and Log::Log4perl are available from CPAN and installed from the CPAN Shell, which automatically resolves dependencies. In the logbot script, you need to modify the name of the chat room you want to monitor and the IRC server you will use before you launch the bot. The Cache::Historical module automatically sets up the SQLite database and the required schema. Other than modifying the $SQLITE_FILE variable to match the path to the database file, no preparation is required. Now you can eavesdrop on conferences and know what people are talking about behind your back, even while you are presenting! The script doesn't even need to run on the laptop you are using for your talk (which could have WiFi disabled): It can be launched somewhere on the Internet and its results checked at a later time.
Infos
- Listings for this article: ftp://www.linux-magazin.de/pub/listings/magazin/2009/11/Perl
- "How Cool is Perl?" by Michael Schilli, Linux Magazine, April 2006, http://www.linuxpromagazine.com/Issues/2006/65/HOW-COOL-IS-PERL
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
New KDE Slimbook Plasma Available for Preorder
Powered by an AMD Ryzen CPU, the latest KDE Slimbook laptop is powerful enough for local AI tasks.
-
Rhino Linux Announces Latest "Quick Update"
If you prefer your Linux distribution to be of the rolling type, Rhino Linux delivers a beautiful and reliable experience.
-
Plasma Desktop Will Soon Ask for Donations
The next iteration of Plasma has reached the soft feature freeze for the 6.2 version and includes a feature that could be divisive.
-
Linux Market Share Hits New High
For the first time, the Linux market share has reached a new high for desktops, and the trend looks like it will continue.
-
LibreOffice 24.8 Delivers New Features
LibreOffice is often considered the de facto standard office suite for the Linux operating system.
-
Deepin 23 Offers Wayland Support and New AI Tool
Deepin has been considered one of the most beautiful desktop operating systems for a long time and the arrival of version 23 has bolstered that reputation.
-
CachyOS Adds Support for System76's COSMIC Desktop
The August 2024 release of CachyOS includes support for the COSMIC desktop as well as some important bits for video.
-
Linux Foundation Adopts OMI to Foster Ethical LLMs
The Open Model Initiative hopes to create community LLMs that rival proprietary models but avoid restrictive licensing that limits usage.
-
Ubuntu 24.10 to Include the Latest Linux Kernel
Ubuntu users have grown accustomed to their favorite distribution shipping with a kernel that's not quite as up-to-date as other distros but that changes with 24.10.
-
Plasma Desktop 6.1.4 Release Includes Improvements and Bug Fixes
The latest release from the KDE team improves the KWin window and composite managers and plenty of fixes.