a3nm's blog

irctk -- an IRC toolkit

— updated

There are a lot of language-specific libraries to interact with IRC and write bots, but if you want to do this from the shell, the only option I know of is to use ii. Sadly, ii is based on the idea of setting a connection up and interacting with filesystem objects, which is inconvenient if you just want to hack something together in one line like you do with netcat for TCP connections. This post presents irctk, a C program I wrote using libircclient. irctk connects to a server specified on the CLI and uses its standard input and output to read what it should say and write what it just heard. With irctk, you can do stuff like:

# output your server log events on irc
ssh server tail -f logfile.log | irctk example.com '#dashboard'
# timestamp and log irc messages to a file
irctk example.com '#chan' | awk '{ print strftime("%s"), $0; fflush() }' >file

You can also write programs which interact with their standard input and output and then just lift them to IRC with irctk. An example of this is wikifirc, a tool to filter irc.wikimedia.org on specific pages and users. The general scheme is just:

mkfifo fifo
cat fifo | irctk example.com '#chan' | program > fifo

Or you can just write simple programs directly in bash. As a convenience, irctk has options to filter incoming messages and only keep those which are specifically addressed to him, and it can reply automatically to the person who addressed him on the channel where it was addressed. For example, if you address the following bot like "fingerbot: foobar" or "/msg fingerbot foobar", it will reply with information about user foobar found with the finger command:

cat fifo | irctk -Fr fingerbot@example.com '#chat' |
  while read; do
    finger -s -- "$REPLY" 2>&1 | tail -1
  done >fifo

Here is a funnier (bash-specific) example: a bot to roll dice like "dmbot: 3d42" (thanks, p4bl0!): Fixed the code to avoid modulo bias

cat fifo | irctk -Fr dmbot@example.com '#chat' |
while read line; do
  if grep -E '^[0-9]{1,2}d[1-9][0-9]{0,2}$' <<<"$line" &>/dev/null; then
    D=(${line/d/ })
    for ((i = 0; i < ${D[0]}; i++)); do
      shuf -i1-${D[1]} -n1 | tr '\n' ' '
    echo "format error: must be NdM with N<100 and M<1000"
done >fifo

irctk has a few other features, like support for commands like "/join", "/nick", "/part", etc., to be able to script actions. Installing irctk should be as easy as installing libircclient (by hand, the version packaged in e.g. Debian is not recent enough as of this writing), and then typing:

git clone 'https://a3nm.net/git/irctk'
cd irctk

You can check the README for more information. Comments, suggestions, bug reports and feature requests are welcome at <a3nmNOSPAM@a3nm.net>.

comments welcome at a3nm<REMOVETHIS>@a3nm.net