irc package

Submodules module

Simple IRC bot library.

This module contains a single-server IRC bot class that can be used to write simpler bots.


Bases: object

A class for keeping information about an IRC channel.


Returns an unsorted list of the channel’s admins.

change_nick(before, after)[source]
clear_mode(mode, value=None)[source]

Clear mode on the channel.


mode – The mode (a single-character string).

value – Value


Returns an unsorted list of the channel’s half-operators.


Check whether the channel has a user.


Check whether a user has admin status in the channel.


Check whether a user has half-operator status in the channel.


Check whether a user has operator status in the channel.


Check whether a user has owner status in the channel.


Check whether a user has voice mode set in the channel.


Returns an unsorted list of the channel’s operators.


Returns an unsorted list of the channel’s owners.

set_mode(mode, value=None)[source]

Set mode on the channel.


mode – The mode (a single-character string).

value – Value

set_userdetails(nick, details)[source]
user_modes = 'ovqha'

Modes which are applicable to individual users, and which should be tracked in the mode_users dictionary.


Returns an unsorted list of the channel’s users.


Returns an unsorted list of the persons that have voice mode set in the channel.



A ReconnectStrategy implementing exponential backoff with jitter.

max_interval = 300
min_interval = 60

Bases: object

An abstract base class describing the interface used by SingleServerIRCBot for handling reconnect following disconnect events.


Invoked by the bot on disconnect. Here a strategy can determine how to react to a disconnect.

class, port=6667, password=None)[source]

Bases: object

An IRC server specification.

>>> spec = ServerSpec('localhost')
>>> spec.port
>>> spec.password
>>> spec = ServerSpec('', 6697, 'fooP455')
>>> spec.password
class, nickname, realname, reconnection_interval=<object object>, recon=< object>, **connect_params)[source]

Bases: irc.client.SimpleIRCClient

A single-server IRC bot class.

The bot tries to reconnect if it is disconnected.

The bot keeps track of the channels it has joined, the other clients that are present in the channels and which of those that have operator or voice modes. The “database” is kept in the self.channels attribute, which is an IRCDict of Channels.


server_list – A list of ServerSpec objects or tuples of
parameters suitable for constructing ServerSpec objects. Defines the list of servers the bot will use (in order).

nickname – The bot’s nickname.

realname – The bot’s realname.

recon – A ReconnectStrategy for reconnecting on
disconnect or failed connection.
dcc_connections – A list of initiated/accepted DCC
**connect_params – parameters to pass through to the connect
die(msg='Bye, cruel world!')[source]

Let the bot die.


msg – Quit message.
disconnect(msg="I'll be back!")[source]

Disconnect the bot.

The bot will try to reconnect after a while.


msg – Quit message.

Returns the bot version.

Used when answering a CTCP VERSION request.

jump_server(msg='Changing servers')[source]

Connect to a new server, possibly disconnecting from the current.

The bot will skip to next server in the server_list each time jump_server is called.

on_ctcp(c, e)[source]

Default handler for ctcp events.

Replies to VERSION and PING requests and relays DCC requests to the on_dccchat method.

on_dccchat(c, e)[source]

Start the bot.

irc.client module

Internet Relay Chat (IRC) protocol client library.

This library is intended to encapsulate the IRC protocol in Python. It provides an event-driven IRC client framework. It has a fairly thorough support for the basic IRC protocol, CTCP, and DCC chat.

To best understand how to make an IRC client, the reader 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:

  • Data is not written asynchronously to the server, i.e. the write() may block if the TCP buffers are stuffed.
  • DCC file transfers are not supported.
  • RFCs 2810, 2811, 2812, and 2813 have not been considered.
  • connection.quit() only sends QUIT to the server.
  • ERROR from the server triggers the error event and the disconnect event.
  • dropping of the connection triggers the disconnect event.
class irc.client.Connection(reactor)[source]

Bases: object

Base class for IRC connections.

execute_at(at, function, arguments=())[source]
execute_delayed(delay, function, arguments=())[source]
execute_every(period, function, arguments=())[source]

The socket for this connection

class irc.client.DCCConnection(reactor, dcctype)[source]

Bases: irc.client.Connection

