POE::C...nt::IRC(3pm)
โจ NAME โจ
POE::Component::IRC โ it's giving fully event-driven IRC client module, bestie. ๐
(That's the one from section 3pm of the Perl docs, aka POE::C...nt::IRC(3pm), aka the whole reason you're here.)
๐ฆ SYNOPSIS ๐ฆ
okay so picture this: a simple Rot13 "encryption" bot. literally the hello-world of irc bots, and honestly? iconic.
# A simple Rot13 'encryption' bot
use strict;
use warnings;
use POE qw(Component::IRC);
my $nickname = 'Flibble' . $$;
my $ircname = 'Flibble the Sailor Bot';
my $server = 'irc.perl.org';
my @channels = ('#Blah', '#Foo', '#Bar');
# We create a new PoCo-IRC object
my $irc = POE::Component::IRC->spawn(
nick => $nickname,
ircname => $ircname,
server => $server,
) or die "Oh noooo! $!";
POE::Session->create(
package_states => [
main => [ qw(_default _start irc_001 irc_public) ],
],
heap => { irc => $irc },
);
$poe_kernel->run();
sub _start {
my $heap = $_[HEAP];
# retrieve our component's object from the heap where we stashed it
my $irc = $heap->{irc};
$irc->yield( register => 'all' );
$irc->yield( connect => { } );
return;
}
sub irc_001 {
my $sender = $_[SENDER];
# Since this is an irc_* event, we can get the component's object by
# accessing the heap of the sender. Then we register and connect to the
# specified server.
my $irc = $sender->get_heap();
print "Connected to ", $irc->server_name(), "\n";
# we join our channels
$irc->yield( join => $_ ) for @channels;
return;
}
sub irc_public {
my ($sender, $who, $where, $what) = @_[SENDER, ARG0 .. ARG2];
my $nick = ( split /!/, $who )[0];
my $channel = $where->[0];
if ( my ($rot13) = $what =~ /^rot13 (.+)/ ) {
$rot13 =~ tr[a-zA-Z][n-za-mN-ZA-M];
$irc->yield( privmsg => $channel => "$nick: $rot13" );
}
return;
}
# We registered for all events, this will produce some debug info.
sub _default {
my ($event, $args) = @_[ARG0 .. $#_];
my @output = ( "$event: " );
for my $arg (@$args) {
if ( ref $arg eq 'ARRAY' ) {
push( @output, '[' . join(', ', @$arg ) . ']' );
}
else {
push ( @output, "'$arg'" );
}
}
print join ' ', @output, "\n";
return;
}
๐ซถ DESCRIPTION ๐ซถ
so POE::Component::IRC is a POE component (like, who'd have guessed, right? ๐ญ) and what it does is act as an easily controllable IRC client for all your other POE components and sessions. no cap. You spin up an IRC component, you tell it which events your session cares about and where to connect, and then it just... sends back interesting IRC events whenever they happen. ๐ฅ You make the client do stuff by sending it events. That's literally it. That's the whole thing. Cool, no? ๐
[forehead kiss of a warning: using this module means you need some actual familiarity with the details of the IRC protocol. I'd advise you to read up on the gory details of RFC 1459 (http://www.faqs.org/rfcs/rfc1459.html) before you get started. Keep the list of server numeric codes handy while you program. And needless to say, you'll also need a good working knowledge of POE, or this document will be of very little use to you. fr fr.]
the POE::Component::IRC distribution has a docs/ folder with a whole collection of salient documentation including the pertinent RFCs. go read it. ๐
so POE::Component::IRC consists of two little guys:
- a
POE::Sessionthat manages the IRC connection and dispatchesirc_prefixed events to interested sessions - an object you can use to access additional information using methods
Sessions register their interest in receiving irc_ events by sending register to the component. You'd usually do this in your _start handler. Your session will keep receiving events until you unregister. And the component will keep hanging around until you tell it not to with shutdown. ๐
The SYNOPSIS demonstrates a fairly basic bot.
See POE::Component::IRC::Cookbook for more examples.
๐ฏ Useful subclasses
shipped right there inside POE::Component::IRC are a bunch of useful subclasses. And because they're subclasses they support all the methods, etc. documented here, plus they have extra methods and quirks documented separately:
POE::Component::IRC::State
gives you all the functionality of POE::Component::IRC but it also tracks IRC state entities such as nicks and channels. the tracking era. ๐
POE::Component::IRC::Qnet
POE::Component::IRC but tweaked for use on the Quakenet IRC network.
POE::Component::IRC::Qnet::State
a tweaked version of POE::Component::IRC::State for use on the Quakenet IRC network.
๐ The Plugin system
as of 3.7, PoCo-IRC sports a plugin system. you can read its documentation over at POE::Component::IRC::Plugin. and bestie listen โ that is not a subclass, it's just a placeholder for documentation! ๐ don't get it twisted.
a number of useful plugins have made their way into the core distribution:
POE::Component::IRC::Plugin::DCC
provides DCC support. Loaded by default.
POE::Component::IRC::Plugin::AutoJoin
keeps you on your favorite channels throughout reconnects and even kicks. clingy in the best way ๐
POE::Component::IRC::Plugin::Connector
glues an irc bot to an IRC network, i.e. it deals with maintaining ircd connections.
POE::Component::IRC::Plugin::BotTraffic
under normal circumstances irc bots do not normally get the msgs and public msgs that they generate themselves. this plugin enables you to handle those events.
POE::Component::IRC::Plugin::BotAddressed
generates irc_bot_addressed / irc_bot_mentioned / irc_bot_mentioned_action events whenever your bot's name comes up in channel discussion. it's giving main character energy, correct. โญ
POE::Component::IRC::Plugin::BotCommand
provides an easy way to handle commands issued to your bot.
POE::Component::IRC::Plugin::Console
see inside the component. see what events are being sent. generate irc commands manually. a TCP based console. ๐
POE::Component::IRC::Plugin::FollowTail
follow the tail of an ever-growing file.
POE::Component::IRC::Plugin::Logger
log public and private messages to disk.
POE::Component::IRC::Plugin::NickServID
identify with NickServ when needed.
POE::Component::IRC::Plugin::Proxy
a lightweight IRC proxy/bouncer.
POE::Component::IRC::Plugin::CTCP
automagically generates replies to ctcp version, time and userinfo queries. โจ
POE::Component::IRC::Plugin::PlugMan
an experimental Plugin Manager plugin. experimental, bestie, you've been warned ๐
POE::Component::IRC::Plugin::NickReclaim
automagically deals with your nickname being in use and reclaiming it.
POE::Component::IRC::Plugin::CycleEmpty
cycles (parts and rejoins) channels if they become empty and opless, in order to gain ops. the grind never stops ๐
๐ CONSTRUCTORS ๐
Both constructors hand you back an object, bestie. And here's the cute part: that same object is also reachable from inside any 'irc_' event handler if you just grab $_[SENDER]->get_heap(). Slay. Also go peek at "register" and "irc_registered" while you're at it. โจ
๐ธ "spawn" ๐ธ
This one takes a whole handful of arguments and every single one of them is optional, which is giving very chill, very low-pressure energy. Good news though: everything in the list below can also be passed to the "connect" input event โ the only exceptions are 'alias', 'options', 'NoDNS', 'debug', and 'plugin_debug'.
'alias'โ a name (kernel alias) that this instance will be known by ๐ท๏ธ'options'โ a hashref containing POE::Session options'Server'โ the server name'Port'โ the remote port number'Password'โ an optional password, for when the server is doing the most and restricting access'Nick'โ your client's IRC nickname'Username'โ your client's username'Ircname'โ some cute comment or something ๐ฌ'Bitmode'โ an integer representing your initial user modes, set in theUSERcommand. See RFC 2812. If you don't set this,8(+i) gets used instead.'UseSSL'โ set it to some true value if you wanna connect using SSL ๐'SSLCert'โ set to a SSL Certificate(PAM encoded) to connect using a client cert'SSLKey'โ set to a SSL Key(PAM encoded) to connect using a client cert'SSLCtx'โ set to a SSL Context to configure the SSL Connection
So the 'SSLCert' and 'SSLKey' both need to be specified. And the 'SSLCtx' takes precedence specified. (That's the original's phrasing, keeping it fr fr.) ๐ซถ
'Raw'โ set to some true value to enable the component to send"irc_raw"and"irc_raw_out"events.'LocalAddr'โ which local IP address on a multihomed box to connect as'LocalPort'โ the local TCP port to open your socket on'NoDNS'โ set this to1to disable DNS lookups using PoCo-Client-DNS. (See the note further down, bestie.)'Flood'โ when true, it disables the component's flood protection algorithms, allowing it to send messages to an IRC server at full speed.
โ ๏ธ Disconnects and k-lines are some common side effects of flooding IRC servers, so care should be used when enabling this option. Default is false.
Two new attributes are 'Proxy' and 'ProxyPort' for sending your =item * 'Proxy', IP address or server name of a proxy server to use.
(Yes โ that line is exactly as mangled as it looks. The original page has a lil pod glitch right there and I am not touching the facts. ๐)
'ProxyPort'โ which tcp port on the proxy to connect to.'NATAddr'โ what other clients see as your IP address.'DCCPorts'โ an arrayref containing tcp ports that can be used for DCC sends.'Resolver'โ provide a POE::Component::Client::DNS object for the component to use.'msg_length'โ the maximum length of IRC messages, in bytes. Default is450.
The IRC component shortens all messages longer than this value minus the length of your current nickname. IRC only allows raw protocol lines messages that are 512 bytes or shorter, including the trailing "\r\n". This is most relevant to long PRIVMSGs. The IRC component can't be sure how long your user@host mask will be every time you send a message, considering that most networks mangle the 'user' part and some even replace the whole string (think FreeNode cloaks). If you have an unusually long user@host mask you might want to decrease this value if you're prone to sending long messages. Conversely, if you have an unusually short one, you can increase this value if you want to be able to send as long a message as possible. Be careful though โ increase it too much and the IRC server might disconnect you with a "Request too long" message when you try to send a message that's too long. ๐ญ
'debug'โ if set to a true value causes the IRC component to print every message sent to and from the server, as well as print some warnings when it receives malformed messages. This option will be enabled if the"POCOIRC_DEBUG"environment variable is set to a true value.'plugin_debug'โ set to some true value to print plugin debug info, default0.
Plugins are processed inside an eval. When you enable this option, you will be notified when (and why) a plugin raises an exception. This option will be enabled if the "POCOIRC_DEBUG" environment variable is set to a true value.
'socks_proxy'โ specify a SOCKS4/SOCKS4a proxy to use.'socks_port'โ the SOCKS port to use, defaults to1080if not specified.'socks_id'โ specify a SOCKS user_id. Default is none.'useipv6'โ enable the use of IPv6 for connections.'webirc'โ enable the use of WEBIRC to spoof host/IP.
You must have a WEBIRC password set up on the IRC server/network (so will only work for servers which trust you to spoof the IP & host the connection is from) โ value should be a hashref containing keys "pass", "user", "host" and "ip". ๐
"spawn" will supply reasonable defaults for any of these attributes which are missing, so don't feel obliged to write them all out. She's got you. ๐
If the component finds that POE::Component::Client::DNS is installed it will use that to resolve the server name passed. Disable this behaviour if you like, by passing: NoDNS => 1.
IRC traffic through a proxy server: 'Proxy''s value should be the IP address or server name of the proxy. 'ProxyPort''s value should be the port on the proxy to connect to. "connect" will default to using the actual IRC server's port if you provide a proxy but omit the proxy's port. These are for HTTP Proxies. See 'socks_proxy' for SOCKS4 and SOCKS4a support. ๐งฆ
For those people who run bots behind firewalls and/or Network Address Translation there are two additional attributes for DCC. 'DCCPorts', is an arrayref of ports to use when initiating DCC connections. 'NATAddr', is the NAT'ed IP address that your bot is hidden behind, this is sent whenever you do DCC. ๐ก๏ธ
SSL support requires POE::Component::SSLify, as well as an IRC server that supports SSL connections. If you're missing POE::Component::SSLify, specifying 'UseSSL' will do nothing. The default is to not try to use SSL. (Not me quietly crying over a silently ignored option ๐ญ)
'Resolver', requires a POE::Component::Client::DNS object. Useful when spawning multiple poco-irc sessions, saves the overhead of multiple dns sessions. Very efficient, very demure. โจ
'NoDNS' has different results depending on whether it is set with "spawn" or "connect". Setting it with "spawn", disables the creation of the POE::Component::Client::DNS completely. Setting it with "connect" on the other hand allows the PoCo-Client-DNS session to be spawned, but will disable any dns lookups using it. Same flag, two whole different vibes. ๐
SOCKS4 proxy support is provided by 'socks_proxy', 'socks_port' and 'socks_id' parameters. If something goes wrong with the SOCKS connection you should get a warning on STDERR. This is fairly experimental currently. ๐งช
IPv6 support is available for connecting to IPv6 enabled ircds (it won't work for DCC though). To enable it, specify 'useipv6'. Perl >=5.14 or Socket6 (for older Perls) is required. If you that and POE::Component::Client::DNS installed and specify a hostname that resolves to an IPv6 address then IPv6 will be used. If you specify an ipv6 'localaddr' then IPv6 will be used.
๐ฆ "new" ๐ฆ
Okay so this method is deprecated, bestie. Go look at the "spawn" method instead, she's the moment. ๐
The first argument should be a name (kernel alias) which this new connection will be known by. Optionally takes more arguments (see "spawn" as name/value pairs. Returns a POE::Component::IRC object. :)
Note: Use of this method will generate a warning. There are currently no plans to make itdie()>;]
(That die() >;] is the original's whole personality and I refuse to edit it. Iconic behavior honestly. ๐
)
๐ธ METHODS ๐ธ
๐ก Information ๐ก
serverโ no args bestie, zero, nada. Just hands you back the host of the server we're currently connected to (or, like, trying to connect to, be patient ๐ ).portโ also takes nothing. Gives you the port number of the server we're on right now (or the one we're tryna reach).server_nameโ no args. Returns the name of the IRC server this component is hooked up to atm.server_versionโ no args. The IRC server's version, served fresh โจ.nick_nameโ no args. Hands back a scalar with whatever nickname the bot is currently rocking.localaddrโ no args. Returns the IP address in use.send_queueโ okay so this component does anti-flood throttling, iconic of it tbh. No arguments needed; you get back a scalar = the number of messages chilling in the queue waiting to be dispatched to the irc server ๐ซถ.logged_inโ no args. True or false depending on whether the IRC component is logged into an IRC network fr.connectedโ no args. True or false depending on whether the component's socket is currently connected.disconnectโ no args. Terminates the socket connection disgracefully >;o] ๐ (their words, not mine, but the drama is warranted).isupportโ takes exactly one argument: a server capability to query. Returnsundefif it flops, or a value representing the applicable capability. The full list of capabilities lives athttp://www.irc.org/tech_docs/005.htmlif you wanna go read.isupport_dump_keysโ no arguments. Returns a list of the available server capabilities keys, the ones you can use withisupport๐.resolverโ returns a reference to thePOE::Component::Client::DNSobject that the component creates internally all by itself. Our little overachiever.
๐ Events ๐
session_idโ Inherited from POE::Component::Syndicator. No arguments. Returns the ID of the component's session. Ideal for posting events to the component, like so:
$kernel->post($irc->session_id() => 'mode' => $channel => '+o' => $dude);
session_aliasโ Inherited from POE::Component::Syndicator. No arguments. Returns the session alias that got set throughspawn's'alias'argument.raw_eventsโ call it with no arguments and it tells you true/false whetherirc_rawandirc_raw_outevents are being generated or not. Pass it a true or false argument and you enable/disable that feature accordingly. You're in control, bestie ๐ .yieldโ Inherited from POE::Component::Syndicator. This is the alternative object-based way of posting events to the component. First argument = the event to post, and every argument after that gets sent as arguments to the resulting post.
$irc->yield(mode => $channel => '+o' => $dude);
callโ Inherited from POE::Component::Syndicator. The alternative object-based way of calling events to the component. First argument = the event to call, following arguments get sent as arguments along with the resulting call.
$irc->call(mode => $channel => '+o' => $dude);
delayโ Inherited from POE::Component::Syndicator. The way you post delayed events to the component. First argument is an arrayref containing the delayed command to post plus any command arguments. Second argument is the time in seconds you wanna delay the posting by.
my $alarm_id = $irc->delay( [ mode => $channel => '+o' => $dude ], 60 );
It returns an alarm ID you can then use with delay_remove to cancel that delayed event. If something went wrong, this will be undefined ๐ญ.
delay_removeโ Inherited from POE::Component::Syndicator. Yeets a previously scheduled delayed event out of the component. Takes one argument: thealarm_idthat adelaymethod call gave you.
my $arrayref = $irc->delay_remove( $alarm_id );
Returns the arrayref that was originally requested to be delayed โจ.
send_eventโ Inherited from POE::Component::Syndicator. Sends an event through the component's event handling system. These get processed by plugins first, then by registered sessions. First argument is the event name, followed by any parameters for that event.send_event_nextโ Inherited from POE::Component::Syndicator. Sends an event right after the one that's currently being processed. So useful when you wanna generate an event that's directly related to another event and you want them to show up together, bestie behaviour ๐ซถ. You can only call this method whilePOE::Component::IRCis processing an event, like from one of your event handlers. Takes the same arguments assend_event.send_event_nowโ Inherited from POE::Component::Syndicator. Sends an event to be processed immediately. Meaning: if an event is currently being processed and there are plugins or sessions that would receive it after you do, then an event sent withsend_event_nowgets received by those plugins/sessions before the current event. Jump the line, main character energy ๐. Takes the same arguments assend_event.
๐ง Plugins ๐ง
pipelineโ Inherited from Object::Pluggable. Returns theObject::Pluggable::Pipelineobject.plugin_addโ Inherited from Object::Pluggable. Accepts two arguments:- The alias for the plugin
- The actual plugin object
- Any number of extra arguments
The alias is there so you, the user, can refer to it โ because it's totally possible to have multiple plugins of the same kind active inside one Object::Pluggable object, and we need to tell them apart.
This method goes through the pipeline's push() method, which will call $plugin->plugin_register($pluggable, @args).
Returns the number of plugins now in the pipeline if the plugin was initialized, or undef/an empty list if not.
plugin_delโ Inherited from Object::Pluggable. Accepts the following arguments:- The alias for the plugin, or the plugin object itself
- Any number of extra arguments
This method goes through the pipeline's remove() method, which will call $plugin->plugin_unregister($pluggable, @args).
Returns the plugin object if the plugin was removed, undef/an empty list if not.
plugin_getโ Inherited from Object::Pluggable. Accepts the following arguments:- The alias for the plugin
This method goes through the pipeline's get() method.
Returns the plugin object if it was found, undef/an empty list if not.
plugin_listโ Inherited from Object::Pluggable. Takes no arguments.
Returns a hashref of plugin objects, keyed on alias, or an empty list if there are no plugins loaded.
plugin_orderโ Inherited from Object::Pluggable. Takes no arguments.
Returns an arrayref of plugin objects, in the order they're encountered in the pipeline.
plugin_registerโ Inherited from Object::Pluggable. Accepts the following arguments:- The plugin object
- The type of the hook (the hook types are specified with
_pluggable_init()'s'types') - The event name[s] to watch
The event names can be as many as possible, or an arrayref. They correspond to the prefixed events and, naturally, arbitrary events too.
You do not need to supply events with the prefix in front of them โ just the names ๐ .
It's possible to register for all events by specifying 'all' as an event.
Returns 1 if everything checked out fine, undef/an empty list if something is seriously wrong.
plugin_unregisterโ Inherited from Object::Pluggable. Accepts the following arguments:- The plugin object
- The type of the hook (the hook types are specified with
_pluggable_init()'s'types') - The event name[s] to unwatch
The event names can be as many as possible, or an arrayref. They correspond to the prefixed events and, naturally, arbitrary events too.
You do not need to supply events with the prefix in front of them โ just the names.
It's possible to register for all events by specifying 'all' as an event.
Returns 1 if all the event name[s] was unregistered, undef if some was not found.
๐ INPUT EVENTS ๐
How to talk to your new IRC component... here's the events we'll accept bestie ๐ซถ. These are events that get posted to the component, either via $poe_kernel->post() or via the object method yield.
So the following would all be functionally equivalent:
sub irc_001 {
my ($kernel,$sender) = @_[KERNEL,SENDER];
my $irc = $sender->get_heap(); # obtain the poco's object
$irc->yield( privmsg => 'foo' => 'Howdy!' );
$kernel->post( $sender => privmsg => 'foo' => 'Howdy!' );
$kernel->post( $irc->session_id() => privmsg => 'foo' => 'Howdy!' );
$kernel->post( $irc->session_alias() => privmsg => 'foo' => 'Howdy!' );
return;
}
โญ Important Commands โญ
registerโ Inherited from POE::Component::Syndicator. Takes N arguments: a list of event names that your session wants to listen for, minus theirc_prefix. So, for instance, if you just want a bot that keeps track of which people are on a channel, you'll need to listen for JOINs, PARTs, QUITs, and KICKs to people on the channel you're in. You'd tellPOE::Component::IRCyou want those events by saying:
$kernel->post('my client', 'register', qw(join part quit kick));
Then, whenever people enter or leave a channel your bot is on (forcibly or not), your session will receive events with names like irc_join, irc_kick, etc., which you can use to update a list of the people on the channel.
Registering for 'all' will cause it to send all IRC-related events to you; that's the easiest way to handle it. See the test script for an example ๐.
Registering will generate an irc_registered event that your session can trap. ARG0 is the components object. Useful if you wanna bolt PoCo-IRC's new features such as Plugins into a bot coded to the older deprecated API. If you're using the new API, ignore this :)
Registering with multiple component sessions can be tricky, especially if one wants to marry up sessions/objects, etc. Check the SIGNALS section for an alternative method of registering with multiple poco-ircs.
Starting with version 4.96, if you spawn the component from inside another POE session, the component will automatically register that session as wanting 'all' irc events. That session will receive an irc_registered event indicating that the component is up and ready to go ๐ฅ.
unregisterโ Inherited from POE::Component::Syndicator. Takes N arguments: a list of event names which you don't wanna receive. If you've previously done aregisterfor a particular event that you no longer care about, this event tells the IRC connection to stop sending them to you. (If you haven't, it just ignores you. No big deal, no drama ๐ .)
If you have registered with 'all', attempting to unregister individual events such as 'mode', etc. will not work. This is a 'feature'.
connect
okay so this one takes exactly one arg: a hashref full of attributes for the new connection โ peek at "spawn" for the deets. This event is literally your IRC client being told to connect to a new/different server. If it's already got a connection open? It'll close it gracefully before reconnecting. polite queen behavior. ๐
ctcpandctcpreplyโ Sends a CTCP query or response to the nick(s) or channel(s) which you specify. Takes 2 arguments: the nick or channel to send a message to (use an array reference here to specify multiple recipients), and the plain text of the message to send (the CTCP quoting will be handled for you). The/mecommand in popular IRC clients is actually a CTCP action.
# Doing a /me
$irc->yield(ctcp => $channel => 'ACTION dances.');
joinโ Tells your IRC client to join a single channel of your choice. Takes at least one arg: the channel name (required) and the channel key (optional, for password-protected channels).kickโ Tell the IRC server to forcibly evict a user from a particular channel. Takes at least 2 arguments: a channel name, the nick of the user to boot, and an optional witty message to show them as they sail out the door.removeโ Tell the IRC server to forcibly evict a user from a particular channel. Takes at least 2 arguments: a channel name, the nick of the user to boot, and an optional witty message to show them as they sail out the door. Similar to KICK but does an enforced PART instead. Not supported by all servers.modeโ Request a mode change on a particular channel or user. Takes at least one argument: the mode changes to effect, as a single string (e.g.#mychan +sm-p+o), and any number of optional operands to the mode changes (nicks, hostmasks, channel keys, whatever.) Or just pass them all as one big string and it'll still work, whatever. ngl I don't have the patience to write a whole dissertation right now, but serious IRC users know the details anyhow.nickโ Allows you to change your nickname. Takes exactly one argument: the new username that you'd like to be known as.nickservโ Talks to NickServ, on networks which have it. Takes any number of arguments.noticeโ Sends a NOTICE message to the nick(s) or channel(s) which you specify. Takes 2 arguments: the nick or channel to send a notice to (use an array reference here to specify multiple recipients), and the text of the notice to send.partโ Tell your IRC client to leave the channels which you pass to it. Takes any number of arguments: channel names to depart from. If the last argument doesn't begin with a channel name identifier or contains a space character, it will be treated as a PART message and dealt with accordingly.privmsgโ Sends a public or private message to the nick(s) or channel(s) which you specify. Takes 2 arguments: the nick or channel to send a message to (use an array reference here to specify multiple recipients), and the text of the message to send.
Have a look at the constants in IRC::Utils if you would like to use formatting and color codes in your messages.
$irc->yield('primvsg', '#mychannel', 'Hello there');
# same, but with a green Hello
use IRC::Utils qw(GREEN NORMAL);
$irc->yield('primvsg', '#mychannel', GREEN.'Hello'.NORMAL.' there');
quitโ Tells the IRC server to disconnect you. Takes one optional argument: some clever, witty string that other users in your channels will see as you leave. You can expect to get anirc_disconnectedevent shortly after sending this.shutdownโ By default, POE::Component::IRC sessions never go away. Even after they're disconnected, they're still sitting around in the background, waiting for you to callconnecton them again to reconnect. (Whether this behavior is the Right Thing is doubtful, but I don't want to break backwards compatibility at this point.) You can send the IRC session ashutdownevent manually to make it delete itself. If you are logged into an IRC server,shutdownfirst will send a quit message and wait to be disconnected. It will wait for up to 5 seconds before forcibly disconnecting from the IRC server. If you provide an argument, that will be used as the QUIT message. If you provide two arguments, the second one will be used as the timeout (in seconds). Terminating multiple components can be tricky. Check the SIGNALS section for a method of shutting down multiple poco-ircs.topicโ Retrieves or sets the topic for particular channel. If called with just the channel name as an argument, it will ask the server to return the current topic. If called with the channel name and a string, it will set the channel topic to that string. Supply an empty string to unset a channel topic.debugโ Takes one argument:0to turn debugging off or1to turn debugging on. This flips the debugging flag in POE::Filter::IRCD, POE::Filter::IRC::Compat, and POE::Component::IRC. This has the same effect as setting Debug inspawnorconnect.
Not-So-Important Commands ๐ฆ
adminโ Asks your server who your friendly neighborhood server administrators are. If you prefer, you can pass it a server name to query, instead of asking the server you're currently on.awayโ When sent with an argument (a message describig where you went), the server will note that you're now away from your machine or otherwise preoccupied, and pass your message along to anyone who tries to communicate with you. When sent without arguments, it tells the server that you're back and paying attention.capโ Used to query/enable/disable IRC protocol capabilities. Takes any number of arguments.dcc*โ See the DCC plugin (loaded by default) documentation for DCC-related commands.infoโ Basically the same as theversioncommand, except that the server is permitted to return any information about itself that it thinks is relevant. There's some nice, specific standards-writing for ya, eh?inviteโ Invites another user onto an invite-only channel. Takes 2 arguments: the nick of the user you wish to admit, and the name of the channel to invite them to.isonโ Asks the IRC server which users out of a list of nicknames are currently online. Takes any number of arguments: a list of nicknames to query the IRC server about.linksโ Asks the server for a list of servers connected to the IRC network. Takes two optional arguments, which I'm too lazy to document here, so all you would-be linklooker writers should probably go dig up the RFC.listโ Asks the server for a list of visible channels and their topics. Takes any number of optional arguments: names of channels to get topic information for. If called without any channel names, it'll list every visible channel on the IRC network. This is usually a really big list, so don't do this often.motdโ Request the server'sMessage of the Day, a document which typically contains stuff like the server's acceptable use policy and admin contact email addresses, et cetera. Normally you'll automatically receive this when you log into a server, but if you want it again, here's how to do it. If you'd like to get the MOTD for a server other than the one you're logged into, pass it the server's hostname as an argument; otherwise, no arguments.namesโ Asks the server for a list of nicknames on particular channels. Takes any number of arguments: names of channels to get lists of users for. If called without any channel names, it'll tell you the nicks of everyone on the IRC network. This is a really big list, so don't do this much.quoteโ Sends a raw line of text to the server. Takes one argument: a string of a raw IRC command to send to the server. It is more optimal to use the events this module supplies instead of writing raw IRC commands yourself.statsโ Returns some information about a server. Kinda complicated and not terribly commonly used, so look it up in the RFC if you're curious. Takes as many arguments as you please.timeโ Asks the server what time it thinks it is, which it will return in a human-readable form. Takes one optional argument: a server name to query. If not supplied, defaults to current server.traceโ If you pass a server name or nick along with this request, it asks the server for the list of servers in between you and the thing you mentioned. If sent with no arguments, it will show you all the servers which are connected to your current server.usersโ Asks the server how many users are logged into it. Defaults to the server you're currently logged into; however, you can pass a server name as the first argument to query some other machine instead.versionโ Asks the server about the version of ircd that it's running. Takes one optional argument: a server name to query. If not supplied, defaults to current server.whoโ Lists the logged-on users matching a particular channel name, hostname, nickname, or what-have-you. Takes one optional argument: a string for it to search for. Wildcards are allowed; in the absence of this argument, it will return everyone who's currently logged in (bad move). Tack anoon the end if you want to list only IRCops, as per the RFC.whoisโ Queries the IRC server for detailed information about a particular user. Takes any number of arguments: nicknames or hostmasks to ask for information about. As of version 3.2, you will receive anirc_whoisevent in addition to the usual numeric responses. See below for details.whowasโ Asks the server for information about nickname which is no longer connected. Takes at least one argument: a nickname to look up (no wildcards allowed), the optional maximum number of history entries to return, and the optional server hostname to query. As of version 3.2, you will receive anirc_whowasevent in addition to the usual numeric responses. See below for details.pingandpongโ Included for completeness sake. The component will deal with ponging to pings automatically. Don't worry about it.
Purely Esoteric Commands ๐ฎ
dieโ Tells the IRC server you're connect to, to terminate. Only useful for IRCops, thank goodness. Takes no arguments.locopsโ Opers-only command. This one sends a message to all currently logged-on local-opers (+l). This option is specific to EFNet.operโ In the exceedingly unlikely event that you happen to be an IRC operator, you can use this command to authenticate with your IRC server. Takes 2 arguments: your username and your password.operwallโ Opers-only command. This one sends a message to all currently logged-on global opers. This option is specific to EFNet.rehashrehashโ tells the IRC server you're connected to, to rehash its configuration files. Only useful for IRCops. Takes no arguments. ๐restartโ tells the IRC server you're connected to, to shut down and restart itself. Only useful for IRCops, thank goodness. Takes no arguments.sconnectโ tells one IRC server (which you have operator status on) to connect to another. This is actually the CONNECT command, but I already had an event calledconnect, so too bad. Takes the args you'd expect: a server to connect to, an optional port to connect on, and an optional remote server to connect with, instead of the one you're currently on.squitโ operator-only command used to disconnect server links. Takes two arguments, the server to disconnect and a message explaining your action.summonโ Don't even ask.servlistโ lists the currently connected services on the network that are visible to you. Takes two optional arguments, a mask for matching service names against, and a service type.squeryโ sends a message to a service. Takes the same arguments asprivmsg.userhostโ asks the IRC server for information about particular nicknames. (The RFC doesn't define exactly what this is supposed to return.) Takes any number of arguments: the nicknames to look up.wallopsโ Another opers-only command. This one sends a message to all currently logged-on opers (and+wusers); sort of a mass PA system for the IRC server administrators. Takes one argument: some clever, witty message to send.
๐โจ OUTPUT EVENTS โจ๐
These are the events you'll receive (or can ask to receive) from your running IRC component, bestie. Note that all incoming event names your session will receive are prefixed by irc_, to inhibit event namespace pollution. periodt.
If you wish, you can ask the client to send you every event it generates. Simply register for the event name all. This is a lot easier than writing a huge list of things you specifically want to listen for. obsessed.
FIXME: I'd really like to classify these somewhat ("basic", "oper", "ctcp", "dcc", "raw" or some such), and I'd welcome suggestions for ways to make this easier on the user, if you can think of some. ๐
In your event handlers, $_[SENDER] is the particular component session that sent you the event. "$_[SENDER]->get_heap()" will retrieve the component's object. Useful if you want on-the-fly access to the object and its methods.
๐ Important Events ๐
irc_registeredโ Inherited from POE::Component::Syndicator. Sent once to the requesting session on registration (seeregister).ARG0is a reference to the component's object.irc_shutdownโ Inherited from POE::Component::Syndicator. Sent to all registered sessions when the component has been asked toshutdown.ARG0will be the session ID of the requesting session.irc_connectedโ The IRC component will send anirc_connectedevent as soon as it establishes a connection to an IRC server, before attempting to log in.ARG0is the server name.
NOTE: When you get anirc_connectedevent, this doesn't mean you can start sending commands to the server yet. Wait until you receive anirc_001event (the server welcome message) before actually sending anything back to the server. no cap, wait for it.
irc_ctcpโirc_ctcpevents are generated upon receipt of CTCP messages, in addition to theirc_ctcp_*events mentioned below. They are identical in every way to these, with one difference: instead of the*being in the method name, it is prepended to the argument list. For example, if someone types/ctcp Flibble foo bar, anirc_ctcpevent will be sent with'foo'asARG0, and the rest as given below. It is not recommended that you register for bothirc_ctcpandirc_ctcp_*events, since they will both be fired and presumably cause duplication. double trouble, avoid.irc_ctcp_*โirc_ctcp_whateverevents are generated upon receipt of CTCP messages. For instance, receiving a CTCP PING request generates anirc_ctcp_pingevent, CTCP ACTION (produced by typing/mein most IRC clients) generates anirc_ctcp_actionevent, blah blah, so on and so forth.ARG0is the nick!hostmask of the sender.ARG1is the channel/recipient name(s).ARG2is the text of the CTCP message. On servers supporting the IDENTIFY-MSG feature (e.g. FreeNode), CTCP ACTIONs will haveARG3, which will be 1 if the sender has identified with NickServ, 0 otherwise. Note that DCCs are handled separately -- see the DCC plugin. dcc girlies, that's your lane.irc_ctcpreply_*โirc_ctcpreply_whatevermessages are just likeirc_ctcp_whatevermessages, described above, except that they're generated when a response to one of your CTCP queries comes back. They have the same arguments and such asirc_ctcp_*events.irc_disconnectedโ The counterpart toirc_connected, sent whenever a socket connection to an IRC server closes down (whether intentionally or unintentionally).ARG0is the server name.irc_errorโ You get this whenever the server sends you an ERROR message. Expect this to usually be accompanied by the sudden dropping of your connection.ARG0is the server's explanation of the error. it's giving chaos.irc_joinโ Sent whenever someone joins a channel that you're on.ARG0is the person's nick!hostmask.ARG1is the channel name.
irc_inviteโ Sent whenever someone offers you an invitation to another channel.ARG0is the person's nick!hostmask.ARG1is the name of the channel they want you to join.
irc_kickโ Sent whenever someone gets booted off a channel that you're on.ARG0is the kicker's nick!hostmask.ARG1is the channel name.ARG2is the nick of the unfortunate kickee.ARG3is the explanation string for the kick.
irc_modeโ Sent whenever someone changes a channel mode in your presence, or when you change your own user mode.ARG0is the nick!hostmask of that someone.ARG1is the channel it affects (or your nick, if it's a user mode change).ARG2is the mode string (i.e.,"+o-b").- The rest of the args (
ARG3 .. $#_) are the operands to the mode string (nicks, hostmasks, channel keys, whatever).
irc_msgโ Sent whenever you receive a PRIVMSG command that was addressed to you privately.ARG0is the nick!hostmask of the sender.ARG1is an array reference containing the nick(s) of the recipients.ARG2is the text of the message.- On servers supporting the IDENTIFY-MSG feature (e.g. FreeNode), there will be an additional argument,
ARG3, which will be 1 if the sender has identified with NickServ, 0 otherwise.
irc_nickโ Sent whenever you, or someone around you, changes nicks.ARG0is the nick!hostmask of the changer.ARG1is the new nick that they changed to.
irc_noticeโ Sent whenever you receive a NOTICE command.ARG0is the nick!hostmask of the sender.ARG1is an array reference containing the nick(s) or channel name(s) of the recipients.ARG2is the text of the NOTICE message.
irc_partโ Sent whenever someone leaves a channel that you're on.ARG0is the person's nick!hostmask.ARG1is the channel name.ARG2is the part message.
irc_publicโ Sent whenever you receive a PRIVMSG command that was sent to a channel.ARG0is the nick!hostmask of the sender.ARG1is an array reference containing the channel name(s) of the recipients.ARG2is the text of the message.- On servers supporting the IDENTIFY-MSG feature (e.g. FreeNode), there will be an additional argument,
ARG3, which will be 1 if the sender has identified with NickServ, 0 otherwise.
irc_quitโ Sent whenever someone on a channel with you quits IRC (or gets KILLed).ARG0is the nick!hostmask of the person in question.ARG1is the clever, witty message they left behind on the way out.
irc_socketerrโ Sent when a connection couldn't be established to the IRC server.ARG0is probably some vague and/or misleading reason for what failed. mystery, but make it annoying.irc_topicโ Sent when a channel topic is set or unset.ARG0is the nick!hostmask of the sender.ARG1is the channel affected.ARG2will be either: a string if the topic is being set; or a zero-length string (i.e.'') if the topic is being unset.- Note: replies to queries about what a channel topic is (i.e.
TOPIC #channel), are returned as numerics, not with this event.
irc_whoisโ Sent in response to a WHOIS query.ARG0is a hashref, with the following keys:'nick', the users nickname;'user', the users username;'host', their hostname;'real', their real name;'idle', their idle time in seconds;'signon', the epoch time they signed on (will beundefif ircd does not support this);'channels', an arrayref listing visible channels they are on, the channel is prefixed with'@','+','%'depending on whether they have+o+vor+h;'server', their server (might not be useful on some networks);'oper', whether they are an IRCop, contains the IRC operator string if they are,undefif they aren't.'actually', some ircds report the user's actual ip address, that'll be here;'identified'. if the user has identified with NICKSERV (ircu, seven, Plexus)'modes', a string describing the user's modes (Rizon)
irc_whowasโ Similar to the above, except some keys will be missing.irc_rawโ Enabled by passingRaw => 1tospawnorconnect, or by callingraw_eventswith a true argument.ARG0is the raw IRC string received by the component from the IRC server, before it has been mangled by filters and such like.irc_raw_outโ Enabled by passingRaw => 1tospawnorconnect, or by callingraw_eventswith a true argument.ARG0is the raw IRC string sent by the component to the IRC server.irc_isupportโ Emitted by the first event after anirc_005, to indicate that isupport information has been gathered.ARG0is thePOE::Component::IRC::Plugin::ISupportobject.irc_socks_failedโ Emitted whenever we fail to connect successfully to a SOCKS server or the SOCKS server is not actually a SOCKS server.ARG0will be some vague reason as to what went wrong. Hopefully. manifesting clarity.irc_socks_rejectedโ Emitted whenever a SOCKS connection is rejected by a SOCKS server.ARG0is the SOCKS code,ARG1the SOCKS server address,ARG2the SOCKS port andARG3the SOCKS user id (if defined).irc_plugin_addโ Inherited from Object::Pluggable. Emitted whenever a new plugin is added to the pipeline.ARG0is the plugin alias.ARG1is the plugin object.
irc_plugin_delโ Inherited from Object::Pluggable.- Emitted whenever a plugin is removed from the pipeline ๐
ARG0is the plugin alias,ARG1is the plugin object itself. irc_plugin_errorโ inherited straight fromObject::Pluggable๐ซถ
Fires when a plugin handler throws a wobbly while it's executing. ARG0 is the error message, ARG1 is the plugin alias, ARG2 is the plugin object. Bestie, if you see this one, your plugin did not slay.
Somewhat Less Important Events ๐ซง
irc_capโ a reply from the server about protocol capabilities (CAP).ARG0is the CAP subcommand (like'LS'),ARG1is the result of that subcommand โ unless it's a multi-part reply, in which caseARG1is just'*'and the real result hides out inARG2. Sneaky.irc_dcc_*โ DCC-related events, all of them. Go read the DCC plugin docs (it's loaded by default, no cap ๐ ).irc_pingโ fired whenever the server slings a PING query at the client. โ ๏ธ Do not confuse this with a CTCP PING, which is a whole different beast โ if you're unsure, go read the RFC. And btw,POE::Component::IRChandles the PONG reply for you automatically, so you don't have to lift a finger. You can still register for the event if you just want to watch, for informational vibes.irc_snoticeโ a weird, non-RFC-compliant message straight from an IRC server. Usually it shows up during the authentication phase right after you connect, while the server is doing a hostname lookup or similar little chores.ARG0is the text of the server's message.ARG1is the target, which could be'*'or'AUTH'or literally whatever. Servers vary on whether these notices even include a server name as the sender, or no sender at all โ andARG1is the sender, if there is one.irc_delay_setโ inherited fromPOE::Component::Syndicatorโจ
Fired when a delayed event gets added successfully via the delay method. ARG0 is the alarm_id, which you can use later with delay_remove. The rest of the parameters are just the arguments that were passed to delay.
irc_delay_removedโ inherited fromPOE::Component::Syndicatorโจ
Fired when a delayed command is successfully removed. ARG0 is the alarm_id that got removed, and again the subsequent parameters are the arguments that were passed to delay.
All numeric events ๐ข
Okay so most messages from IRC servers are identified only by three-digit numeric codes with the most undescriptive constant names imaginable, like RPL_UMODEIS and ERR_NOTOPLEVEL. ๐
(Real talk though: the list of codes in the RFC is kind of out-of-dateโฆ the list in the back of Net::IRC::Event.pm is more complete, AND different IRC networks have different and incompatible lists. Ack!)
Say you wanted to handle event 376 โ that's RPL_ENDOFMOTD, the one that signals the end of the MOTD message. You'd register for '376', and listen for irc_376 events. Simple, no? ๐
ARG0 is the name of the server that sent the message, ARG1 is the text of the message, and ARG2 is an array reference of the already parsed message โ so you don't have to parse ARG1 yourself. Periodt.
๐ก SIGNALS ๐ก
The component handles a bunch of custom signals that you can send it using POE::Kernel's signal method. Let's go. ๐ซถ
POCOIRC_REGISTER
Inherited from POE::Component::Syndicator.
Registering with multiple PoCo-IRC components has been a pita. ๐ญ Well, no more, thanks to the power of POE::Kernel signals.
If the component receives a POCOIRC_REGISTER signal, it'll register the requesting session and trigger an irc_registered event. From that event you can grab everything you need โ the poco-irc object, the SENDER session โ and do whatever you gotta do to build a poco-irc dispatch table.
The way the signal handler in PoCo-IRC is written also supports sending POCOIRC_REGISTER to multiple sessions simultaneously, by sending the signal to the POE Kernel itself. Iconic.
Pass the signal your session, session ID or alias, plus the IRC events (same as you'd give to register).
To register with multiple PoCo-IRCs, you can do this in your session's _start handler:
sub _start {
my ($kernel, $session) = @_[KERNEL, SESSION];
# Registering with multiple pocoircs for 'all' IRC events
$kernel->signal($kernel, 'POCOIRC_REGISTER', $session->ID(), 'all');
return:
}
Each poco-irc will send your session an irc_registered event:
sub irc_registered {
my ($kernel, $sender, $heap, $irc_object) = @_[KERNEL, SENDER, HEAP, ARG0];
# Get the poco-irc session ID
my $sender_id = $sender->ID();
# Or it's alias
my $poco_alias = $irc_object->session_alias();
# Store it in our heap maybe
$heap->{irc_objects}->{ $sender_id } = $irc_object;
# Make the poco connect
$irc_object->yield(connect => { });
return;
}
POCOIRC_SHUTDOWN
Inherited from POE::Component::Syndicator.
Telling multiple poco-ircs to shutdown was a pita as well. Same principle as with registering, though โ it applies to shutdown too. ๐ธ
Send a POCOIRC_SHUTDOWN to the POE Kernel to terminate all the active poco-ircs simultaneously:
$poe_kernel->signal($poe_kernel, 'POCOIRC_SHUTDOWN');
Any additional parameters you pass to the signal will become your quit messages on each IRC network. Cute AND functional.
๐ ENCODING ๐
This can be an issue, ngl. Take a look at IRC::Utils' section on it. ๐ฆ
๐ BUGS ๐
A few have turned up in the past, and they are sure to again. Please use <http://rt.cpan.org/> to report any. Alternatively, just email the current maintainer. ๐ซถ
๐ DEVELOPMENT ๐
You can find the latest source on github: <http://github.com/bingos/poe-component-irc>
The project's developers usually hang out in the #poe IRC channel on irc.perl.org. Do drop us a line. ๐
๐ MAINTAINERS ๐
- Chris "BinGOs" Williams <chris@bingosnet.co.uk>
- Hinrik รrn Sigurรฐsson <hinrik.sig@gmail.com>
โ๏ธ AUTHOR โ๏ธ
Dennis Taylor.
๐ LICENCE ๐
Copyright (c) Dennis Taylor, Chris Williams and Hinrik รrn Sigurรฐsson
This module may be used, modified, and distributed under the same terms as Perl itself. Please see the license that came with your Perl distribution for details.
๐ MAD PROPS ๐
The maddest of mad props go out to Rocco "dngor" Caputo <troc@netrus.net>, for inventing something as mind-bogglingly cool as POE, and to Kevin "oznoid" Lenzo <lenzo@cs.cmu.edu>, for being the attentive parent of our precocious little infobot on #perl. ๐
Further props to a few of the studly bughunters who made this module not suck: Abys <abys@web1-2-3.com>, Addi <addi@umich.edu>, ResDev <ben@reser.org>, and Roderick <roderick@argon.org>. Woohoo! ๐ฅ
Kudos to Apocalypse, <apocal@cpan.org>, for the plugin system and to Jeff 'japhy' Pinyan, <japhy@perlmonk.org>, for Pipeline. ๐
Thanks to the merry band of POE pixies from #PoE @ irc.perl.org, including ( but not limited to ), ketas, ct, dec, integral, webfox, immute, perigrin, paulv, alias. ๐ง
IP functions are shamelessly 'borrowed' from Net::IP by Manuel Valente.
Check out the Changes file for further contributors.
๐ SEE ALSO ๐
- RFC 1459 <http://www.faqs.org/rfcs/rfc1459.html>
- <http://www.irchelp.org/>
- <http://poe.perl.org/>
- <http://www.infobot.org/>
Some good examples reside in the POE cookbook, which has a whole section devoted to IRC programming: <http://poe.perl.org/?POE_Cookbook> โจ
The examples/ folder of this distribution.
aaaaand that's the whole page, bestie, we made it to the end ๐๐ซถ This was POE::Component::IRC, perl v5.40.1, dated 2025-08-21 โ go forth and write some absolutely iconic IRC bots, you've got this ๐
โจ
๐ฆ where this page comes from
- ubuntu resolute: libpoe-component-irc-perl 6.95+dfsg-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libpoe-component-irc-perl 6.95+dfsg-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms