NAME

AnyEvent::IRC::Client - A highlevel IRC connection

SYNOPSIS

use AnyEvent;
use AnyEvent::IRC::Client;

my $c = AnyEvent->condvar;

my $timer;
my $con = new AnyEvent::IRC::Client;

$con->reg_cb (connect => sub {
   my ($con, $err) = @_;
   if (defined $err) {
      warn "connect error: $err\n";
      return;
   }
});
$con->reg_cb (registered => sub { print "I'm in!\n"; });
$con->reg_cb (disconnect => sub { print "I'm out!\n"; $c->broadcast });
$con->reg_cb (
   sent => sub {
      my ($con) = @_;

      if ($_[2] eq 'PRIVMSG') {
         print "Sent message!\n";

         $timer = AnyEvent->timer (
            after => 1,
            cb => sub {
               undef $timer;
               $con->disconnect ('done')
            }
         );
      }
   }
);

$con->send_srv (
   PRIVMSG => 'elmex',
   "Hello there I'm the cool AnyEvent::IRC test script!"
);

$con->connect ("localhost", 6667, { nick => 'testbot' });
$c->wait;
$con->disconnect;

DESCRIPTION

AnyEvent::IRC::Client is a (nearly) highlevel client connection, that manages all the stuff that noone wants to implement again and again when handling with IRC. For example it PONGs the server or keeps track of the users on a channel.