A DCC (Direct Client Connection).

DCCConnection objects are instantiated by calling the dcc method on a Reactor object.

connect(address, port)[source]

Connect/reconnect to a DCC peer.


address – Host/IP address of the peer.

port – The port number to connect to.

Returns the DCCConnection object.


Hang up the connection and close the object.


message – Quit message.

Wait for a connection/reconnection from a DCC peer.

Returns the DCCConnection object.

The local IP address and port are available as self.localaddress and self.localport. After connection from a peer, the peer address and port are available as self.peeraddress and self.peerport.


Send text to DCC peer.

The text will be padded with a newline if it’s a DCC CHAT session.




Send data to DCC peer.

socket = None
exception irc.client.DCCConnectionError[source]

Bases: irc.client.IRCError

class irc.client.Event(type, source, target, arguments=None, tags=None)[source]

Bases: object

An IRC event.

>>> print(Event('privmsg', '@somebody', '#channel'))
type: privmsg, source: @somebody, target: #channel, arguments: [], tags: []
exception irc.client.IRCError[source]

Bases: Exception

An IRC exception

exception irc.client.InvalidCharacters[source]

Bases: ValueError

Invalid characters were encountered in the message

exception irc.client.MessageTooLong[source]

Bases: ValueError

Message is too long

class irc.client.NickMask[source]

Bases: str

A nickmask (the source of an Event)

>>> nm = NickMask('pinky!')
>>> nm.nick
>>> nm.user
>>> isinstance(nm, six.text_type)
>>> nm = 'красный!'
>>> if not six.PY3: nm = nm.decode('utf-8')
>>> nm = NickMask(nm)
>>> isinstance(nm.nick, six.text_type)

Some messages omit the userhost. In that case, None is returned.

>>> nm = NickMask('')
>>> nm.nick
>>> nm.userhost
>>> nm.user
classmethod from_group(group)[source]
classmethod from_params(nick, user, host)[source]
class irc.client.PrioritizedHandler[source]

Bases: irc.client.Base

class irc.client.Reactor(on_connect=<function Reactor.__do_nothing>, on_disconnect=<function Reactor.__do_nothing>)[source]

Bases: object

Processes events from one or more IRC server connections.

This class implements a reactor in the style of the reactor pattern.

When a Reactor object has been instantiated, it can be used to create Connection objects that represent the IRC connections. The responsibility of the reactor 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, process_once, and process_forever.

This is functionally an event-loop which can either use it’s own internal polling loop, or tie into an external event-loop, by having the external event-system periodically call process_once on the instantiated reactor class. This will allow the reactor to process any queued data and/or events.

Calling process_forever will hand off execution to the reactor’s internal event-loop, which will not return for the life of the reactor.

Here is an example:

client = irc.client.Reactor() server = client.server() server.connect(“irc.some.where”, 6667, “my_nickname”) server.privmsg(“a_nickname”, “Hi there!”) client.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.

The methods of this class are thread-safe; accesses to and modifications of its internal lists of connections, handlers, and delayed commands are guarded by a mutex.

add_global_handler(event, handler, priority=0)[source]

Adds a global handler function for a specific event type.


event – Event type (a string). Check the values of
numeric_events for possible event types.
handler – Callback function taking ‘connection’ and ‘event’

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.


Creates and returns a DCCConnection object.


dcctype – “chat” for DCC CHAT connections or “raw” for
DCC SEND (or other DCC types). If “chat”, incoming data will be split in newline-separated chunks. If “raw”, incoming data is not touched.

Disconnects all connections.

execute_at(at, function, arguments=())[source]

Execute a function at a specified time.


at – Execute at this time (a standard Unix timestamp). function – Function to call. arguments – Arguments to give the function.
execute_delayed(delay, function, arguments=())[source]

Execute a function after a specified time.

delay – How many seconds to wait. function – Function to call. arguments – Arguments to give the function.

execute_every(period, function, arguments=())[source]

Execute a function every ‘period’ seconds.

period – How often to run (always waits this long for first). function – Function to call. arguments – Arguments to give the function.


Called when there is more data to read on connection sockets.


sockets – A list of socket objects.

See documentation for Reactor.__init__.


