GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
Bot::BasicBot(3) User Contributed Perl Documentation Bot::BasicBot(3)

Bot::BasicBot - simple irc bot baseclass

  #!/usr/bin/perl
  use strict;
  use warnings;

  # Subclass Bot::BasicBot to provide event-handling methods.
  package UppercaseBot;
  use base qw(Bot::BasicBot);

  sub said {
      my $self      = shift;
      my $arguments = shift;    # Contains the message that the bot heard.

      # The bot will respond by uppercasing the message and echoing it back.
      $self->say(
          channel => $arguments->{channel},
          body    => uc $arguments->{body},
      );

      # The bot will shut down after responding to a message.
      $self->shutdown('I have done my job here.');
  }

  # Create an object of your Bot::BasicBot subclass and call its run method.
  package main;

  my $bot = UppercaseBot->new(
      server      => 'irc.example.com',
      port        => '6667',
      channels    => ['#bottest'],
      nick        => 'UppercaseBot',
      name        => 'John Doe',
      ignore_list => [ 'laotse', 'georgeburdell' ],
  );
  $bot->run();

Basic bot system designed to make it easy to do simple bots, optionally forking longer processes (like searches) concurrently in the background.

There are several examples of bots using Bot::BasicBot in the examples/ folder in the Bot::BasicBot tarball.

A quick summary, though - You want to define your own package that subclasses Bot::BasicBot, override various methods (documented below), then call "new" and "run" on it.

Creates a new instance of the class. Key/value pairs may be passed which will have the same effect as calling the method of that name with the value supplied. Returns a Bot::BasicBot object, that you can call 'run' on later.

eg:

  my $bot = Bot::BasicBot->new( nick => 'superbot', channels => [ '#superheroes' ] );

Runs the bot. Hands the control over to the POE core.

To shut down the bot cleanly, use the "shutdown" method, which will (through "AUTOLOAD") send an event of the same name to POE::Component::IRC, so it takes the same arguments:

 $bot->shutdown( $bot->quit_message() );

In your Bot::BasicBot subclass, you want to override some of the following methods to define how your bot works. These are all object methods - the (implicit) first parameter to all of them will be the bot object.

called when the bot is created, as part of new(). Override to provide your own init. Return a true value for a successful init, or undef if you failed, in which case new() will die.

This is the main method that you'll want to override in your subclass - it's the one called by default whenever someone says anything that we can hear, either in a public channel or to us in private that we shouldn't ignore.

You'll be passed a hashref that contains the arguments described below. Feel free to alter the values of this hash - it won't be used later on.

who
Who said it (the nick that said it)
raw_nick
The raw IRC nick string of the person who said it. Only really useful if you want more security for some reason.
channel
The channel in which they said it. Has special value "msg" if it was in a message. Actually, you can send a message to many channels at once in the IRC spec, but no-one actually does this so this is just the first one in the list.
body
The body of the message (i.e. the actual text)
address
The text that indicates how we were addressed. Contains the string "msg" for private messages, otherwise contains the string off the text that was stripped off the front of the message if we were addressed, e.g. "Nick: ". Obviously this can be simply checked for truth if you just want to know if you were addressed or not.

You should return what you want to say. This can either be a simple string (which will be sent back to whoever was talking to you as a message or in public depending on how they were talking) or a hashref that contains values that are compatible with say (just changing the body and returning the structure you were passed works very well.)

Returning undef will cause nothing to be said.

This is a secondary method that you may wish to override. It gets called when someone in channel 'emotes', instead of talking. In its default configuration, it will simply pass anything emoted on channel through to the "said" handler.

"emoted" receives the same data hash as "said".

This is like "said", except for notices instead of normal messages.

Called when someone joins a channel. It receives a hashref argument similar to the one received by said(). The key 'who' is the nick of the user who joined, while 'channel' is the channel they joined.

This is a do-nothing implementation, override this in your subclass.

Called when someone parts a channel. It receives a hashref argument similar to the one received by said(). The key 'who' is the nick of the user who parted, while 'channel' is the channel they parted.

This is a do-nothing implementation, override this in your subclass.

Whenever we have been given a definitive list of 'who is in the channel', this function will be called. It receives a hash reference as an argument. The key 'channel' will be the channel we have information for, 'names' is a hashref where the keys are the nicks of the users, and the values are more hashes, containing the two keys 'op' and 'voice', indicating if the user is a chanop or voiced respectively.

The reply value is ignored.

Normally, I wouldn't override this method - instead, just use the names call when you want to know who's in the channel. Override this only if you want to be able to do something as soon as possible. Also be aware that the names list can be changed by other events - kicks, joins, etc, and this method won't be called when that happens.

Called when the topic of the channel changes. It receives a hashref argument. The key 'channel' is the channel the topic was set in, and 'who' is the nick of the user who changed the channel, 'topic' will be the new topic of the channel.

