#rubyonrails api bot !usage
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


See leaves/rorapi.rb

there are also some ongoing mods in lib/leaf.rb

Ruby docs will be added shortly, along with the code to scrape and 
parse the online docs and generate up-to-date dump files.

= Autumn: A Ruby IRC Bot Framework
<b>Version 2.0.3 (Mar 22, 2008)</b>

Author::    Tim Morgan (mailto:riscfuture@gmail.com)
Copyright:: Copyright (c)2007-2008 Tim Morgan
License::   Distributed under the same terms as Ruby. Portions of this code are
            copyright (c)2004 David Heinemeier Hansson; please see
            libs/inheritable_attributes.rb for more information.

Autumn is a full-featured framework on top of which IRC bots (called "leaves")
can be quickly and easily built. It features a very Ruby-like approach to
bot-writing, a complete framework for loading and daemonizing your bots,
multiple environment contexts, a database-backed model, and painless logging

== Requirements

Autumn requires RubyGems (http://www.rubygems.org) and the Daemons and Facets*
gems. Install RubyGems then run <tt>sudo gem install daemons facets</tt> in a
command line in order to run Autumn.

If you wish to use a database backend for your bot, you will need the DataMapper
gem. To install:

 sudo gem install datamapper
 sudo gem install do_mysql # If you are using a MySQL database
 sudo gem install do_postgres # If you are using a PostgreSQL database
 sudo gem install do_sqlite3 # If you are using a SQLite database

The included example bot, Scorekeeper, requires the DataMapper gem. It can
optionally use the Chronic gem to enhance its textual date parsing.

== Directory Structure

An Autumn installation is like a Ruby on Rails installation: There is a
certain directory structure where your files go. A lot of files and folders will
seem confusing to people who have never used Autumn before, but bear with me. In
a bit I will explain in detail what all of this stuff is. For now, here is an
overview you can consult for future reference:

* <b>config/</b> - Configuration files and
  * global.yml - Universal settings that apply to every season
  * <b>seasons/</b> - Contains directories for each season (see "Seasons")
    * <b>testing/</b> - Example season
      * database.yml - Example database configuration file
      * leaves.yml - Example bot configuration file
      * season.yml - Season configuration
      * stems.yml - Example IRC configuration file
* <b>data/</b> - Not used by the program, but you can store your SQLite database
  files here.
* <b>doc/</b> - HTML documentation generated by RDoc
  * <b>api/</b> - Autumn API documentation
  * <b>leaves/</b> - Autumn leaves documentation
* <b>leaves/</b> - Autumn::Leaf subclasses
  * scorekeeper.rb - Example leaf provided with the installation
* <b>libs/</b> - Autumn core code
  * channel_leaf.rb - A leaf subclass that can ignore messages from certain
    channels its in
  * coder.rb - Used by script/generate to write out Ruby code
  * ctcp.rb - CTCP support library
  * daemon.rb - Provides support for different kinds of IRC servers
  * foliater.rb - Instantiates and manages stems and leaves
  * formatting.rb - Provides support for different kinds of IRC client text
    formatting and colorization
  * generator.rb - Library used by script/generate
  * genesis.rb - Boots the Autumn environment
  * inheritable_attributes.rb - Adds support for class-level inheritable
  * leaf.rb - The core bot superclass
  * log_facade.rb - Simplifies logging for stems and leaves
  * misc.rb - RubyCore class additions and other knick-knacks
  * script.rb - Library used by script/generate and script/destroy
  * speciator.rb - Manages global, season, stem, and leaf configurations
  * stem.rb - IRC client library
  * stem_facade.rb - Additional methods to simplify the Stem class
* <b>log/</b> - Directory where (most) Autumn logs are written (see the "Logs"
* Rakefile - Contains the rake tasks used to control Autumn (see the "Tasks"
* README - This file
* <b>resources/</b> - Data files used by Autumn
  * <b>daemons/</b> - Data files describing different IRC server types
* <b>script/</b> - Helper scripts for controlling Autumn
  * daemon - Runs Autumn as a daemon
  * destroy - Destroys Autumn objects
  * generate - Creates Autumn objects
  * server - Starts Autumn
* <b>support/</b> - Additional code your bots need
* <b>tmp/</b> - Temporary files, such as PID files

== Configuring Autumn for Your First Launch

Before you can run Autumn and try out the example leaf, Scorekeeper, you'll need
to set up a few things. Here are the steps:

=== Configure Your Testing Season

In Autumn, your leaves run in an environment, called a "season." Each season has
different leaves and different settings for those leaves. By default, Autumn
comes with a season called "testing" already set up for you. You can edit that
season or create a new one with <tt>script/generate season [season name]</tt>.

First, edit the stems.yml file. This file stores information about your IRC
connection. Edit it to connect to an IRC server of your choosing. For more
information, see "Stems" below.

Next, edit the database.yml file. As mentioned previously, Scorekeeper requires
the DataMapper gem because it uses a persistent store. By default it's set up to
use a MySQL database, but you can use PostgreSQL or SQLite 3 if you'd like. If
you'd prefer not to install any of these database solutions, please skip to
"Making Your Own Leaf," below, disable the Scorekeeper leaf, delete the
database.yml file, and then continue from here.

Lastly, view the leaves.yml file. You shouldn't have to make any changes to this
file, but it's a good idea to look at it to see how leaves are configured. You
can do the same with the season.yml file. See "Seasons" and "Leaves" below for

=== Starting the Server

Run the shell command <tt>script/server</tt> to start the server. After a short
while, your leaf should appear in the channel you specified. You can type
"!points Coolguy +5" and then "!points" to get started using it. Have some fun,
and when you're satisfied, stop the server by typing "!quit".

If you'd like to daemonize your server, you can use the shell commands <tt>rake
app:start</tt> and <tt>rake app:stop</tt>. For more information, see "Tasks"

== Making Your Own Leaf

Making your own leaf using Autumn is easy. In this tutorial, I'll show you how
to make a simple Fortune bot that responds to a few basic commands.

=== Step 1: Subclass Leaf

Create a new leaf by typing <tt>script/generate leaf fortune</tt>. This will
create a fortune.rb file in the leaves directory. Edit this file. First we'll
create an array to hold our fortunes:

   "You will make someone happy today.",
   "Someone you don't expect will be important to you today.",
   "Today will bring unexpected hardships."

As you can see, our 3 meager fortunes are stored in the +FORTUNES+ class
constant. Now, we'll want it to respond to the "!fortune" command, and all you
have to do is create a method called +fortune_command+ to make it work:

 def fortune_command(stem, sender, reply_to, msg)

The +at_rand+ method is provided by Facets, so you'll need to add a <tt>require
'facets/random'</tt> line at the top of your file. Our method returns a fortune
at random, which is automatically transmitted to the channel or nick where the
command was received.

Of course, any self-respecting fortune bot announces its presence when it starts
up, so, in your +Fortune+ class, override the Autumn::Leaf#did_start_up method
to display a cheerful greeting:

 def did_start_up
   stems.message 'FortuneBot at your service! Type "!fortune" to get your fortune!'

...and that's it! You now have a fully functional fortune bot featuring -- not
two -- but <i>three</i> unique and exciting fortunes!

(For more on that <tt>stems.message</tt> bit, see "Stems.")

=== Step 2: Add the Leaf to Your Season

If you want, you can add the fortune bot to your leaves.yml and stems.yml files
to try it out. Adding a leaf is easy; simply duplicate the structure used for
Scorekeeper's entry and change the values as appropriate. A typical two-leaf
configuration will look like:

   class: Scorekeeper
   respond_to_private_messages: false
   class: Fortune
   respond_to_private_messages: true

As you notice, each leaf is given a name. In this example the name happens to be
the same as the leaf's _class_ name, but you could run two copies of a leaf like

   class: Fortune
   class: Fortune

We've created the leaf, but we have to add it to the stem for it to work.
(Remember, a stem is an IRC connection and a leaf is a bot.) So, in your
stems.yml file, add an entry for this leaf. Your new config will appear
something like:

   nick: Scorekeeper
     - Scorekeeper
     - Fortune
   rejoin: true
   channel: somechannel
   server: irc.someserver.com

When you restart the server, Scorekeeper will come back online but will now
also respond to the "!fortune" command. This is a helpful tutorial on how stems
and leaves are separate. One leaf can have many stems, and one stem can have
many leaves. You can combine these two entities however you need.

== Seasons

Each time you start Autumn with the rake task, the process launches in a certain
season (a.k.a. environment context). This season is defined in the
config/global.yml file. You can temporarily override it by setting the +SEASON+
environment variable (e.g., <tt>SEASON=production script/server</tt>).

It's important to realize that an season is just a name, nothing more. You can
have as many seasons as you like, and name them anything that you like. Autumn
will load the config files for the season you've indicated as active. Autumn
doesn't really care if it's named "production" or "live" or
"testing-on-jeffs-machine"; it's all the same to Autumn.

Your season's configuration is stored in the season.yml file within your season
directory. Currently it supports one directive, +logging+. When set to "debug",
the logger will log all messages, and will parrot output to the console. When
set to "production", the logger will not log debug messages, and will not parrot
to the console. (See the "Logging" section.)

The power of seasons comes in custom configuration options. For instance,
consider that you have a testing and production season. In your testing season,
your season.yml file contains:

 dont_http: true

and in production, it contains:

 dont_http: false

Now, in your code, you might have a method like:

 def scores_command(stem, sender, reply_to, msg)
   if options[:dont_http] then
     return "Some fake sports scores."
     # go on the web and find real sports scores

=== Standard Configuration Options

==== Global

System-wide configuration is done in the config/global.yml file. It supports by
default the following directives:

+season+:: The season to launch in.
+log_history+:: The number of historical logfiles to keep.

In addition, the following options are available (but cannot be set in the yml

+root+:: The root directory of the Autumn installation.
+system_logger+:: The Autumn::LogFacade instance that records system messages.

==== Season

Season-specific configuration is done in the config/seasons/[season]/season.yml
file. Currently it only supports one directive, +logging+. When set to +debug+,
the logger will log all messages and parrot to stdout.

==== Stem

Stem-specific configuration is done in the config/seasons/[season]/stems.yml
file. It's important to note that stem and leaf configurations are completely
independent of each other. (In other words, stem options do not override leaf
options, nor vice versa.) Therefore, you generally won't add custom directives
to the stems.yml file, because you generally won't be working with stems
directly. The standard options are:

+server+:: The address of the IRC server.
+port+:: The IRC server port (default 6667).
+nick+:: The nick to request.
+password+:: The nick's password, if it is registered.
+channel+:: A channel to join.
+channels+:: A list of channels to join.
+leaf+:: The name of a leaf to run.
+leaves+:: A list of leaves to run. (These are the names of leaf configurations
           in leaves.yml, not leaf subclasses.)
+rejoin+:: If true, the stem will rejoin any channels it is kicked from.
+server_password+:: The password for the IRC server, if necessary.
+ssl+:: If true, the connection to the IRC server will be made over SSL.
+server_type+:: The IRC server type. See resources/daemons for a list of valid
                server types. If you do not manually set this value, it will be
                guessed automatically.
+case_sensitive_channel_names+:: If true, channel names will be compared with
                                 case sensitivity.
+dont_ghost+:: If true, the stem will not try to GHOST a registered nick if it's
+ghost_without_password+:: If true, the stem will use the GHOST command without
                           a password. Set this for servers that use some other
                           form of nick authentication, such as hostname-based.
+user+:: The username to send (optional).
+name+:: The user's real name (optional).

The +channel+ and +channels+ directives can also be used to specify a password
for a password protected channel, like so:

   channelname: channelpassword


 - channel1: password1
 - channel2: password2

The +port+, +server_type+, and <tt>channel</tt>/<tt>channels</tt> options are
set in the config file but not available in the +options+ hash. They are
accessed directly from attributes in the Stem instance, such as the +channels+

==== Leaf

Leaf-specific configuration is done in the config/seasons/[season]/leaves.yml
file. As mentioned above, leaf and stem configurations are completely separate,
so one does not override the other. The standard options are:

+class+:: The Autumn::Leaf subclass running this leaf. It must be a file in the
          leaves directory, named after the class (lowercase and underscored).
+command_prefix+:: The text that must precede each command. Defaults to "!".
+respond_to_private_messages+:: If true, the leaf will parse commands in
                                whispers, and respond over whispers to those
+database+:: A database connection to use (as defined in database.yml). By
             default Autumn will choose a connection named after your leaf.
+formatter+:: The name of a module in Autumn::Formatting that will handle output
              formatting and colorization. This defaults to mIRC-style

=== Custom Configuration Options

All configuration files support user-generated directives. You can set options
at any level. Options at a more narrow level override those at a broader level.

Options are maintained and cataloged by the Autumn::Speciator singleton. You
could access the singleton directly, but most objects have a +config+ or
+options+ attribute providing simpler access to the Speciator.

For example, to access options in a leaf, all you do is call, for example,
<tt>options[:my_custom_option]</tt>. +my_custom_option+ can be set at the
global, season, or leaf level.

== Leaves

The Autumn::Leaf class has many tools to help you write your leaves. These
include things like filters, helpers, loggers, and an easy to use IRC library.
The Autumn::Leaf and Autumn::Stem class docs are the most thorough way of
learning about each of these features, but I'll walk you through the basics

=== The Many Methods of Leaf

By subclassing Autumn::Leaf, you gain access to a number of neat utilities.
These generally come in three classes: IRC commands that have already been
written for you, utility methods you can call, and invoked methods you can
override. Helper methods do things like add filters. Invoked methods are called
when certain events happen, like when your leaf starts up or when a private
message is received. You override them in your leaf to customize how it responds
to these events.

<b>Invoked methods</b>:: +will_start_up+, +did_start_up+,
                         +did_receive_channel_message+, etc.
<b>Utility methods</b>:: +before_filter+, +database+
<b>IRC commands</b>:: +quit_command+, +reload_command+, +autumn_command+, etc.

See the class docs for more information on these methods.

In addition, your leaf is designated as a listener for its Autumn::Stem
instances. In short, this means if you want even finer control over the IRC
connection, you can implement listener methods. See the
Autumn::Stem#add_listener method for examples of such methods.

Finally, your leaf can implement methods that are broadcast by listener plugins.
An example of such a plugin is the Autumn::CTCP class, which is included in all
stems by default. Visit its class docs to learn more about how to send and
receive CTCP requests.

=== Filters

Filters are methods that are run either before or after a command is executed.
In the former case, they can also prevent the command from being run. This is
useful for authentication, for instance: A filter could determine if someone is
authorized to run a command, and prevent the command from being run if not.

Use filters to save yourself the effort of rewriting code that will run before
or after a command is executed. Filter methods are named <tt>[word]_filter</tt>
and they are added to the filter chain using the +before_filter+ and
+after_filter+ methods (like in Ruby on Rails). As an example, imagine you
wanted your bot to say something after each command:

 class OutroLeaf > Autumn::Leaf
   after_filter :outro
   def outro_filter(stem, channel, sender, command, msg, opts)
     stem.message "This has been a production of OutroBot!", channel

The result of this is that after each command, the leaf will make a dramatic
exit. (Why did I use +after_filter+ and not +before_filter+? Because as I said
earlier, a +before_filter+ can stop the command from being executed; the only
way we know for sure that the command was executed -- and therefore should be
outroed -- is to use an +after_filter+.)

I made the +outro_filter+ method private because I felt it shouldn't be exposed
to other classes; this is not a requirement of the filter framework, though.

Now let's say you wanted to prevent the command from being run in some cases.
The most obvious application of this feature is authentication: You don't want
just any person to run your leaf's administrative commands. So, you write a
+before_filter+ to determine if the user is authenticated.
<tt>before_filter</tt>s have return values; if they return false, the filter
chain is halted and the command is suppressed. If you want to have your leaf
display some sort of message (like "Nice try!"), you need to include that in
your filter.

As an example, here's a simple form of authentication that just checks a
person's nick:

 class MyLeaf < Autumn::Leaf
   before_filter :authenticate, :only => :quit, :admin => 'Yournick'
   def authenticate_filter(stem, channel, sender, command, msg, opts)
     sender == opts[:admin]

I'm introducing you to three new features with this sample:

* You can use the <tt>:only</tt> option to limit your filter to certain
  commands. Note that you specify the _command_ name as a symbol, _not_ the
  method name (which would be +quit_command+ in this case).
* You can pass your own options to +before_filter+ and +after_filter+; they are
  passed through to your method via the last parameter, +opts+.
* The return value of a +before_filter+ is used to determine if the command
  should be run. So be careful that your method does not return nil or false
  unless you really mean for the command to be suppressed.

Both of these examples use the parameters sent to your filter method. They are,
in order:

1. the Autumn::Stem instance that received the command,
2. the name of the channel to which the command was sent (or nil if it was a
   private message),
3. the sender hash,
4. the name of the command that was typed, as a symbol,
5. any additional parameters after the command (same as the +msg+ parameter in
   the <tt>*_command</tt> methods),
6. the custom options that were given to +before_filter+ or +after_filter+.

There are two built-in options that you can specify for +before_filter+ and
+after_filter+, and those are +only+ and +except+. They work just like in Rails:
The +only+ option limits the filter to running only on the given command or list
of commands, and the +except+ option prevents the filter from being run on the
given command or list. All other options are passed to the filter for you to

Filters are run in the order they are added to the filter chain. Therefore, a
superclass's filters will run before a subclass's filters, and filters added
later in a class definition will be run after those added earlier.

If you subclass one of your leaves, it inherits your superclass's filters. The
Autumn::Leaf superclass does not have any filters by default, though by default
new leaves come with a simple authentication filter that checks the user's
privilege level.

=== Persistent Stores

If you would like to use a persistent store for your leaf, you should install
the DataMapper gem and a DataObjects gem for your database of choice (MySQL,
PostgreSQL, or SQLite). DataMapper works almost identically to ActiveRecord, so
if you have any Rails programming experience, you should be able to dive right

Once you've got DataMapper installed, you should create one or more database
connections in your config/seasons/[season]/database.yml file. A sample database
connection looks like:

   adapter: mysql
   host: localhost
   username: root
   password: pass
   database: database_name

If you are using the "sqlite3" adapter, the +database+ option is the path to the
file where the data should be written (example: data/my_database.db). You can
name your connection however you want, but you _should_ name it after either
your leaf or your leaf subclass. (More on this below.)

You should also create <tt>DataMapper::Base</tt> subclasses for each of your
model objects. You can place them within your leaf's support directory. This
works almost exactly the same as the app/models directory in Rails.

Once your database, data models, and leaves have been configured, you can use
the <tt>rake db:create</tt> and <tt>rake db:populate</tt> tasks to automatically
set up your database.

Now, unlike Rails, Autumn supports multiple database connections. Two leaves can
use two different database connections, or share the same database connection.
Because of this, it's important to understand how to manage your connections.
Autumn tries to do this for you by guessing which connection belongs to which
leaf, based on their names.

For example, imagine you have a leaf subclass named +Fortune+ and a
configuration in leaves.yml named "MyFortune". If you name your database
connection either "Fortune" or "MyFortune" (or "fortune" or "my_fortune"), it
will automatically be associated with that leaf. What this means is that for the
leaf's command methods (such as +about_command+) and invoked methods (such as
+did_receive_private_message+), the database connection will already be set for
you, and you can start using your DataMapper objects just like ActiveRecord

If, on the other hand, you either <b>named your database connection differently
from your leaf or subclass name</b> or you <b>are writing a method outside of
the normal flow of leaf methods</b> (for instance, one that is directly called
by a Stem, or a different listener), you will need to call the +database+ method
and pass it a block containing your code.

This is terribly confusing, so let me give you an example. Let's assume you've
got a fortune bot running off of a +FortuneLeaf+ subclass, so your leaf
configuration is:

   class: FortuneLeaf

And you have a database connection for that leaf, named after the leaf's class:

   adapter: sqlite3
   database: data/fortune.db

Let's further assume you have a simple DataMapper object:

 class Fortune < DataMapper::Base
   property :text, :string

Now, if we wanted to write a "!fortune" command, it would appear something like

 def fortune_command(stem, sender, reply_to, msg)
   fortunes = Fortune.all

Autumn automatically knows to execute this DataMapper code in the correct
database context. It knows this because your leaf's class is +FortuneLeaf+, and
your database context is named the same.

But what if you wanted to use that connection for other leaves too, so you named
it something like "local_database"? Now, Autumn won't be able to guess that you
want to use that DB context, so you have to specify it manually:

 def fortune_command(stem, sender, reply_to, msg)
   database(:local_database) do
     fortunes = Fortune.all
     return fortunes[rand(fortunes.size)].text

If that is too tedious, you can specify the database connection manually in the
leaves.yml file:

   class: FortuneLeaf
   database: local_database

OK, now onto the second special case. Imagine you want your fortune bot to also
send a fortune in response to a CTCP VERSION request. So, you'd implement a
method like so:

 def ctcp_version_request(handler, stem, sender, arguments)
   fortune = random_fortune # Loads a random fortune
   send_ctcp_reply stem, sender[:nick], 'VERSION', fortune.text

This will break -- why? Because the +ctcp_version_request+ method is in the
realm of the Autumn::CTCP class, _not_ the Autumn::Leaf class. (You can see this
by investigating the CTCP class docs; it shows you what methods you can
implement for CTCP support.) Basically, the CTCP class calls your method
directly, giving the Autumn::Leaf class no chance to set up the database first.
So to fix it, make a call to +database+ first:

 def ctcp_version_request(handler, stem, sender, arguments)
   database do
     fortune = random_fortune # Loads a random fortune
     send_ctcp_reply stem, sender[:nick], 'VERSION', fortune.text

This will execute those methods in the scope of the database connection guessed
by Autumn::Leaf. Of course, you can manually pass in a connection name if

=== Using Support Modules

Helper modules placed in the support/ directory will automatically be loaded and
included in your leaf classes. To create a helper module, create a subdirectory
within the support folder named after your leaf class. In there, you can place
Ruby files that will be loaded. Name your helper modules after your leaf class,
in the pattern of "<Leaf Name><Helper Name>Helper".

For instance, if your leaf class is +Fortune+, and you needed two helpers, a
database helper and a network helper, you could create two modules named
+FortuneDatabaseHelper+ and +FortuneNetworkHelper+. If you only needed on
helper, you could name the module +FortuneHelper+. These modules should be
defined in Ruby source files within the support/fortune directory. Any modules
named in this fashion and defined in that location will be loaded and appended
to the +Fortune+ class automatically.

If you are using DataMapper, you can also place your leaf's DataMapper objects
in the support directory.

=== Debugging Your Leaf

If you make a simple code change to your leaf, you can reload it without having
to restart the whole process. See the Autumn::Leaf#reload_command documentation
for more information on when and how you can reload your leaf's code.

If an error occurs on a live production instance, it will be logged to the
log file for your season and the leaf will exit. You can inspect the log file
to determine what went wrong.

If the error happens before the logger is available, oftentimes it will appear
in the autumn-leaves.output or autumn-leaves.log files. These files are
generated by the daemon library and note any uncaught exceptions or standard

The most tricky of errors can happen before the process is daemonized. If your
process is quitting prematurely, and you don't see anything in either log file,
consider running <tt>script/server</tt>, allowing you to see any exceptions for

Unfortunately, it's still possible that the bug might not appear when you do
this, but only appear when the process is daemonized. In this situation, I'd
recommend installing rdebug (<tt>sudo gem install rdebug</tt>) and stepping
through the code to figure out what's going wrong. In particular, make sure you
step into the Foliater's +start_stems+ method, when it creates the new threads.
It's possible your exception will rear its head once you step into that line of

== Stems

Autumn::Stem is a full-featured IRC client library, written from the ground up
for Autumn. It makes extensive use of implicit protocols, meaning that most
features are accessed by implementing the methods you feel are necessary.

Most of the time, you will only work with stems indirectly via leaves. For
instance, if you want an "!opped" command that returns true if the sender is an
operator, it would look like this:

 def opped_command(stem, sender, reply_to, msg)
   stem.channel_members[reply_to][sender[:nick]] == :operator ? "You are opped." : "You are not opped."

Let's break this down. In order to figure out if someone is opped or not, we
need three pieces of information: their nick, the channel they are in, and the
IRC server they are connected to.

The +stem+ variable contains the Autumn::Stem instance that received this
message. It is our link to that server. Through it we can perform IRC actions
and make requests.

Autumn::Stem includes an attribute +channel_members+, a hash of channels mapped
to their members. The channel that received the message is passed via the
+reply_to+ parameter. So we call <tt>channel_members[reply_to]</tt> and we
receive a hash of member names to their privilege levels. The +sender+ parameter
contains information about the person who sent the command, including their
nick. So we use their nick to resolve their privilege level.

Complicated? Sure it is. That's the price we pay for separating stems from
leaves. But what if you, like probably 90% of the people out there who use
Autumn, only have one stem? Why should you have to call the same damn stem each
and every time?

Fortunately, your pleas are not in vain. For leaves that run off only one stem,
the stem's methods are rolled right into the leaf. So, that "!opped" command
method becomes:

 def opped_command(stem, sender, reply_to, msg)
   channel_members[reply_to][sender[:nick]] == :operator ? "You are opped." : "You are not opped."

OK, so it's not like a world-class improvement, but it helps.

The primary thing your leaf will probably do with a Stem instance is use it to
send messages, like so:

 def about_command(stem, sender, reply_to, msg)
   stem.message "I am a pretty awesome bot!", reply_to

Fortunately, if you just return a string, Autumn::Leaf will automatically send
it for you, simplifying our method:

 def about_command(stem, sender, reply_to, msg)
   "I am a pretty awesome bot!"

You would still interact with the stem directly if you wanted to do something
like announce your leaf's presence to everyone. To do this, you'd have to send
a message to every channel of every stem the leaf is a listener for:

 stems.each { |stem| stem.channels.each { |channel| stem.message "Hello!", channel } }

But! Autumn::Stem#message will automatically send a message to every channel if
you don't specify any channels, simplifying our code to:

 stems.each { |stem| stem.message "Hello!" }

It gets even better. <b>You can call methods on the +stems+ array as if it were
a stem itself!</b> This simplifies the line significantly:

 stems.message "Hello!"

Pretty nifty, huh? This also works for functions as well as methods; for
instance, the Autumn::Stem#ready? function, which returns true if a stem is

 stems.ready? #=> [ true, true, false, true ] (for example)

=== The nitty-gritty of stems

The section above dealt with stems as they relate to leaves. But when would you
need to deal with a stem directly? Generally, never. However, if you find
that Autumn::Leaf doesn't have what you need, you may have to turn to
Autumn::Stem to get the functionality you are looking for. So let's take a look
at how Stem works.

A stem interacts with interested parties via the _listener_ protocol. Your leaf
signals its interest to a stem by calling Autumn::Stem#add_listener. When a leaf
or any other object becomes a stem's listener, that stem then invokes methods on
the listener whenever an IRC event occurs.

Let's take a simple example. Assume you wanted to build a basic textual IRC
client using Stem. You'd first want to indicate that your client is a listener:

 class MyClient
   def initialize(stem)
     @stem = stem
     @stem.add_listener self

Now the stem will send method calls to your +MyClient+ instance every time an
IRC event occurs. None of these methods are required -- you can implement as few
or as many as you want. The different methods that Stem will send are documented
in the Autumn::Stem#add_listener method docs. One very important method is the
+irc_privmsg_event+ method. Let's implement it:

 def irc_privmsg_event(stem, sender, arguments)
   puts "#{arguments[:channel]} <#{sender[:nick]}> #{arguments[:message]}"

Now we've got the most important part of our IRC client done -- receiving

You can also send IRC events using stem. It's simple: Every IRC command (such as
JOIN and PRIVMSG and MODE) has a corresponding method in Stem (such as +join+
and +privmsg+ and +mode+). These methods aren't in the API docs because they're
implemented using +method_missing+. Their arguments are exactly the same as the
arguments the IRC command expects, and in the same order.

So how do we send a message? Well according to RFC-1459, the basic IRC spec, the
PRIVMSG command takes two arguments: a list of receivers, and the text to be
sent. So, we know our method call should look something like this:

 @stem.privmsg recipient, message

Astute readers will note that the spec shows a _list_ of recipients, and indeed,
you can call the method like so:

 @stem.privmsg [ recipient1, recipient2 ], message

That's the basics of how Autumn::Stem works, but there's one other thing worth
mentioning, and that's listener plugins. The details are in the
Autumn::Stem#add_listener method docs, but the short of it is that these are
special listeners that bestow their powers onto other listeners.

The best example of this is the Autumn::CTCP class. This class is indeed a Stem
listener: It listens to PRIVMSG events from the stem, and checks them to see if
they are CTCP requests. However, it _also_ gives you, the author of another
listener (such as your leaf) the ability to implement methods according to _its_

For example, say you wanted to respond to CTCP VERSION requests with your own
version information. You do it like so:

 def ctcp_version_request(handler, stem, sender, arguments)
   send_ctcp_reply stem, sender[:nick], 'VERSION', "AwesomeBot 2.0 by Sancho Sample"

What's going on here? Because the Autumn::CTCP class is a listener plugin, it is
sending its own method calls as well as implementing Stem's method calls. One
such call is the +ctcp_version_request+ method, which you can see in the CTCP
class docs. Somewhere deep in the annals of Autumn::Foliater, there is some code
similar to the following:

 ctcp = Autumn::CTCP.new
 stem.add_listener ctcp

Thus, every stem comes pre-fab with a CTCP listener plugin. That plugin is
intercepting PRIVMSG events and checking if they're CTCP requests. If they are,
it is invoking methods, such as +ctcp_version_request+, in all of the stem's
other listeners, among which is your leaf. Hopefully you understand how this all
fits together.

The lesson to take home here is two-fold: Firstly, if you'd like CTCP support in
your leaf, know that it's the Autumn::CTCP class that is providing the method
calls to your leaf, not the Autumn::Stem class. Secondly, this should hopefully
give you some ideas should you want to write your own listener plugin to enhance
Stem's functionality.

== Autumn's Logging

Autumn uses Ruby's Logger class to log; however, it uses Autumn::LogFacade to
prepend additional information to each log entry. The LogFacade class has the
exact same external API as Logger, so you can use it like a typical Ruby or
Ruby on Rails logger. Many objects (such as Leaf and Stem) include a +logger+

 logger.debug "Debug statement"
 logger.fatal $!

See the LogFacade class docs for details.

== Tasks

The included Rakefile contains a number of useful tasks to help you develop and
deploy your leaves. You can always get a list of tasks by typing
<tt>rake -T</tt>. The various commands you can run are:

Application tasks:

* <b>rake app:start</b> - Starts the Autumn daemon in the background.
* <b>rake app:stop</b> - Stops the Autumn daemon.
* <b>rake app:restart</b> - Reloads the Autumn daemons.
* <b>rake app:run</b> - Starts the Autumn daemon in the foreground.
* <b>rake app:zap</b> - Forces the daemon to a stopped state. Use this command
  if your daemon is not running but script/daemon thinks it still is.

Database tasks:

* <b>LEAF=[leaf name] rake db:create</b> - Creates an empty database for the
* <b>LEAF=[leaf name] rake db:drop</b> - Drops a leaf's database.
* <b>LEAF=[leaf name] rake db:populate</b> - Creates all the tables for a leaf,
  as specified by the leaf's model objects (in its support directory).

Documentation tasks:

* <b>rake doc:api</b> - Generates HTML documentation for Autumn, found in the
  doc/api directory.
* <b>rake doc:leaves</b> - Generates HTML documentation for your leaves, found
  in the doc/leaves directory.
* <b>rake doc:clear</b> - Removes all HTML documentation.

Logging tasks:

* <b>rake log:clear</b> - Clears the log files for all seasons
* <b>rake log:errors</b> - Prints a list of error-level log messages for the
  current season, and uncaught exceptions in all seasons

== Scripts

Autumn includes four scripts to help you control it.

=== script/daemon

Controller for the Autumn daemon. Starts, stops, and manages the daemon. Must be
run from the Autumn root directory.

Usage: script/daemon <command> <options> -- <application options>

where <command> is one of:

+start+:: start an instance of the application
+stop+:: stop all instances of the application
+restart+:: stop all instances and restart them afterwards
+run+:: start the application and stay on top
+zap+:: set the application to a stopped state

and where <options> may contain several of the following:

<tt>-t, --ontop</tt>:: Stay on top (does not daemonize)
<tt>-f, --force</tt>:: Force operation

Common options:

<tt>-h, --help</tt>:: Show this message
<tt>--version</tt>:: Show version

=== script/destroy

Destroys the files for leaves, seasons, and other objects of the Autumn

Usage: script/destroy <options> <object> <name>

<object>:: The object type to destroy. Valid types are "leaf" and "season".
<name>:: The name of the object to destroy. For example, you can call
         "script/destroy leaf Scorekeeper" to remove a leaf named Scorekeeper.

<tt>--help, -h</tt>:: Displays this usage information.
<tt>--vcs, -c</tt>:: Remove any created files or directories from the project's
                     version control system. (Autodetects CVS and Subversion.)

=== script/generate

Generates template files for leaves, seasons, and other Autumn objects.

Usage: script/generate <options> <template> <name>

<template>:: The template to create. Valid templates are "leaf" and "season".
<name>:: The name to give the created template. For example, you can call
         "script/generate leaf Scorekeeper" to create a leaf named Scorekeeper.

<tt>--help, -h</tt>:: Displays this usage information.
<tt>--vcs, -c</tt>:: Add any created files or directories to the project's
                     version control system. (Autodetects CVS and Subversion.)

=== script/server

Runs Autumn from the command line. This script will not exit until all leaves
have exited. You can set the SEASON environment variable to override the season.

== Thread Safety

Autumn is a multi-threaded IRC client. When a message is received, a new thread
is spawned to process the message. In this thread, the message will be parsed,
and all listener hooks will be invoked, including your leaf's methods. The
thread will terminate once the message has been fully processed and all methods

I have made every effort to ensure that Autumn::Stem and Autumn::Leaf are
thread-safe, as well as other relevant support classes such as Autumn::CTCP. It
is now in your hands to ensure your leaves are thread-safe! This basically means
recognizing that, while your leaf is churning away at whatever command it
received, things can and will change in the background. If your command requires
your leaf to have operator privileges, write your code under the assumption that
operator could be taken from your leaf in the middle of executing the command.
Write data in critical blocks, use transactions in your database calls ... you
know the deal. Don't assume things will be the same between one line of code and
the next.

== Getting Ready for Deployment

There's only a few things you need to do once your leaf is ready to greet
the Real World:

1. Create a new production season. Configure your stems, leaves, and database
   as necessary for your production environment.
2. In config/global.yml, set the season to your production season.
3. If desired, in script/daemon, set the <tt>:monitor</tt> option to true. This
   will spawn a monitor process that will relaunch Autumn if it crashes.

== Other Information

Please see http://code.google.com/p/autumn-leaves/wiki/KnownBugs for a list of
known bugs, and http://code.google.com/p/autumn-leaves/wiki/VersionHistory for
complete version history.

*<i>Why do you require Facets?</i>, I hear you ask. Facets doesn't add any super
awesome new features to Ruby like Daemons or DataMapper does. It does, however,
improve code reuse, and I'm a big fan of that. Why should a million different
Ruby projects all write the same <tt>Symbol#to_proc</tt> method or the same
<tt>Hash#symbolize_keys</tt> method? I use Facets because that job has already
been done, and staying DRY means staying DRY _between_ codebases, not just
within them.