kibot.irclib
index
/usr/src/rpm/BUILD/kibot-0.0.12/kibot/irclib.py

irclib -- Internet Relay Chat (IRC) protocol client library.
 
This library is intended to encapsulate the IRC protocol at a quite
low level.  It provides an event-driven IRC client framework.  It has
a fairly thorough support for the basic IRC protocol and CTCP, but DCC
connection support is not yet implemented.
 
In order to understand how to make an IRC client, I'm afraid you more
or less must understand the IRC specifications.  They are available
here: [IRC specifications].
 
The main features of the IRC client framework are:
 
  * Abstraction of the IRC protocol.
  * Handles multiple simultaneous IRC server connections.
  * Handles server PONGing transparently.
  * Messages to the IRC server are done by calling methods on an IRC
    connection object.
  * Messages from an IRC server triggers events, which can be caught
    by event handlers.
  * Reading from and writing to IRC server sockets are normally done
    by an internal select() loop, but the select()ing may be done by
    an external main loop.
  * Functions can be registered to execute at specified times by the
    event-loop.
  * Decodes CTCP tagging correctly (hopefully); I haven't seen any
    other IRC client implementation that handles the CTCP
    specification subtilties.
  * A kind of simple, single-server, object-oriented IRC client class
    that dispatches events to instance methods is included.
 
Current limitations:
 
  * The IRC protocol shines through the abstraction a bit too much.
  * Data is not written asynchronously to the server, i.e. the write()
    may block if the TCP buffers are stuffed.
  * There are no support for DCC connections.
  * The author haven't even read RFC 2810, 2811, 2812 and 2813.
  * Like most projects, documentation is lacking...
 
Since I seldom use IRC anymore, I will probably not work much on the
library.  If you want to help or continue developing the library,
please contact me (Joel Rosdahl <joel@rosdahl.net>).
 
.. [IRC specifications] http://www.irchelp.org/irchelp/rfc/

 
Modules
       
bisect
re
select
socket
string
sys
time
types

 
Classes
       
Connection
DCCConnection
ServerConnection
Event
exceptions.Exception
IRCError
ServerConnectionError
IRC
SimpleIRCClient

 
class Connection
    Base class for IRC connections.
 
Must be overridden.
 
  Methods defined here:
__init__(self, irclibobj)
execute_at(self, at, function, arguments=())
execute_delayed(self, delay, function, arguments=())

 
class DCCConnection(Connection)
    Unimplemented.
 
  Methods defined here:
__init__(self)

Methods inherited from Connection:
execute_at(self, at, function, arguments=())
execute_delayed(self, delay, function, arguments=())

 
class Event
    Class representing an IRC event.
 
  Methods defined here:
__init__(self, eventtype, source, target, arguments=None)
Constructor of Event objects.
 
Arguments:
 
    eventtype -- A string describing the event.
 
    source -- The originator of the event (a nick mask or a server). XXX Correct?
 
    target -- The target of the event (a nick or a channel). XXX Correct?
 
    arguments -- Any event specific arguments.
arguments(self)
Get the event arguments.
eventtype(self)
Get the event type.
source(self)
Get the event source.
target(self)
Get the event target.

 
class IRC
    Class that handles one or several IRC server connections.
 
When an IRC object has been instantiated, it can be used to create
Connection objects that represent the IRC connections.  The
responsibility of the IRC object is to provide an event-driven
framework for the connections and to keep the connections alive.
It runs a select loop to poll each connection's TCP socket and
hands over the sockets with incoming data for processing by the
corresponding connection.
 
The methods of most interest for an IRC client writer are server,
add_global_handler, remove_global_handler, execute_at,
execute_delayed, process_once and process_forever.
 
Here is an example:
 
    irc = irclib.IRC()
    server = irc.server()
    server.connect("irc.some.where", 6667, "my_nickname")
    server.privmsg("a_nickname", "Hi there!")
    server.process_forever()
 
This will connect to the IRC server irc.some.where on port 6667
using the nickname my_nickname and send the message "Hi there!"
to the nickname a_nickname.
 
  Methods defined here:
__init__(self, fn_to_add_socket=None, fn_to_remove_socket=None, fn_to_add_timeout=None)
Constructor for IRC objects.
 
Optional arguments are fn_to_add_socket, fn_to_remove_socket
and fn_to_add_timeout.  The first two specify functions that
will be called with a socket object as argument when the IRC
object wants to be notified (or stop being notified) of data
coming on a new socket.  When new data arrives, the method
process_data should be called.  Similarly, fn_to_add_timeout
is called with a number of seconds (a floating point number)
as first argument when the IRC object wants to receive a
notification (by calling the process_timeout method).  So, if
e.g. the argument is 42.17, the object wants the
process_timeout method to be called after 42 seconds and 170
milliseconds.
 
