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
@nicksare added to the channel$channel, this happens for example when someone JOINs a channel or when you get a RPL_NAMREPLY (see RFC1459).$msgis the IRC message hash that as returned byparse_irc_msg. - channel_remove => $msg, $channel, @nicks
-
Emitted when
@nicksare removed from the channel$channel, happens for example when they PART, QUIT or get KICKed.$msgis the IRC message hash that as returned byparse_irc_msgor 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_nickto$new_nickgive the application a chance to quickly analyze what channels were affected.$is_myselfis 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.
$destis the nickname on the$channelwho's mode was updated. - channel_topic => $channel, $topic, $who
-
This is emitted when the topic for a channel is discovered.
$channelis the channel for which$topicis the current topic now. Which is set by$who.$whomight be undefined when it's not known who set the channel topic. - ident_change => $nick, $ident
-
Whenever the user and host of
$nickhas been determined or a change happened this event is emitted. - join => $nick, $channel, $is_myself
-
Emitted when
$nickenters the channel$channelby JOINing.$is_myselfis true if yourself are the one who JOINs. - part => $nick, $channel, $is_myself, $msg
-
Emitted when
$nickPARTs the channel$channel.$is_myselfis true if yourself are the one who PARTs.$msgis the PART message. - kick => $kicked_nick, $channel, $is_myself, $msg, $kicker_nick
-
Emitted when
$kicked_nickis KICKed from the channel$channelby$kicker_nick.$is_myselfis true if yourself are the one who got KICKed.$msgis the KICK message. - nick_change => $old_nick, $new_nick, $is_myself
-
Emitted when
$old_nickis renamed to$new_nick.$is_myselfis 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.
$boolis true if you are now away, or false/undef if you are not away anymore.You can change your away status by emitting the
AWAYIRC 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.
$tagis the CTCP message tag. (eg. "PING", "VERSION", ...).$msgis the CTCP message and$typeis either "NOTICE" or "PRIVMSG".$srcis the source nick the message came from.$targetis 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.
$tagis the CTCP message tag (in lower case). (eg. "ping", "version", ...).$msgis the CTCP message and$typeis either "NOTICE" or "PRIVMSG".$srcis the source nick the message came from.$targetis 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.
$idis the DCC connection ID.$destand$typeare the destination and type of the DCC request.$local_ipis the$local_ipargument passed tostart_dccor the IP the socket is bound to.$local_portis 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.
$idis the DCC connection ID,$srcis his nickname,$typeis the DCC type in lower cases (eg. 'chat').$argis the DCC type argument.$addris the IP address we can reach him at in ASCII encoded human readable form (eg. something like "127.0.0.1"). And$portis the TCP port we have to connect to.To answer to his request you can just call
dcc_acceptwith the$id. - dcc_accepted => $id, $type, $hdl
-
When the locally listening DCC socket has received a connection this event is emitted.
$idand$typeare the DCC connection ID and type of the DCC request.$hdlis 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_acceptthis event is emitted.$idis the DCC connection ID.$typeis the dcc type in lower case.$hdlis the AnyEvent::Handle object of the connection (see alsodcc_acceptedabove). - dcc_close => $id, $type, $reason
-
This event is emitted whenever a DCC connection is terminated.
$idand$typeare the DCC connection ID and type of the DCC request.$reasonis 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.
$idis the DCC connection ID we received the message on. And$msgis the message he sent us. - quit => $nick, $msg
-
Emitted when the nickname
$nickQUITs with the message$msg. - publicmsg => $channel, $ircmsg
-
Emitted for NOTICE and PRIVMSG where the target
$channelis a channel.$ircmsgis the original IRC message hash like it is returned byparse_irc_msg.The last parameter of the
$ircmsgwill 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.$ircmsgis the original IRC message hash like it is returned byparse_irc_msg.The last parameter of the
$ircmsgwill have all CTCP messages stripped off. - error => $code, $message, $ircmsg
-
Emitted when any error occurs.
$codeis the 3 digit error id string from RFC 1459 or the string 'ERROR'.$messageis a description of the error.$ircmsgis the complete error irc message.You may use AnyEvent::IRC::Util::rfc_code_to_name to convert
$codeto 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
connectonce it disconnected.NOTE: You are free to use the hash member
heapto store any associated data with this object. For example retry timers or anything else.%argsmay contain these options:- send_initial_whois => $bool
-
If this option is enabled an initial
WHOIScommand is sent to your own NICKNAME to determine your own ident. See also the methodnick_ident. This is necessary to ensure that the information about your own nickname is available as early as possible for thesend_long_messagemethod.$boolisfalseby default.
- $cl->connect ($host, $port)
- $cl->connect ($host, $port, $info)
-
This method does the same as the
connectmethod of AnyEvent::Connection, but if the$infoparameter is passed it will automatically register with the IRC server upon connect for you, and you won't have to call theregistermethod yourself. If$infoonly contains the timeout value it will not automatically connect, this way you can pass a custom connect timeout value without having to register.The keys of the hash reference you can pass in
$infoare:nick - the nickname you want to register as user - your username real - your realname password - the server password timeout - the TCP connect timeoutAll keys, except
nickare optional. - $cl->register ($nick, $user, $real, $server_pass)
-
Sends the IRC registration commands NICK and USER. If
$server_passis passed also a PASS command is generated.NOTE: If you passed the nick, user, etc. already to the
connectmethod 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.
$callbackis called with the current nickname as first argument when a ERR_NICKNAMEINUSE or ERR_UNAVAILRESOURCE error occurs on login. The return value of$callbackwill then be used to change the nickname.If
$callbackis not defined the default nick change callback will be used again.The default callback appends '_' to the end of the nickname supplied in the
registerroutine.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
registeras a nick-collision might happened on login. - $cl->is_my_nick ($string)
-
This returns true if
$stringis 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
$channelparameter: 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 fromnick_modes ()).If the
$channelparameter 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
$nickon$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 theregisteredevent 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 thebefore_registeredevent, thesend_srvqueue 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, likesend_srvonly that it will queue the messages if it hasn't joined the channel$channelyet. The queued messages will be send once the connection successfully JOINed the$channel.$channelwill 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_queueto 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.
$cmdand@paramsare the IRC command and it's first parameters, except the last one: the$msg.$msgcan be a Unicode string, which will be encoded in$encodingbefore sending.If you want to send a CTCP message you can encode it in the
$cmdby 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");$encodingcan 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_identfor your own nick is necessary to compute this. To ensure best performance as possible use thesend_initial_whoisoption 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_messagebefore theWHOISreply tosend_initial_whoisarrived.To be on the safest side you might want to wait until that initial
WHOISreply 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
$intervalseconds. If no PONG was received from the server until the next interval the connection will be terminated or the callback in$cbwill be called.(
$cbwill 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
registeredevent). - $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
$stringis 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
$nickif the information is available. If the nick's ident hasn't been seen yet, undef is returned.NOTE: If you want to rely on the
nick_identof your own nick you should make sure to enable thesend_initial_whoisoption 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_commandvia PRIVMSG,@msgwill be used as argument to theencode_ctcpfunction of the AnyEvent::IRC::Util package. The replies will be sent with the NOTICE IRC command.If
$coderefwas given and is a code reference, it will called each time a$ctcp_commandis received, this is useful for eg. CTCP PING reply generation. The arguments will be the same arguments that thectcpevent callbacks get. (See alsoctcpevent description above). The return value of the called subroutine should be a list of arguments forencode_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
$destof type$type. It will setup a listening TCP socket on$local_port, or a random port if$local_portis undefined.$local_ipis 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_ipwill probably be something like "0.0.0.0". It is always advisable to set$local_ipto a (from the "outside", what ever that might be) reachable IP Address.$timeoutis 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_readyevent is emitted. When the receiver connects to the socket thedcc_acceptedevent is emitted. And whenever a dcc connection is closed thedcc_closeevent is emitted.For canceling the DCC offer or closing the connection see
dcc_disconnectbelow.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_chatordcc_handle. - $cl->dcc_disconnect ($id, $reason)
-
In case you want to withdraw a DCC offer sent by
start_dccor close a DCC connection you call this function.$idis the DCC connection ID.$reasonshould be a human readable reason why you ended the dcc offer, but it's only used for local logging purposes (seedcc_closeevent). - $cl->dcc_accept ($id, $timeout)
-
This will accept an incoming DCC request as received by the
dcc_requestevent. Thedcc_connectedevent will be emitted when we successfully connected. And thedcc_closeevent when the connection was disconnected.$timeoutis 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
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.