Skip to content
Simple IRC bot base class http://search.cpan.org/dist/Bot-BasicBot/
Perl Perl6
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
examples
lib/Bot
t
Build.PL
Changes
MANIFEST
META.yml
Makefile.PL
NINJA
README

README

NAME
    Bot::BasicBot - simple irc bot baseclass

SYNOPSIS
      # with all defaults
      my $bot = Bot::BasicBot->new( channels => ["#bottest"] );
      $bot->run();

      # with all known options
      my $bot = Bot::BasicBot->new(

        server => "irc.example.com",
        port   => "6667",
        channels => ["#bottest"],
    
        nick      => "basicbot",
        alt_nicks => ["bbot", "simplebot"],
        username  => "bot",
        name      => "Yet Another Bot",
    
        ignore_list => [qw(dipsy dadadodo laotse)],

        charset => "utf-8", # charset the bot assumes the channel is using

      );
      $bot->run();

DESCRIPTION
    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. If you installed Bot::BasicBot
    through CPAN, see http://jerakeen.org/programming/Bot-BasicBot for more
    docs and examples.

    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.

STARTING THE BOT
  new( key => value, .. )
    Creates a new instance of the class. Name 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' ] );

  run()
    Runs the bot. Hands the control over to the POE core.

METHODS TO OVERRIDE
    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.

  init()
    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.

  said($args)
    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)

    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.

  emoted( $args )
    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".

  chanjoin( $mess )
    Called when someone joins a channel. $mess is an object similar to a
    said() message, $mess->{who} is the nick of the user who joined,
    $mess->{channel} is the channel they joined.

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

  chanpart( $mess )
    Called when someone leaves a channel. $mess is an object similar to a
    said() message, $mess->{who} is the nick of the user who left,
    $mess->{channel} is the channel they left.

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

  got_names( $mess )
    Whenever we have been given a definitive list of 'who is in the
    channel', this function will be called. As usual, $mess is a hash.
    $mess->{channel} will be the channel we have information for,
    $mess->{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.

  topic( $mess )
    Called when the topic of the channel changes. $mess->{channel} is the
    channel the topic was set in, $mess->{who} is the nick of the user who
    changed the channel, and $mess->{topic} will be the new topic of the
    channel.

  nick_change( $mess )
    When a user changes nicks, this will be called. $mess looks like

      { from => "old_nick",
        to => "new_nick",
      }

  kicked( $mess )
    Called when a user is kicked from the channel. $mess looks like:

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

    The reply value is ignored.

  tick()
    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.

  help
    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.

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

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

  schedule_tick(time)
    Causes the tick event to be called in 'time' seconds (or 5 seconds if
    time is left unspecified). 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.

  forkit
    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.

    "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).

    body
        Optional. Use this to pass on the body of the incoming message that
        triggered you to fork this process. Useful for interactive proceses
        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( key => value, .. )
    Say something to someone. 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( key => value, .. )
    "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.

  reply($mess, $body)
    Reply to a message $mess. Will reply to an incoming message with the
    text '$body', in a privmsg if $mess was a privmsg, in channel if not,
    and prefixes if $mess was prefixed. Mostly a shortcut method - it's
    roughly equivalent to $mess->{body} = $body; $self->say($mess);

  channel_data
ATTRIBUTES
    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.

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

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

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

  alt_nicks
    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.

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

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

  channels
    The channels we're going to connect to.

  quit_message
    The quit message. Defaults to "Bye".

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

  charset
    IRC has no defined character set for putting high-bit chars into
    channel. In general, people tend to assume latin-1, but in case your
    channel thinks differently, the bot can be told about different
    charsets.

    This feature requires perl 5.8+, I'm not fannying about with charsets
    under any other version of perl.

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

STATES
    These are the POE states that we register in order to listen for IRC
    events. For the most part you don't need to worry about these, unless
    you want to override them to do something clever.

  start_state
    Called when we start. Used to fire a "connect to irc server event"

  reconnect
    Connects the bot to the IRC server. Called 1 second after the 'start'
    event.

    in an ideal world, this will never get called again - we schedule it for
    'x' seconds in the future, and whenever we see a server ping we reset
    this counter again. This means that it'll get run if we haven't seen
    anything from the server for a while, so we can assume that something
    bad has happened. At that point we shotgun the IRC session and restart
    everything, so we reconnect to the server.

    This is by far the most reliable way I have found of ensuring that a bot
    will reconnect to a server after it's lost a network connection for some
    reason.

    By default, the timeout is 300 seconds. It can be set by changing
    $Bot::BasicBot::RECONNECT_TIMEOUT.

  stop_state
    Called when we're stopping. Shutdown the bot correctly.

  irc_001_state
    Called when we connect to the irc server. This is used to tell the irc
    server that we'd quite like to join the channels.

    We also ignore ourselves. We don't want to hear what we have to say.

  irc_disconnected_state
    Called if we are disconnected from the server. Logs the error and
    schedules a reconnect event.

  irc_error_state
    Called if there is an irc server error. Logs the error and schedules a
    reconnect event.

  irc_kicked_state
    Called on kick. If we're kicked then it's best to do nothing. Bots are
    normally called in wrapper that restarts them if we die, which may end
    us up in a busy loop. Anyway, if we're not wanted, the best thing to do
    would be to hang around off channel.

  irc_join_state
    Called if someone joins. Used for nick tracking

  irc_nick_state
    Called if someone changes nick. Used for nick tracking.

  irc_mode_state
  irc_said_state
    Called if we recieve a private or public message. This formats it into a
    nicer format and calls 'said'

  irc_emoted_state
    Called if someone "emotes" on channel, rather than directly saying
    something. Currently passes the emote striaght to "irc_said_state" which
    deals with it as if it was a spoken phrase.

  irc_received_state
    Called by "irc_said_state" and "irc_emoted_state" in order to format
    channel input into a more copable-with format.

  irc_ping_state
    The most reliable way I've found of doing auto-server-rejoin is to
    listen for pings. Every ping we get, we put off rejoining the server for
    another few mins. If we haven't heard a ping in a while, the rejoin code
    will get called.

    Recently, I've adapted this for servers that don't send pings very
    often, and reset the counter any time _anything_ interesting happens.

    You can change the amount of time the bot waits between events before
    calling a reconnect event by changing $Bot::BasicBot::RECONNECT_TIMEOUT
    to a value in seconds. The default is '500'.

  irc_chanjoin_state
    Called if someone joins a channel.

  irc_chanpart_state
    Called if someone parts a channel.

  irc_chan_received_state
    Called by "irc_chanjoin_state" and "irc_chanpart_state" in order to
    format channel joins and parts into a more copable-with format.

  fork_close_state
    Called whenever a process forked by POE::Wheel::Run (in "forkit")
    terminates, and allows us to delete the object and associated data from
    memory.

  fork_error_state
    Called if a process forked by POE::Wheel::Run (in "forkit") hits an
    error condition for any reason. Does nothing, but can be overloaded in
    derived classes to be more useful

  tick_state
    the POE state for the tick event. Reschedules a tick event for the
    future if the tick method returned a value.

  names_state
  names_done_state
  topic_raw_state
  topic_state
OTHER METHODS
  AUTOLOAD
    Bot::BasicBot implements AUTOLOAD for sending arbitrary states to the
    underlying POE::Component::IRC compoment. So for a $bot object, sending

        $bot->foo("bar");

    is equivalent to

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

  log
    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 @_.

  ignore_nick($nick)
    Return true if this nick should be ignored. Ignores anything in the
    ignore list

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

  charset_decode( foo, bar, baz )
    Converts a string of bytes into a perl string, using the bot's charset.
    (under perls before 5.8, just returns the thing it's passed.

    Takes a list of strings, returns a list of strings, this is useful in
    the contexts that I tend to be calling it from. Bytes that cannot be
    decoded are converted to '?' symbols - see
    http://search.cpan.org/~dankogai/Encode-2.09/Encode.pm#Handling_Malforme
    d_Data

  charset_encode( foo, bar, baz )
    Converts a list of perl strings into a list of byte sequences, using the
    bot's charset. See charset_decode.

AUTHOR
    Tom Insam <tom@jerakeen.org>

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

CREDITS
    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 recieved 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.

SYSTEM REQUIREMENTS
    Bot::BasicBot is based on POE, and really needs the latest version as of
    writing (0.22), since POE::Wheel::Run (used for forking) is still under
    development, and the interface recently changed. With earlier versions
    of POE, forking will not work, and the makefile process will carp if you
    have < 0.22. Sorry.

    You also need POE::Component::IRC.

BUGS
    During the make, make test make install process, POE will moan about its
    kernel not being run. I'll try and gag it in future releases, but hey,
    release early, release often, and it's not a fatal error. It just looks
    untidy.

    Don't call your bot "0".

    Nick tracking blatantly doesn't work yet. In Progress.

    "fork_error_state" handlers sometimes seem to cause the bot to segfault.
    I'm not yet sure if this is a POE::Wheel::Run problem, or a problem in
    our implementation.

SEE ALSO
    POE, POE::Component::IRC

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

Something went wrong with that request. Please try again.