The three arguments mainly exist to be able to use an external
main loop (for example Tkinter's or PyGTK's main app loop)
instead of calling the process_forever method.
 
An alternative is to just call ServerConnection.process_once()
once in a while.
add_global_handler(self, event, handler, priority=0)
Adds a global handler function for a specific event type.
 
Arguments:
 
    event -- Event type (a string).  Check the values of the
    numeric_events dictionary in irclib.py for possible event
    types.
 
    handler -- Callback function.
 
    priority -- A number (the lower number, the higher priority).
 
The handler function is called whenever the specified event is
triggered in any of the connections.  See documentation for
the Event class.
 
The handler functions are called in priority order (lowest
number is highest priority).  If a handler function returns
"NO MORE", no more handlers will be called.
disconnect_all(self, message='')
Disconnects all connections.
execute_at(self, at, function, arguments=())
Execute a function at a specified time.
 
Arguments:
 
    at -- Execute at this time (standard "time_t" time).
 
    function -- Function to call.
 
    arguments -- Arguments to give the function.
execute_delayed(self, delay, function, arguments=())
Execute a function after a specified time.
 
Arguments:
 
    delay -- How many seconds to wait.
 
    function -- Function to call.
 
    arguments -- Arguments to give the function.
process_data(self, sockets)
Called when there is more data to read on connection sockets.
 
Arguments:
 
    sockets -- A list of socket objects.
 
See documentation for IRC.__init__.
process_forever(self, timeout=0.20000000000000001)
Run an infinite loop, processing data from connections.
 
This method repeatedly calls process_once.
 
Arguments:
 
    timeout -- Parameter to pass to process_once.
process_once(self, timeout=0)
Process data from connections once.
 
Arguments:
 
    timeout -- How long the select() call should wait if no
               data is available.
 
This method should be called periodically to check and process
incoming data, if there are any.  If that seems boring, look
at the process_forever method.
process_timeout(self)
Called when a timeout notification is due.
 
See documentation for IRC.__init__.
remove_global_handler(self, event, handler)
Removes a global handler function.
 
Arguments:
 
    event -- Event type (a string).
 
    handler -- Callback function.
 
Returns 1 on success, otherwise 0.
server(self)
Creates and returns a ServerConnection object.

 
class IRCError(exceptions.Exception)
    Represents an IRC exception.
 
  Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
class ServerConnection(Connection)
    This class represents an IRC server connection.
 
ServerConnection objects are instantiated by calling the server
method on an IRC object.
 
  Methods defined here:
__init__(self, irclibobj)
action(self, target, action)
Send a CTCP ACTION command.
add_global_handler(self, *args)
Add global handler.
 
See documentation for IRC.add_global_handler.
admin(self, server='')
Send an ADMIN command.
close(self)
Close the connection.
 
This method closes the connection permanently; after it has
been called, the object is unusable.
connect(self, server, port, nickname, password=None, username=None, ircname=None)
Connect/reconnect to a server.
 
Arguments:
 
    server -- Server name.
 
    port -- Port number.
 
    nickname -- The nickname.
 
    password -- Password (if any).
 
    username -- The username.
 
    ircname -- The IRC name.
 
This function can be called to reconnect a closed connection.
 
Returns the ServerConnection object.
ctcp(self, ctcptype, target, parameter='')
Send a CTCP command.
ctcp_reply(self, target, parameter)
Send a CTCP REPLY command.
disconnect(self, message='')
Hang up the connection.
 
Arguments:
 
    message -- Quit message.
get_nickname(self)
Get the (real) nick name.
 
This method returns the (real) nickname.  The library keeps
track of nick changes, so it might not be the nick name that
was passed to the connect() method.
get_server_name(self)
Get the (real) server name.
 
This method returns the (real) server name, or, more
specifically, what the server calls itself.
globops(self, text)
Send a GLOBOPS command.
info(self, server='')
Send an INFO command.
invite(self, nick, channel)
Send an INVITE command.
is_connected(self)
Return connection status.
 
Returns true if connected, otherwise false.
ison(self, nicks)
Send an ISON command.
 
Arguments:
 
    nicks -- List of nicks.
join(self, channel, key='')
Send a JOIN command.
kick(self, channel, nick, comment='')
Send a KICK command.
links(self, remote_server='', server_mask='')
Send a LINKS command.
list(self, channels=None, server='')
Send a LIST command.
lusers(self, server='')
Send a LUSERS command.
mode(self, target, command)
Send a MODE command.
motd(self, server='')
Send an MOTD command.
names(self, channels=None)
Send a NAMES command.
nick(self, newnick)
Send a NICK command.
notice(self, target, text)
Send a NOTICE command.
oper(self, nick, password)
Send an OPER command.
part(self, channels)
Send a PART command.
pass_(self, password)
Send a PASS command.
ping(self, target, target2='')
Send a PING command.
pong(self, target, target2='')
Send a PONG command.
privmsg(self, target, text)
Send a PRIVMSG command.
privmsg_many(self, targets, text)
Send a PRIVMSG command to multiple targets.
process_data(self)
[Internal]
quit(self, message='')
Send a QUIT command.
sconnect(self, target, port='', server='')
Send an SCONNECT command.
send_raw(self, string)
Send raw string to the server.
 
