IRC is still cool, so let’s build a bot

Sending message over IRC using PHP

Today, we will tackle the problem of creating a chat bot capable of sending messages to an IRC channel using PHP. Despite what I was initially thinking, working with IRC is actually easy, simple and fun as everything you do from an IRC client can easily be done by typing obscure command in a telnet session. As such, using a library for such a simple task is both overkill and cumbersome.

The reason I’ve undertook this mini project was 2 fold:

  1. Feed my IRC chanels with interesting events I want to subscribe to using Zapier. Because Zapier doesn’t integrate with IRC, using a third party script is the perfect workaround, cheap and 100% functional.
  2. Leverage webhook coming from different platforms, see the hooks for a project I manage:

I’ve gone with PHP for this mini project as I wanted minimal maintenance and ease of deployement on an existing stack.

Give me the code

The very good news about IRC is we can do our business straight from telnet which is refreshingly nice. This is what it looks like:

telnet chat.freenode.net 6667
# and then type the commands:
USER hal9000 * * :HAL 9000!
NICK hal9000
JOIN #lounge
PRIVMSG #lounge :Hello world!
QUIT

The sending function is nothing more than what we just did over telnet but done in PHP:

<?php

function send($params, $message){  
  $socket = @fsockopen($params["server"], $params["port"]);
  if(!$socket){
    return "NO_SOCKET";
  }
  socket_set_timeout($socket, 30);
  fputs($socket, sprintf("USER %s * * :%s\n", $params["nick"], $params["fullname"]));
  fputs($socket, sprintf("NICK %s\n", $params["nick"]));
  fputs($socket, sprintf("JOIN %s\n", $params["channel"]));
  fputs($socket, sprintf("PRIVMSG %s :%s \n", $params["channel"], $message));
  fputs($socket, sprintf("QUIT\n"));

  while ($input = trim(fgets($socket))){
    echo("SOCKET: " . $input. "<br/>");
    flush();
    ob_flush();
  }
  echo("COMPLETED");
}

To make it available on the internet more fancy, I use it that way:

if($_GET("key") !== "I_m_the_super_key"){
  header("HTTP/1.1 401 Unauthorized");
  exit;
}

send(
  Array(
    "server"   => "chat.freenode.net",
    "port"     => 6667,
    "fullname" => "HAL 9000",
    "nick"     => "hal9000",
    "channel"  => "#lounge"
  ), 
  $_GET("message")
);

Now you can trigger the script using curl:

curl -X GET http://localhost/script/irc.php?key=I_m_the_super_key&message=Blip blip!

Tada!!