Run an infinite loop, processing data from connections.

This method repeatedly calls process_once.


timeout – Parameter to pass to process_once.

Process data from connections once.


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.


Called when a timeout notification is due.

See documentation for Reactor.__init__.

remove_global_handler(event, handler)[source]

Removes a global handler function.


event – Event type (a string). handler – Callback function.

Returns 1 on success, otherwise 0.


alias of DefaultScheduler


Creates and returns a ServerConnection object.

class irc.client.ServerConnection(reactor)[source]

Bases: irc.client.Connection

An IRC server connection.

ServerConnection objects are instantiated by calling the server method on a Reactor object.

action(target, action)[source]

Send a CTCP ACTION command.


Add global handler.

See documentation for IRC.add_global_handler.


Send an ADMIN command.


Set the nick for the duration of the context.


alias of DecodingLineBuffer

cap(subcommand, *args)[source]

Send a CAP command according to the spec.


subcommand – LS, LIST, REQ, ACK, CLEAR, END args – capabilities, if required for given subcommand


.cap(‘LS’) .cap(‘REQ’, ‘multi-prefix’, ‘sasl’) .cap(‘END’)

Close the connection.

This method closes the connection permanently; after it has been called, the object is unusable.

connect(server, port, nickname, password=None, username=None, ircname=None, connect_factory=<irc.connection.Factory object>)[source]

Connect/reconnect to a server.


  • server - Server name
  • port - Port number
  • nickname - The nickname
  • password - Password (if any)
  • username - The username
  • ircname - The IRC name (“realname”)
  • server_address - The remote host/port of the server
  • connect_factory - A callable that takes the server address and returns a connection (with a socket interface)

This function can be called to reconnect a closed connection.

Returns the ServerConnection object.

ctcp(ctcptype, target, parameter='')[source]

Send a CTCP command.

ctcp_reply(target, parameter)[source]

Send a CTCP REPLY command.


Hang up the connection.


message – Quit message.

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 the (real) server name.

This method returns the (real) server name, or, more specifically, what the server calls itself.


Send a GLOBOPS command.


Send an INFO command.

invite(nick, channel)[source]

Send an INVITE command.


Return connection status.

Returns true if connected, otherwise false.


Send an ISON command.


nicks – List of nicks.
join(channel, key='')[source]

Send a JOIN command.

kick(channel, nick, comment='')[source]

Send a KICK command.

Send a LINKS command.

list(channels=None, server='')[source]

Send a LIST command.


Send a LUSERS command.

mode(target, command)[source]

Send a MODE command.


Send an MOTD command.


Send a NAMES command.


Send a NICK command.

notice(target, text)[source]

Send a NOTICE command.

oper(nick, password)[source]

Send an OPER command.

part(channels, message='')[source]

Send a PART command.


Send a PASS command.

ping(target, target2='')[source]

Send a PING command.

pong(target, target2='')[source]

Send a PONG command.

privmsg(target, text)[source]

Send a PRIVMSG command.

privmsg_many(targets, text)[source]

Send a PRIVMSG command to multiple targets.


read and process input from self.socket


Send a QUIT command.


Reconnect with the last arguments passed to self.connect()


Remove global handler.

See documentation for IRC.remove_global_handler.


Send all non-empty items, separated by spaces.


Send raw string to the server.

The string will be padded with appropriate CR LF.


Set a keepalive to occur every interval on this connection.


Set a frequency limit (messages per second) for this connection. Any attempts to send faster than this rate will block.

socket = None
squit(server, comment='')[source]

Send an SQUIT command.

stats(statstype, server='')[source]

Send a STATS command.


Send a TIME command.

topic(channel, new_topic=None)[source]

Send a TOPIC command.


Send a TRACE command.

user(username, realname)[source]

Send a USER command.


Send a USERHOST command.


Send a USERS command.


Send a VERSION command.


Send a WALLOPS command.

who(target='', op='')[source]

Send a WHO command.


Send a WHOIS command.

whowas(nick, max='', server='')[source]

Send a WHOWAS command.

exception irc.client.ServerConnectionError[source]

Bases: irc.client.IRCError

exception irc.client.ServerNotConnectedError[source]