When a user changes nicks, this will be called. It receives two arguments: the old nickname and the new nickname.

When a user sets channel modes, or the bot (or someone sharing its bouncer connection?) sets user modes, this will be called. It receives a hashref which will look like the following:

  {
      channel => "#channel",
      who => "nick!user@host",
      mode_changes => "+o+v",
      mode_operands => ["bigpresh", "somedude"],
  }

Called when a user is kicked from the channel. It receives a hashref which will look like this:

  {
    channel => "#channel",
    who => "nick",
    kicked => "kicked",
    reason => "reason",
  }

The reply value is ignored.

This is an event called every regularly. The function should return the amount of time until the tick event should next be called. The default tick is called 5 seconds after the bot starts, and the default implementation returns '0', which disables the tick. Override this and return non-zero values to have an ongoing tick event.

Use this function if you want the bot to do something periodically, and don't want to mess with 'real' POE things.

Call the schedule_tick event to schedule a tick event without waiting for the next tick.

This is the other method that you should override. This is the text that the bot will respond to if someone simply says help to it. This should be considered a special case which you should not attempt to process yourself. Saying help to a bot should have no side effects whatsoever apart from returning this text.

An optional method to override, gets called after we have connected to the server

Receives a hashref which will look like:

    {
      who => "nick that quit",
      body => "quit message",
    }

Receives a line of raw IRC input. Intended for cases where you're trying to do something clever which the normal methods and parsing supplied can't handle.

Receives a line of raw IRC output being sent to the IRC server.

There are a few methods you can call on the bot object to do things. These are as follows:

Takes an integer as an argument. Causes the tick event to be called after that many seconds (or 5 seconds if no argument is provided). Note that if the tick event is due to be called already, this will override it. You can't schedule multiple future events with this funtction.

This method allows you to fork arbitrary background processes. They will run concurrently with the main bot, returning their output to a handler routine. You should call "forkit" in response to specific events in your "said" routine, particularly for longer running processes like searches, which will block the bot from receiving or sending on channel whilst they take place if you don't fork them.

Inside the subroutine called by forkit, you can send output back to the channel by printing lines (followd by "\n") to STDOUT. This has the same effect as calling "Bot::BasicBot->say".

"forkit" takes the following arguments:

run
A coderef to the routine which you want to run. Bear in mind that the routine doesn't automatically get the text of the query - you'll need to pass it in "arguments" (see below) if you want to use it at all.

Apart from that, your "run" routine just needs to print its output to "STDOUT", and it will be passed on to your designated handler.