This module also implements the ISUPPORT (command 005) extension of the IRC protocol (see http://www.irc.org/tech_docs/005.html) and will enable the NAMESX and UHNAMES extensions when supported by the server.

Also CTCP support is implemented, all CTCP messages will be decoded and events for them will be generated. You can configure auto-replies to certain CTCP commands with the ctcp_auto_reply method, or you can generate the replies yourself.

A NOTE TO CASE MANAGEMENT

The case insensitivity of channel names and nicknames can lead to headaches when dealing with IRC in an automated client which tracks channels and nicknames.

I tried to preserve the case in all channel and nicknames AnyEvent::IRC::Client passes to his user. But in the internal structures I'm using lower case for the channel names.

The returned hash from channel_list for example has the lower case of the joined channels as keys.

But I tried to preserve the case in all events that are emitted. Please keep this in mind when handling the events.

For example a user might joins #TeSt and parts #test later.

EVENTS

The following events are emitted by AnyEvent::IRC::Client. Use reg_cb as described in Object::Event to register to such an event.

registered

Emitted when the connection got successfully registered and the end of the MOTD (IRC command 376 or 422 (No MOTD file found)) was seen, so you can start sending commands and all ISUPPORT/PROTOCTL handshaking has been done.

channel_add => $msg, $channel, @nicks

Emitted when @nicks are added to the channel $channel, this happens for example when someone JOINs a channel or when you get a RPL_NAMREPLY (see RFC1459).

$msg is the IRC message hash that as returned by parse_irc_msg.

channel_remove => $msg, $channel, @nicks

Emitted when @nicks are removed from the channel $channel, happens for example when they PART, QUIT or get KICKed.

$msg is the IRC message hash that as returned by parse_irc_msg or undef if the reason for the removal was a disconnect on our end.

channel_change => $msg, $channel, $old_nick, $new_nick, $is_myself

Emitted when a nickname on a channel changes. This is emitted when a NICK change occurs from $old_nick to $new_nick give the application a chance to quickly analyze what channels were affected. $is_myself is true when yourself was the one who changed the nick.

channel_nickmode_update => $channel, $dest

This event is emitted when the (user) mode (eg. op status) of an occupant of a channel changes. $dest is the nickname on the $channel who's mode was updated.

channel_topic => $channel, $topic, $who

This is emitted when the topic for a channel is discovered. $channel is the channel for which $topic is the current topic now. Which is set by $who. $who might be undefined when it's not known who set the channel topic.

ident_change => $nick, $ident

Whenever the user and host of $nick has been determined or a change happened this event is emitted.

join => $nick, $channel, $is_myself

Emitted when $nick enters the channel $channel by JOINing. $is_myself is true if yourself are the one who JOINs.

part => $nick, $channel, $is_myself, $msg

Emitted when $nick PARTs the channel $channel. $is_myself is true if yourself are the one who PARTs. $msg is the PART message.

kick => $kicked_nick, $channel, $is_myself, $msg, $kicker_nick

Emitted when $kicked_nick is KICKed from the channel $channel by $kicker_nick. $is_myself is true if yourself are the one who got KICKed. $msg is the KICK message.

nick_change => $old_nick, $new_nick, $is_myself

Emitted when $old_nick is renamed to $new_nick. $is_myself is true when yourself was the one who changed the nick.

away_status_change => $bool

Emitted whenever a presence/away status change for you was detected. $bool is true if you are now away, or false/undef if you are not away anymore.

You can change your away status by emitting the AWAY IRC command:

$cl->send_srv (AWAY => "I'm not here right now");

Or reset it:

$cl->send_srv ('AWAY');
ctcp => $src, $target, $tag, $msg, $type

Emitted when a CTCP message was found in either a NOTICE or PRIVMSG message. $tag is the CTCP message tag. (eg. "PING", "VERSION", ...). $msg is the CTCP message and $type is either "NOTICE" or "PRIVMSG".

$src is the source nick the message came from. $target is the target nickname (yours) or the channel the ctcp was sent on.

"ctcp_$tag", => $src, $target, $msg, $type

Emitted when a CTCP message was found in either a NOTICE or PRIVMSG message. $tag is the CTCP message tag (in lower case). (eg. "ping", "version", ...). $msg is the CTCP message and $type is either "NOTICE" or "PRIVMSG".

$src is the source nick the message came from. $target is the target nickname (yours) or the channel the ctcp was sent on.

dcc_ready => $id, $dest, $type, $local_ip, $local_port

Whenever a locally initiated DCC request is made this event is emitted after the listening socket has been setup.

$id is the DCC connection ID.

$dest and $type are the destination and type of the DCC request.

$local_ip is the $local_ip argument passed to start_dcc or the IP the socket is bound to.

$local_port is the TCP port is the socket is listening on.

dcc_request => $id, $src, $type, $arg, $addr, $port

Whenever we receive a DCC offer from someone else this event is emitted. $id is the DCC connection ID, $src is his nickname, $type is the DCC type in lower cases (eg. 'chat'). $arg is the DCC type argument. $addr is the IP address we can reach him at in ASCII encoded human readable form (eg. something like "127.0.0.1"). And $port is the TCP port we have to connect to.

To answer to his request you can just call dcc_accept with the $id.

dcc_accepted => $id, $type, $hdl

When the locally listening DCC socket has received a connection this event is emitted.

$id and $type are the DCC connection ID and type of the DCC request.

$hdl is a pre-configured AnyEvent::Handle object, which you only need to care about in case you want to implement your own DCC protocol. (This event has the on_error and on_eof events pre-configured to cleanup the data structures in this connection).

dcc_connected => $id, $type, $hdl

Whenever we accepted a DCC offer and connected by using dcc_accept this event is emitted. $id is the DCC connection ID. $type is the dcc type in lower case. $hdl is the AnyEvent::Handle object of the connection (see also dcc_accepted above).

dcc_close => $id, $type, $reason

This event is emitted whenever a DCC connection is terminated.

$id and $type are the DCC connection ID and type of the DCC request.

$reason is a human readable string indicating the reason for the end of the DCC request.

dcc_chat_msg => $id, $msg

This event is emitted for a DCC CHAT message. $id is the DCC connection ID we received the message on. And $msg is the message he sent us.

quit => $nick, $msg

Emitted when the nickname $nick QUITs with the message $msg.

publicmsg => $channel, $ircmsg

Emitted for NOTICE and PRIVMSG where the target $channel is a channel. $ircmsg is the original IRC message hash like it is returned by parse_irc_msg.

The last parameter of the $ircmsg will have all CTCP messages stripped off.

privatemsg => $nick, $ircmsg

Emitted for NOTICE and PRIVMSG where the target $nick (most of the time you) is a nick. $ircmsg is the original IRC message hash like it is returned by parse_irc_msg.

The last parameter of the $ircmsg will have all CTCP messages stripped off.

error => $code, $message, $ircmsg

Emitted when any error occurs. $code is the 3 digit error id string from RFC 1459 or the string 'ERROR'. $message is a description of the error. $ircmsg is the complete error irc message.

You may use AnyEvent::IRC::Util::rfc_code_to_name to convert $code to the error name from the RFC 2812. eg.:

rfc_code_to_name ('471') => 'ERR_CHANNELISFULL'

NOTE: This event is also emitted when a 'ERROR' message is received.

debug_send => $command, @params

Is emitted everytime some command is sent.

debug_recv => $ircmsg

Is emitted everytime some command was received.

METHODS

$cl = AnyEvent::IRC::Client->new (%args)

This is the constructor of a AnyEvent::IRC::Client object, which stands logically for a client connected to ONE IRC server. You can reuse it and call connect once it disconnected.

NOTE: You are free to use the hash member heap to store any associated data with this object. For example retry timers or anything else.

%args may contain these options:

send_initial_whois => $bool

If this option is enabled an initial WHOIS command is sent to your own NICKNAME to determine your own ident. See also the method nick_ident. This is necessary to ensure that the information about your own nickname is available as early as possible for the send_long_message method.

$bool is false by default.

$cl->connect ($host, $port)
$cl->connect ($host, $port, $info)

This method does the same as the connect method of AnyEvent::Connection, but if the $info parameter is passed it will automatically register with the IRC server upon connect for you, and you won't have to call the register method yourself.

The keys of the hash reference you can pass in $info are:

nick      - the nickname you want to register as
user      - your username
real      - your realname
password  - the server password
timeout   - the TCP connect timeout

All keys, except nick are optional.

$cl->register ($nick, $user, $real, $server_pass)

Sends the IRC registration commands NICK and USER. If $server_pass is passed also a PASS command is generated.

NOTE: If you passed the nick, user, etc. already to the connect method you won't need to call this method, as AnyEvent::IRC::Client will do that for you.

$cl->set_nick_change_cb ($callback)

This method lets you modify the nickname renaming mechanism when registering the connection. $callback is called with the current nickname as first argument when a ERR_NICKNAMEINUSE or ERR_UNAVAILRESOURCE error occurs on login. The return value of $callback will then be used to change the nickname.

If $callback is not defined the default nick change callback will be used again.

The default callback appends '_' to the end of the nickname supplied in the register routine.

If the callback returns the same nickname that was given it the connection will be terminated.

$cl->nick ()

Returns the current nickname, under which this connection is registered at the IRC server. It might be different from the one that was passed to register as a nick-collision might happened on login.

$cl->is_my_nick ($string)

This returns true if $string is the nick of ourself.

$cl->registered ()

Returns a true value when the connection has been registered successful and you can send commands.

$cl->channel_list ()
$cl->channel_list ($channel)

Without $channel parameter: This returns a hash reference. The keys are the currently joined channels in lower case. The values are hash references which contain the joined nicks as key (NOT in lower case!) and the nick modes as values (as returned from nick_modes ()).

If the $channel parameter is given it returns the hash reference of the channel occupants or undef if the channel does not exist.

$cl->nick_modes ($channel, $nick)

This returns the mode map of the $nick on $channel. Returns undef if the channel isn't joined or the user is not on it. Returns a hash reference with the modes the user has as keys and 1's as values.

$cl->send_msg (...)

See also AnyEvent::IRC::Connection.

$cl->send_srv ($command, @params)

This function sends an IRC message that is constructed by mk_msg (undef, $command, @params) (see AnyEvent::IRC::Util). If the registered event has NOT yet been emitted the messages are queued until that event is emitted, and then sent to the server.

NOTE: If you stop the registered event (with stop_event, see Object::Event) in a callback registered to the before_registered event, the send_srv queue will NOT be flushed and NOT sent to the server!

This allows you to simply write this:

my $cl = AnyEvent::IRC::Client->new;
$cl->connect ('irc.freenode.net', 6667, { nick => 'testbot' });
$cl->send_srv (PRIVMSG => 'elmex', 'Hi there!');

Instead of:

my $cl = AnyEvent::IRC::Client->new;
$cl->reg_cb (
   registered => sub {
      $cl->send_msg (PRIVMSG => 'elmex', 'Hi there!');
   }
);
$cl->connect ('irc.freenode.net', 6667, { nick => 'testbot' });
$cl->clear_srv_queue ()

Clears the server send queue.

$cl->send_chan ($channel, $command, @params)

This function sends a message (constructed by mk_msg (undef, $command, @params) to the server, like send_srv only that it will queue the messages if it hasn't joined the channel $channel yet. The queued messages will be send once the connection successfully JOINed the $channel.

$channel will be lowercased so that any case that comes from the server matches. (Yes, IRC handles upper and lower case as equal :-(

Be careful with this, there are chances you might not join the channel you wanted to join. You may wanted to join #bla and the server redirects that and sends you that you joined #blubb. You may use clear_chan_queue to remove the queue after some timeout after joining, so that you don't end up with a memory leak.

$cl->clear_chan_queue ($channel)

Clears the channel queue of the channel $channel.

my (@lines) = $cl->send_long_message ($encoding, $overhead, $cmd, @params, $msg)

As IRC only allows 512 byte blocks of messages and sometimes your messages might get longer, you have a problem. This method will solve your problem:

This method can be used to split up long messages into multiple commands.

$cmd and @params are the IRC command and it's first parameters, except the last one: the $msg. $msg can be a Unicode string, which will be encoded in $encoding before sending.

If you want to send a CTCP message you can encode it in the $cmd by appending the CTCP command with a "\001". For example if you want to send a CTCP ACTION you have to give this $cmd:

$cl->send_long_message (undef, 0, "PRIVMSG\001ACTION", "#test", "rofls");

$encoding can be undef if you don't need any recoding of $msg. But in case you want to send Unicode it is necessary to determine where to split a message exactly, to not break the encoding.

Please also note that the nick_ident for your own nick is necessary to compute this. To ensure best performance as possible use the send_initial_whois option if you want to use this method.

But note that this method might not work 100% correct and you might still get at least partially chopped off lines if you use send_long_message before the WHOIS reply to send_initial_whois arrived.

To be on the safest side you might want to wait until that initial WHOIS reply arrived.

The return value of this method is the list of the actually sent lines (but without encoding applied).

$cl->enable_ping ($interval, $cb)

This method enables a periodical ping to the server with an interval of $interval seconds. If no PONG was received from the server until the next interval the connection will be terminated or the callback in $cb will be called.

($cb will have the connection object as it's first argument.)

Make sure you call this method after the connection has been established. (eg. in the callback for the registered event).

$cl->lower_case ($str)

Converts the given string to lowercase according to CASEMAPPING setting given by the IRC server. If none was sent, the default - rfc1459 - will be used.

$cl->eq_str ($str1, $str2)

This function compares two strings, whether they are describing the same IRC entity. They are lower cased by the networks case rules and compared then.

$cl->isupport ()
$cl->isupport ($key)

Provides access to the ISUPPORT variables sent by the IRC server. If $key is given this method will return its value only, otherwise a hashref with all values is returned

$cl->split_nick_mode ($prefixed_nick)

This method splits the $prefix_nick (eg. '+elmex') up into the mode of the user and the nickname.

This method returns 2 values: the mode map and the nickname.

The mode map is a hash reference with the keys being the modes the nick has set and the values being 1.

NOTE: If you feed in a prefixed ident ('@elmex!elmex@fofofof.de') you get 3 values out actually: the mode map, the nickname and the ident, otherwise the 3rd value is undef.

$cl->map_prefix_to_mode ($prefix)

Maps the nick prefix (eg. '@') to the corresponding mode (eg. 'o'). Returns undef if no such prefix exists (on the connected server).

$cl->map_mode_to_prefix ($mode)

Maps the nick mode (eg. 'o') to the corresponding prefix (eg. '@'). Returns undef if no such mode exists (on the connected server).

$cl->available_nick_modes ()

Returns a list of possible modes on this IRC server. (eg. 'o' for op).

$cl->is_channel_name ($string)

This return true if $string is a channel name. It analyzes the prefix of the string (eg. if it is '#') and returns true if it finds a channel prefix. Those prefixes might be server specific, so ISUPPORT is checked for that too.

$cl->nick_ident ($nick)

This method returns the whole ident of the $nick if the informations is available. If the nick's ident hasn't been seen yet, undef is returned.

NOTE: If you want to rely on the nick_ident of your own nick you should make sure to enable the send_initial_whois option in the constructor.

my $bool = $cl->away_status

Returns a true value if you are away or undef if you are not away.

$cl->ctcp_auto_reply ($ctcp_command, @msg)
$cl->ctcp_auto_reply ($ctcp_command, $coderef)

This method installs an auto-reply for the reception of the $ctcp_command via PRIVMSG, @msg will be used as argument to the encode_ctcp function of the AnyEvent::IRC::Util package. The replies will be sent with the NOTICE IRC command.

If $coderef was given and is a code reference, it will called each time a $ctcp_command is received, this is useful for eg. CTCP PING reply generation. The arguments will be the same arguments that the ctcp event callbacks get. (See also ctcp event description above). The return value of the called subroutine should be a list of arguments for encode_ctcp.

Currently you can only configure one auto-reply per $ctcp_command.

Example:

$cl->ctcp_auto_reply ('VERSION', ['VERSION', 'ScriptBla:0.1:Perl']);

$cl->ctcp_auto_reply ('PING', sub {
   my ($cl, $src, $target, $tag, $msg, $type) = @_;
   ['PING', $msg]
});
$cl->dcc_initiate ($dest, $type, $timeout, $local_ip, $local_port)

This function will initiate a DCC TCP connection to $dest of type $type. It will setup a listening TCP socket on $local_port, or a random port if $local_port is undefined. $local_ip is the IP that is being sent to the receiver of the DCC connection. If it is undef the local socket will be bound to 0 (or "::" in case of IPv6) and $local_ip will probably be something like "0.0.0.0". It is always advisable to set $local_ip to a (from the "outside", what ever that might be) reachable IP Address.

$timeout is the time in seconds after which the listening socket will be closed if the receiver didn't connect yet. The default is 300 (5 minutes).

When the local listening socket has been setup the dcc_ready event is emitted. When the receiver connects to the socket the dcc_accepted event is emitted. And whenever a dcc connection is closed the dcc_close event is emitted.

For canceling the DCC offer or closing the connection see dcc_disconnect below.

The return value of this function will be the ID of the initiated DCC connection, which can be used for functions such as dcc_disconnect, send_dcc_chat or dcc_handle.

$cl->dcc_disconnect ($id, $reason)

In case you want to withdraw a DCC offer sent by start_dcc or close a DCC connection you call this function.

$id is the DCC connection ID. $reason should be a human readable reason why you ended the dcc offer, but it's only used for local logging purposes (see dcc_close event).

$cl->dcc_accept ($id, $timeout)

This will accept an incoming DCC request as received by the dcc_request event. The dcc_connected event will be emitted when we successfully connected. And the dcc_close event when the connection was disconnected.

$timeout is the connection try timeout in seconds. The default is 300 (5 minutes).

EXAMPLES

See samples/anyeventirccl and other samples in samples/ for some examples on how to use AnyEvent::IRC::Client.

AUTHOR

Robin Redeker, <elmex@ta-sa.org>

SEE ALSO

AnyEvent::IRC::Connection

RFC 1459 - Internet Relay Chat: Client Protocol

COPYRIGHT & LICENSE

Copyright 2006-2009 Robin Redeker, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.