Bases: irc.client.ServerConnectionError

class irc.client.SimpleIRCClient[source]

Bases: object

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.

Functionally, any of the event names in may be subscribed to by prefixing them with on_, and creating a function of that name in the child-class of SimpleIRCClient. When the event of event_name is received, the appropriately named method will be called (if it exists) by runtime class introspection.

See _dispatcher(), which takes the event name, postpends it to on_, and then attemps to look up the class member function by name and call it.

Instance attributes that can be used by sub classes:

reactor – The Reactor instance.

connection – The ServerConnection instance.

dcc_connections – A list of DCCConnection instances.

connect(*args, **kwargs)[source]

Connect using the underlying connection

dcc_connect(address, port, dcctype='chat')[source]

Connect to a DCC peer.


address – IP address of the peer.

port – Port to connect to.

Returns a DCCConnection instance.


Listen for connections from a DCC peer.

Returns a DCCConnection instance.


alias of Reactor


Start the IRC client.


Convert an IP number as an integer given in ASCII representation to an IP address string.

>>> ip_numstr_to_quad('3232235521')
>>> ip_numstr_to_quad(3232235521)

Convert an IP address string (e.g. ‘’) to an IP number as a base-10 integer given in ASCII representation.

>>> ip_quad_to_numstr('')

Check if a string is a channel name.

Returns true if the argument is a channel name, otherwise false.

irc.connection module

class irc.connection.Factory(bind_address=None, wrapper=<function <lambda>>, ipv6=False)[source]

Bases: object

A class for creating custom socket connections.

To create a simple connection:

server_address = (‘localhost’, 80) Factory()(server_address)

To create an SSL connection:


To create an SSL connection with parameters to wrap_socket:

wrapper = functools.partial(ssl.wrap_socket, ssl_cert=get_cert()) Factory(wrapper=wrapper)(server_address)

To create an IPv6 connection:


Note that Factory doesn’t save the state of the socket itself. The caller must do that, as necessary. As a result, the Factory may be re-used to create new connections with the same settings.

family = 2

irc.ctcp module

Handle Client-to-Client protocol per the best available spec.


Dequote a message according to CTCP specifications.

The function returns a list where each element can be either a string (normal message) or a tuple of one or two strings (tagged messages). If a tuple has only one element (ie is a singleton), that element is the tag; otherwise the tuple has two elements: the tag and the data.


message – The message to be decoded.

irc.dict module

class irc.dict.IRCDict(*args, **kargs)[source]

Bases: jaraco.collections.KeyTransformingDict

A dictionary of names whose keys are case-insensitive according to the IRC RFC rules.

>>> d = IRCDict({'[This]': 'that'}, A='foo')

The dict maintains the original case:

>>> '[This]' in ''.join(d.keys())

But the keys can be referenced with a different case

>>> d['a'] == 'foo'
>>> d['{this}'] == 'that'
>>> d['{THIS}'] == 'that'
>>> '{thiS]' in d

This should work for operations like delete and pop as well.

>>> d.pop('A') == 'foo'
>>> del d['{This}']
>>> len(d)
static transform_key(key)[source] module

irc.features module

class irc.features.FeatureSet[source]

Bases: object

An implementation of features as loaded from an ISUPPORT server directive.

Each feature is loaded into an attribute of the same name (but lowercased to match Python sensibilities).

>>> f = FeatureSet()
>>> f.load(['target', 'PREFIX=(abc)+-/', 'your message sir'])
>>> f.prefix == {'+': 'a', '-': 'b', '/': 'c'}

Order of prefix is relevant, so it is retained.

>>> tuple(f.prefix)
('+', '-', '/')
>>> f.load_feature('CHANMODES=foo,bar,baz')
>>> f.chanmodes
['foo', 'bar', 'baz']

Load the values from the a ServerConnection arguments

set(name, value=True)[source]

set a feature value

irc.features.string_int_pair(target, sep=':')[source]

irc.functools module


Wrap a method such that when it is called, the args and kwargs are saved on the method.