handler
Optional. A method name within your current package which we can return the routine's data to. Defaults to the built-in method "say_fork_return" (which simply sends data to channel).
callback
Optional. A coderef to execute in place of the handler. If used, the value of the handler argument is used to name the POE event. This allows using closures and/or having multiple simultanious calls to forkit with unique handler for each call.
body
Optional. Use this to pass on the body of the incoming message that triggered you to fork this process. Useful for interactive processes such as searches, so that you can act on specific terms in the user's instructions.
who
The nick of who you want any response to reach (optional inside a channel.)
channel
Where you want to say it to them in. This may be the special channel "msg" if you want to speak to them directly
address
Optional. Setting this to a true value causes the person to be addressed (i.e. to have "Nick: " prepended to the front of returned message text if the response is going to a public forum.
arguments
Optional. This should be an anonymous array of values, which will be passed to your "run" routine. Bear in mind that this is not intelligent - it will blindly spew arguments at "run" in the order that you specify them, and it is the responsibility of your "run" routine to pick them up and make sense of them.

Say something to someone. Takes a list of key/value pairs as arguments. You should pass the following arguments:
who
The nick of who you are saying this to (optional inside a channel.)
channel
Where you want to say it to them in. This may be the special channel "msg" if you want to speak to them directly
body
The body of the message. I.e. what you want to say.
address
Optional. Setting this to a true value causes the person to be addressed (i.e. to have "Nick: " prepended to the front of the message text if this message is going to a pulbic forum.

You can also make non-OO calls to "say", which will be interpreted as coming from a process spawned by "forkit". The routine will serialise any data it is sent, and throw it to STDOUT, where POE::Wheel::Run can pass it on to a handler.

"emote" will return data to channel, but emoted (as if you'd said "/me writes a spiffy new bot" in most clients). It takes the same arguments as "say", listed above.

"notice" will send a IRC notice to the channel. This is typically used by bots to not break the IRC conversations flow. The message will appear as:

    -nick- message here

It takes the same arguments as "say", listed above. Example:

    $bot->notice(
        channel => '#bot_basicbot_test',
        body => 'This is a notice'
    );

Takes two arguments, a hashref containing information about an incoming message, and a reply message. It will reply in a privmsg if the incoming one was a privmsg, in channel if not, and with prefixes if the incoming one was prefixed. Mostly a shortcut method - it's roughly equivalent to

 $mess->{body} = $body;
 $self->say($mess);

Takes no arguments. Returns the underlying POE::Component::IRC::State object used by Bot::BasicBot. Useful for accessing various state methods and for posting commands to the component. For example:

 # get the list of nicks in the channel #someplace
 my @nicks = $bot->pocoirc->channel_list("#someplace");

 # join the channel #otherplace
 $bot->pocoirc->yield('join', '#otherplace');

Takes a channel names as a parameter, and returns a hash of hashes. The keys are the nicknames in the channel, the values are hashes containing the keys "voice" and "op", indicating whether these users are voiced or opped in the channel. This method is only here for backwards compatibility. You'll probably get more use out of POE::Component::IRC::State's methods (which this method is merely a wrapper for). You can access the POE::Component::IRC::State object through Bot::BasicBot's "pocoirc" method.

Get or set methods. Changing most of these values when connected won't cause sideffects. e.g. changing the server will not cause a disconnect and a reconnect to another server.

Attributes that accept multiple values always return lists and either accept an arrayref or a complete list as an argument.

The usual way of calling these is as keys to the hash passed to the 'new' method.

The server we're going to connect to. Defaults to "irc.perl.org".

The port we're going to use. Defaults to "6667"

The server password for the server we're going to connect to. Defaults to undef.

A boolean to indicate whether or not the server we're going to connect to is an SSL server. Defaults to 0.

The local address to use, for multihomed boxes. Defaults to undef (use whatever source IP address the system deigns is appropriate).

A boolean to indicate whether IPv6 should be used. Defaults to undef (use IPv4).

The nick we're going to use. Defaults to five random letters and numbers followed by the word "bot"

Alternate nicks that this bot will be known by. These are not nicks that the bot will try if it's main nick is taken, but rather other nicks that the bot will recognise if it is addressed in a public channel as the nick. This is useful for bots that are replacements for other bots...e.g, your bot can answer to the name "infobot: " even though it isn't really.

The username we'll claim to have at our ip/domain. By default this will be the same as our nick.

The name that the bot will identify itself as. Defaults to "$nick bot" where $nick is the nick that the bot uses.

The channels we're going to connect to.

The quit message. Defaults to "Bye".

The list of irc nicks to ignore public messages from (normally other bots.) Useful for stopping bot cascades.

IRC has no defined character set for putting high-bit chars into channel. This attribute sets the encoding to be used for outgoing messages. Defaults to 'utf8'.

Set to '1' to disable the built-in flood protection of POE::Compoent::IRC

Tells Bot::BasicBot to not run the POE kernel at the end of "run", in case you want to do that yourself.

A hashref of WEBIRC params - keys "user", "pass", "host" and "ip". Unless the network you are connecting to trusts you enough to give you a WEBIRC config block & password, this won't be of any use to you.

Bot::BasicBot implements AUTOLOAD for sending arbitrary states to the underlying POE::Component::IRC component. So for a $bot object, sending

    $bot->foo("bar");

is equivalent to

    $poe_kernel->post(BASICBOT_ALIAS, "foo", "bar");

Logs the message. This method merely prints to STDERR - If you want smarter logging, override this method - it will have simple text strings passed in @_.

Takes a nick name as an argument. Return true if this nick should be ignored. Ignores anything in the ignore list

Takes a nick and hostname (of the form "nick!hostname") and returns just the nick

Converts a string of bytes from IRC (uses "decode_irc" from IRC::Utils internally) and returns a Perl string.

It can also takes a list (or arrayref or hashref) of strings, and return a list of strings

Converts a list of perl strings into a list of byte sequences, using the bot's charset. See "charset_decode".

If you have any questions or issues, you can drop by in #poe or #bot-basicbot @ irc.perl.org, where I (Hinrik) am usually around.

David Precious (BIGPRESH) "<davidp@preshweb.co.uk>" is the current maintainer.

Tom Insam <tom@jerakeen.org> was the original author.

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

The initial version of Bot::BasicBot was written by Mark Fowler, and many thanks are due to him.

Nice code for dealing with emotes thanks to Jo Walsh.

Various patches from Tom Insam, including much improved rejoining, AUTOLOAD stuff, better interactive help, and a few API tidies.

Maintainership for a while was in the hands of Simon Kent <simon@hitherto.net>. Don't know what he did. :-)

I (Tom Insam) received patches for tracking joins and parts from Silver, sat on them for two months, and have finally applied them. Thanks, dude. He also sent me changes for the tick event API, which made sense.

In November 2010, maintainership moved to Hinrik Örn Sigurðsson (hinrik.sig@gmail.com).

In April 2017, maintainership moved to David Precious (davidp@preshweb.co.uk).

If you want to write/run a more flexible bot which supports module loading, authentication, data storage etc, consider the subclass Bot::BasicBot::Pluggable.

Also see POE, POE::Component::IRC

Possibly Infobot, at http://www.infobot.org

2018-02-02 perl v5.32.1

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.