The string will be padded with appropriate CR LF.
squit(self, server, comment='')
Send an SQUIT command.
stats(self, statstype, server='')
Send a STATS command.
time(self, server='')
Send a TIME command.
topic(self, channel, new_topic=None)
Send a TOPIC command.
trace(self, target='')
Send a TRACE command.
user(self, username, localhost, server, ircname)
Send a USER command.
userhost(self, nicks)
Send a USERHOST command.
users(self, server='')
Send a USERS command.
version(self, server='')
Send a VERSION command.
wallops(self, text)
Send a WALLOPS command.
who(self, target='', op='')
Send a WHO command.
whois(self, targets)
Send a WHOIS command.
whowas(self, nick, max='', server='')
Send a WHOWAS command.

Methods inherited from Connection:
execute_at(self, at, function, arguments=())
execute_delayed(self, delay, function, arguments=())

 
class ServerConnectionError(IRCError)
    
Method resolution order:
ServerConnectionError
IRCError
exceptions.Exception

Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
class SimpleIRCClient
    A simple single-server IRC client class.
 
This is an example of an object-oriented wrapper of the IRC
framework.  A real IRC client can be made by subclassing this
class and adding appropriate methods.
 
The method on_join will be called when a "join" event is created
(which is done when the server sends a JOIN messsage/command),
on_privmsg will be called for "privmsg" events, and so on.  The
handler methods get two arguments: the connection object (same as
self.connection) and the event object.
 
Instance attributes that can be used by sub classes:
 
    ircobj -- The IRC instance.
 
    connection -- The ServerConnection instance.
 
  Methods defined here:
__init__(self)
connect(self, server, port, nickname, password=None, username=None, ircname=None)
Connect/reconnect to a server.
 
Arguments:
 
    server -- Server name.
 
    port -- Port number.
 
    nickname -- The nickname.
 
    password -- Password (if any).
 
    username -- The username.
 
    ircname -- The IRC name.
 
This function can be called to reconnect a closed connection.
start(self)
Start the IRC client.

 
Functions
       
irc_lower(s)
Returns a lowercased string.
 
The definition of lowercased comes from the IRC specification (RFC
1459).
is_channel(string)
Check if a string is a channel name.
 
Returns true if the argument is a channel name, otherwise false.
mask_matches(nick, mask)
Check if a nick matches a mask.
 
Returns true if the nick matches, otherwise false.
nm_to_h(s)
Get the host part of a nickmask.
 
(The source of an Event is a nickmask.)
nm_to_n(s)
Get the nick part of a nickmask.
 
(The source of an Event is a nickmask.)
nm_to_u(s)
Get the user part of a nickmask.
 
(The source of an Event is a nickmask.)
nm_to_uh(s)
Get the userhost part of a nickmask.
 
(The source of an Event is a nickmask.)
parse_channel_modes(mode_string)
Parse a channel mode string.
 
The function returns a list of lists with three members: sign,
mode and argument.  The sign is "+" or "-".  The argument is
None if mode isn't one of "b", "k", "l", "v" or "o".
 
Example:
 
>>> irclib.parse_channel_modes("+ab-c foo")
[['+', 'a', None], ['+', 'b', 'foo'], ['-', 'c', None]]
parse_nick_modes(mode_string)
Parse a nick mode string.
 
The function returns a list of lists with three members: sign,
mode and argument.  The sign is "+" or "-".  The argument is
always None.
 
Example:
 
>>> irclib.parse_nick_modes("+ab-c")
[['+', 'a', None], ['+', 'b', None], ['-', 'c', None]]

 
Data
        DEBUG = 0
VERSION = (0, 3, 4)
all_events = ['disconnect', 'ctcp', 'ctcpreply', 'error', 'join', 'kick', 'mode', 'part', 'ping', 'privmsg', 'privnotice', 'pubmsg', 'pubnotice', 'quit', 'statskline', 'statsqline', 'statsnline', 'statsiline', 'statscommands', 'statscline', ...]
generated_events = ['disconnect', 'ctcp', 'ctcpreply']
nick_characters = r'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-[]\`^{}'
numeric_events = {'001': 'welcome', '002': 'yourhost', '003': 'created', '004': 'myinfo', '005': 'featurelist', '200': 'tracelink', '201': 'traceconnecting', '202': 'tracehandshake', '203': 'traceunknown', '204': 'traceoperator', ...}
protocol_events = ['error', 'join', 'kick', 'mode', 'part', 'ping', 'privmsg', 'privnotice', 'pubmsg', 'pubnotice', 'quit']