>>> class MyClass(object):
...     @save_method_args
...     def method(self, a, b):
...         print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)
>>> my_ob._saved_method.kwargs
>>> my_ob.method(a=3, b='foo')
3 foo
>>> my_ob._saved_method.args
>>> my_ob._saved_method.kwargs == dict(a=3, b='foo')

The arguments are stored on the instance, allowing for different instance to save different args.

>>> your_ob = MyClass()
>>> your_ob.method({str('x'): 3}, b=[4])
{'x': 3} [4]
>>> your_ob._saved_method.args
({'x': 3},)
>>> my_ob._saved_method.args

irc.modes module


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”, “o”, “h”, or “q”.


>>> parse_channel_modes("+ab-c foo")
[['+', 'a', None], ['+', 'b', 'foo'], ['-', 'c', None]]

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.


>>> parse_nick_modes("+ab-c")
[['+', 'a', None], ['+', 'b', None], ['-', 'c', None]]

irc.rfc module


irc.schedule module

class irc.schedule.DefaultScheduler[source]

Bases: tempora.schedule.InvokeScheduler, irc.schedule.IScheduler

execute_after(delay, func)[source]
execute_at(when, func)[source]
execute_every(period, func)[source]
class irc.schedule.IScheduler[source]

Bases: object

execute_after(delay, func)[source]

execute func after delay

execute_at(when, func)[source]

execute func at when

execute_every(period, func)[source]

execute func every period


invoke the functions that are due

irc.server module


This server has basic support for:

  • Connecting
  • Channels
  • Nicknames
  • Public/private messages

It is MISSING support for notably:

  • Server linking
  • Modes (user and channel)
  • Proper error reporting
  • Basically everything else

It is mostly useful as a testing tool or perhaps for building something like a private proxy on. Do NOT use it in any kind of production code or anything that will ever be connected to by the public.

class irc.server.IRCChannel(name, topic='No topic')[source]

Bases: object

An IRC channel.

class irc.server.IRCClient(request, client_address, server)[source]

Bases: socketserver.BaseRequestHandler

IRC client connect and command handling. Client connection is handled by the handle method which sets up a two-way communication with the client. It then handles commands sent by the client by dispatching them to the handle_ methods.

exception Disconnect[source]

Bases: BaseException


Return the client identifier as included in many command replies.


The client conection is finished. Do some cleanup to ensure that the client doesn’t linger around in any channel or the client list, in case the client didn’t properly close the connection with PART and QUIT.


Dump internal server information for debugging purposes.


Handle the JOINing of a user to a channel. Valid channel names start with a # and consist of a-z, A-Z, 0-9 and/or ‘_’.


Handle the initial setting of the user’s nickname and nick changes.


Handle a client parting from channel(s).


Handle client PING requests to keep the connection alive.


Handle sending a private message to a user or channel.


Handle the client breaking off the connection with a QUIT command.


Handle a topic command.


Handle the USER command which identifies the user to the server.

exception irc.server.IRCError(code, value)[source]

Bases: Exception

Exception thrown by IRC command handlers to notify client of a server/client error.

classmethod from_name(name, value)[source]
class irc.server.IRCServer(*args, **kwargs)[source]

Bases: socketserver.ThreadingMixIn, socketserver.TCPServer

allow_reuse_address = True
channels = {}

Existing channels (IRCChannel instances) by channel name

clients = {}

Connected clients (IRCClient instances) by nick name

daemon_threads = True

irc.strings module

class irc.strings.IRCFoldedCase[source]

Bases: jaraco.text.FoldedCase

A version of FoldedCase that honors the IRC specification for lowercased strings (RFC 1459).

>>> IRCFoldedCase('Foo^').lower()
>>> IRCFoldedCase('[this]') == IRCFoldedCase('{THIS}')
>>> IRCFoldedCase().lower()
translation = {65: 97, 66: 98, 67: 99, 68: 100, 69: 101, 70: 102, 71: 103, 72: 104, 73: 105, 74: 106, 75: 107, 76: 108, 77: 109, 78: 110, 79: 111, 80: 112, 81: 113, 82: 114, 83: 115, 84: 116, 85: 117, 86: 118, 87: 119, 88: 120, 89: 121, 90: 122, 91: 123, 92: 124, 93: 125, 94: 126}

Module contents