SOPEL(1)

NAME
sopel - Sopel IRC Bot Documentation

Sopel is a Python IRC bot framework. It is designed to enable easily writing new utilities and features for your IRC channels.

QUICK LINKS

•   Latest releases

•   Source code

•   Wiki

DOCUMENTATION

  Plugin structure

A Sopel plugin consists of a Python module containing one or more callables. It may optionally also contain configure, setup, and shutdown hooks.

callable(bot, trigger)
    A callable is any function which takes as its arguments a sopel.bot.Sopel object and a sopel.trigger.Trigger object, and is wrapped with appropriate decorators from sopel.module. The bot provides the ability to send messages to the network and check the state of the bot. The trigger provides information about the line which triggered this function to be called.

    The return value of these function is ignored, unless it is sopel.module.NOLIMIT, in which case rate limiting will not be applied for that call.

    Note that the name can, and should, be anything - it doesn't need to be called "callable".

setup(bot)
    This is an optional function of a plugin, which will be called while the module is being loaded. The purpose of this function is to perform whatever actions are needed to allow a module to function properly (e.g, ensuring that the appropriate configuration variables exist and are set). Note that this normally occurs prior to connection to the server, so the behavior of the messaging functions on the sopel.bot.Sopel object it's passed is undefined.

    Throwing an exception from this function (such as a sopel.config.ConfigurationError) will prevent any callables in the module from being registered, and provide an error message to the user. This is useful when requiring the presence of configuration values or making other environmental requirements.

    The bot will not continue loading modules or connecting during the execution of this function. As such, an infinite loop (such as an unthreaded polling loop) will cause the bot to hang.

shutdown(bot)
    This is an optional function of a module, which will be called while the bot is quitting. Note that this normally occurs after closing connection to the server, so the behavior of the messaging functions on the sopel.bot.Sopel object it's passed is undefined. The purpose of this function is to perform whatever actions are needed to allow a module to properly clean up (e.g, ensuring that any temporary cache files are deleted).

    The bot will not continue notifying other modules or continue quitting during the execution of this function. As such, an infinite loop (such as an unthreaded polling loop) will cause the bot to hang.

    New in version 4.1.

configure(config)
    This is an optional function of a module, which will be called during the user's setup of the bot. It's intended purpose is to use the methods of the passed sopel.config.Config object in order to create the configuration variables it needs to function properly.

    New in version 3.0.

  sopel.module

This contains decorators and tools for creating callable plugin functions.

sopel.module.NOLIMIT = 1
    Return value for callables, which suppresses rate limiting for the call.

    Returning this value means the triggering user will not be prevented from triggering the command again within the rate limit. This can be used, for example, to allow a user to retry a failed command immediately.

    New in version 4.0.

sopel.module.commands(*command_list)
    Decorate a function to set one or more commands to trigger it.

    This decorator can be used to add multiple commands to one callable in a single line. The resulting match object will have the command as the first group, rest of the line, excluding leading whitespace, as the second group. Parameters 1 through 4, separated by whitespace, will be groups 3-6.

Args:
    command: A string, which can be a regular expression.

Returns:
    A function with a new command appended to the commands attribute. If there is no commands attribute, it is added.

Example:

@commands("hello"):
    If the command prefix is ".", this would trigger on lines starting with ".hello".

@commands('j', 'join')
    If the command prefix is ".", this would trigger on lines starting with either ".j" or ".join".

sopel.module.event(*event_list)
    Decorate a function to be triggered on specific IRC events.

    This is one of a number of events, such as 'JOIN', 'PART', 'QUIT', etc. (More details can be found in RFC 1459.) When the Sopel bot is sent one of these events, the function will execute. Note that functions with an event must also be given a rule to match (though it may be '.*', which will always match) or they will not be triggered.

    sopel.tools.events provides human-readable names for many of the numeric events, which may help your code be clearer.

class sopel.module.example(msg, result=None, privmsg=False, admin=False, owner=False, repeat=1, re=False, ignore=None)
    Decorate a function with an example.

    Add an example attribute into a function and generate a test.

sopel.module.intent(*intent_list)
    Decorate a callable trigger on a message with any of the given intents.

    New in version 5.2.0.

sopel.module.interval(*args)
    Decorates a function to be called by the bot every X seconds.

    This decorator can be used multiple times for multiple intervals, or all intervals can be given at once as arguments. The first time the function will be called is X seconds after the bot was started.

    Unlike other plugin functions, ones decorated by interval must only take a sopel.bot.Sopel as their argument; they do not get a trigger. The bot argument will not have a context, so functions like bot.say() will not have a default destination.

    There is no guarantee that the bot is connected to a server or joined a channel when the function is called, so care must be taken.

    Example::

    import sopel.module
    @sopel.module.interval(5)
    def spam_every_5s(bot):
        if "#here" in bot.channels:
            bot.msg("#here", "It has been five seconds!")

sopel.module.nickname_commands(*command_list)
    Decorate a function to trigger on lines starting with "$nickname: command".

    This decorator can be used multiple times to add multiple rules. The resulting match object will have the command as the first group, rest of the line, excluding leading whitespace, as the second group. Parameters 1 through 4, separated by whitespace, will be groups 3-6.

Args:
    command: A string, which can be a regular expression.

Returns:
    A function with a new regular expression appended to the rule attribute. If there is no rule attribute, it is added.

Example:

@nickname_commands("hello!"):
    Would trigger on "$nickname: hello!", "$nickname, hello!", "$nickname hello!", "$nickname hello! parameter1" and "$nickname hello! p1 p2 p3 p4 p5 p6 p7 p8 p9".

@nickname_commands(".*"):
    Would trigger on anything starting with "$nickname[:,]? ", and would have never have any additional parameters, as the command would match the rest of the line.

sopel.module.priority(value)
    Decorate a function to be executed with higher or lower priority.

Args:

value: Priority can be one of high , medium , low . Defaults to
    medium.

    Priority allows you to control the order of callable execution, if your module needs it.

sopel.module.rate(user=0, channel=0, server=0)
    Decorate a function to limit how often it can be triggered on a per-user basis, in a channel, or across the server (bot). A value of zero means no limit. If a function is given a rate of 20, that function may only be used once every 20 seconds in the scope corresponding to the parameter. Users on the admin list in Sopel’s configuration are exempted from rate limits.

    Rate-limited functions that use scheduled future commands should import threading.Timer() instead of sched, or rate limiting will not work properly.

sopel.module.require_admin(message=None)
    Decorate a function to require the triggering user to be a bot admin.

    If they are not, message will be said if given.

sopel.module.require_chanmsg(message=None)
    Decorate a function to only be triggerable from a channel message.

    If it is triggered in a private message, message will be said if given.

sopel.module.require_owner(message=None)
    Decorate a function to require the triggering user to be the bot owner.

    If they are not, message will be said if given.

sopel.module.require_privilege(level, message=None)
    Decorate a function to require at least the given channel permission.

    level can be one of the privilege levels defined in this module. If the user does not have the privilege, message will be said if given. If it is a private message, no checking will be done.

sopel.module.require_privmsg(message=None)
    Decorate a function to only be triggerable from a private message.

    If it is triggered in a channel message, message will be said if given.

sopel.module.rule(value)
    Decorate a function to be called when a line matches the given pattern

    This decorator can be used multiple times to add more rules.

Args:
    value: A regular expression which will trigger the function.

    If the Sopel instance is in a channel, or sent a PRIVMSG, where a string matching this expression is said, the function will execute. Note that captured groups here will be retrievable through the Trigger object later.

    Inside the regular expression, some special directives can be used. $nick will be replaced with the nick of the bot and , or :, and $nickname will be replaced with the nick of the bot.

sopel.module.thread(value)
    Decorate a function to specify if it should be run in a separate thread.

    Functions run in a separate thread (as is the default) will not prevent the bot from executing other functions at the same time. Functions not run in a separate thread may be started while other functions are still running, but additional functions will not start until it is completed.

Args:

value: Either True or False. If True the function is called in
    a separate thread. If False from the main thread.

sopel.module.unblockable(function)
    Decorator which exempts the function from nickname and hostname blocking.

    This can be used to ensure events such as JOIN are always recorded.

sopel.module.url(url_rule)
    Decorate a function to handle URLs.

    This decorator takes a regex string that will be matched against URLs in a message. The function it decorates, in addition to the bot and trigger, must take a third argument match, which is the regular expression match of the URL. This should be used rather than the matching in trigger, in order to support e.g. the .title command.

  The bot and its state

class sopel.bot.Sopel(config, daemon=False)

nick
    Sopel's current nick. Changing this while Sopel is running is unsupported.

user
    Sopel's user/ident.

name
    Sopel's "real name", as used for whois.

action(text, dest)
    Send text as a CTCP ACTION PRIVMSG to dest.

    The same loop detection and length restrictions apply as with say(), though automatic message splitting is not available.

    Within the context of a triggered callable, dest will default to the channel (or nickname, if a private message), in which the trigger happened.

cap_req(module_name, capability, arg=None, failure_callback=None, success_callback=None)
    Tell Sopel to request a capability when it starts.

    By prefixing the capability with -, it will be ensured that the capability is not enabled. Simmilarly, by prefixing the capability with =, it will be ensured that the capability is enabled. Requiring and disabling is "first come, first served"; if one module requires a capability, and another prohibits it, this function will raise an exception in whichever module loads second. An exception will also be raised if the module is being loaded after the bot has already started, and the request would change the set of enabled capabilities.

    If the capability is not prefixed, and no other module prohibits it, it will be requested. Otherwise, it will not be requested. Since capability requests that are not mandatory may be rejected by the server, as well as by other modules, a module which makes such a request should account for that possibility.

    The actual capability request to the server is handled after the completion of this function. In the event that the server denies a request, the failure_callback function will be called, if provided. The arguments will be a Sopel object, and the capability which was rejected. This can be used to disable callables which rely on the capability. It will be be called either if the server NAKs the request, or if the server enabled it and later DELs it.

    The success_callback function will be called upon acknowledgement of the capability from the server, whether during the initial capability negotiation, or later.

    If arg is given, and does not exactly match what the server provides or what other modules have requested for that capability, it is considered a conflict.

channels = None
    A map of the channels that Sopel is in.

    The keys are Identifiers of the channel names, and map to sopel.tools.target.Channel objects which contain the users in the channel and their permissions.

config = None
    The sopel.config.Config for the current Sopel instance.

db = None
    The bot's database, as a sopel.db.SopelDB instance.

doc = None
    A dictionary of command names to their docstring and example, if declared. The first item in a callable's commands list is used as the key in version 3.2 onward. Prior to 3.2, the name of the function as declared in the source code was used.

enabled_capabilities = None
    A set containing the IRCv3 capabilities that the bot has enabled.

join(channel, password=None)
    Join a channel

    If channel contains a space, and no password is given, the space is assumed to split the argument into the channel to join and its password. channel should not contain a space if password is given.

memory = None
    A thread-safe dict for storage of runtime data to be shared between modules. See sopel.tools.Sopel.SopelMemory

notice(text, dest)
    Send an IRC NOTICE to a user or a channel.

    Within the context of a triggered callable, dest will default to the channel (or nickname, if a private message), in which the trigger happened.

part(channel, msg=None)
    Part a channel.

privileges = None
    A dictionary of channels to their users and privilege levels

    The value associated with each channel is a dictionary of sopel.tools.Identifiers to a bitwise integer value, determined by combining the appropriate constants from sopel.module.

    Deprecated since version 6.2.0: Use channels instead.

reply(text, dest, reply_to, notice=False)
    Prepend reply_to to text, and send as a PRIVMSG to dest.

    If notice is True, send a NOTICE rather than a PRIVMSG.

    The same loop detection and length restrictions apply as with say(), though automatic message splitting is not available.

    Within the context of a triggered callable, reply_to will default to the nickname of the user who triggered the call, and dest to the channel (or nickname, if a private message), in which the trigger happened.

say(text, recipient, max_messages=1)
    Send text as a PRIVMSG to recipient.

    In the context of a triggered callable, the recipient defaults to the channel (or nickname, if a private message) from which the message was received.

    By default, this will attempt to send the entire text in one message. If the text is too long for the server, it may be truncated. If max_messages is given, the text will be split into at most that many messages, each no more than 400 bytes. The split is made at the last space character before the 400th byte, or at the 400th byte if no such space exists. If the text is too long to fit into the specified number of messages using the above splitting, the final message will contain the entire remainder, which may be truncated by the server.

server_capabilities = None
    A dict mapping supported IRCv3 capabilities to their options.

    For example, if the server specifies the capability sasl=EXTERNAL, it will be here as {"sasl": "EXTERNAL"}. Capabilities specified without any options will have None as the value.

    For servers that do not support IRCv3, this will be an empty set.

shutdown_methods = None
    List of methods to call on shutdown

users = None
    A map of the users that Sopel is aware of.

    The keys are Identifiers of the nicknames, and map to sopel.tools.target.User instances. In order for Sopel to be aware of a user, it must be in at least one channel which they are also in.

write(args, text=None)
    Send a command to the server.

    args is an iterable of strings, which are joined by spaces. text is treated as though it were the final item in args, but is preceeded by a :. This is a special case which means that text, unlike the items in args may contain spaces (though this constraint is not checked by write).

    In other words, both sopel.write(('PRIVMSG',), 'Hello, world!') and sopel.write(('PRIVMSG', ':Hello, world!')) will send PRIVMSG :Hello, world! to the server.

    Newlines and carriage returns ('n' and 'r') are removed before sending. Additionally, if the message (after joining) is longer than than 510 characters, any remaining characters will not be sent.

  Triggers

class sopel.trigger.Trigger
    A line from the server, which has matched a callable's rules.

    Note that CTCP messages (PRIVMSG`es and `NOTICE`es which start and end with `'x01') will have the 'x01' bytes stripped, and the command (e.g. ACTION) placed mapped to the 'intent' key in Trigger.tags.

account
    The account name of the user sending the message.

    This is only available if either the account-tag or the account-notify and extended-join capabilites are available. If this isn't the case, or the user sending the message isn't logged in, this will be None.

admin
    True if the nick which triggered the command is one of the bot's admins.

args
    A tuple containing each of the arguments to an event. These are the strings passed between the event name and the colon. For example, setting mode -m on the channel #example, args would be ('#example', '-m')

event
    The IRC event (e.g. PRIVMSG or MODE) which triggered the message.

group
    The group function of the match attribute.

    See Python re documentation for details.

groupdict
    The groupdict function of the match attribute.

    See Python re documentation for details.

groups
    The groups function of the match attribute.

    See Python re documentation for details.

host
    The hostname of the person who sent the message

hostmask
    Hostmask of the person who sent the message as <nick>!<user>@<host>

is_privmsg
    True if the trigger is from a user, False if it's from a channel.

match
    The regular expression re.MatchObject for the triggering line.

nick
    The sopel.tools.Identifier of the person who sent the message.

owner
    True if the nick which triggered the command is the bot's owner.

raw The entire message, as sent from the server. This includes the CTCP x01 bytes and command, if they were included.

sender
    The channel from which the message was sent.

    In a private message, this is the nick that sent the message.

tags
    A map of the IRCv3 message tags on the message.

time
    A datetime object at which the message was received by the IRC server.

    If the server does not support server-time, then time will be the time that the message was received by Sopel

user
    Local username of the person who sent the message

  Configuration functionality

The config object provides a simplified to access Sopel's configuration file. The sections of the file are attributes of the object, and the keys in the section are attributes of that. So, for example, the eggs attribute in the [spam] section can be accessed from config.spam.eggs.

Section definitions (see "Section configuration sections" below) can be added to the config object with define_section. When this is done, only the defined keys will be available. A section can not be given more than one definition. The [core] section is defined with CoreSection when the object is initialized.

New in version 6.0.0.

class sopel.config.Config(filename, validate=True)

class ConfigSection(name, items, parent)
    Represents a section of the config file.

    Contains all keys in thesection as attributes.

get_list(name)

add_section(name)
    Add a section to the config file.

    Returns False if already exists.

define_section(name, cls_, validate=True)
    Define the available settings in a section.

    cls_ must be a subclass of StaticSection. If the section has already been defined with a different class, ValueError is raised.

    If validate is True, the section's values will be validated, and an exception raised if they are invalid. This is desirable in a module's setup function, for example, but might not be in the configure function.

filename = None
    The config object's associated file, as noted above.

homedir
    An alias to config.core.homedir

option(question, default=False)
    Ask "y/n" and return the corresponding boolean answer.

    Show user in terminal a "y/n" prompt, and return true or false based on the response. If default is passed as true, the default will be shown as [y], else it will be [n]. question should be phrased as a question, but without a question mark at the end.

save()
    Save all changes to the config file.

exception sopel.config.ConfigurationError(value)
    Exception type for configuration errors

    Types for creating section definitions.

    A section definition consists of a subclass of StaticSection, on which any number of subclasses of BaseValidated (a few common ones of which are available in this module) are assigned as attributes. These descriptors define how to read values from, and write values to, the config file.

    As an example, if one wanted to define the [spam] section as having an eggs option, which contains a list of values, they could do this:

    >>> class SpamSection(StaticSection):
    ...     eggs = ListAttribute('eggs')
    ...
    >>> SpamSection(config, 'spam')
    >>> print(config.spam.eggs)
    []
    >>> config.spam.eggs = ['goose', 'turkey', 'duck', 'chicken', 'quail']
    >>> print(config.spam.eggs)
    ['goose', 'turkey', 'duck', 'chicken', 'quail']
    >>> config.spam.eggs = 'herring'
    Traceback (most recent call last):
        ...
    ValueError: ListAttribute value must be a list.

class sopel.config.types.BaseValidated(name, default=None)
    The base type for a descriptor in a StaticSection.

configure(prompt, default, parent, section_name)
    With the prompt and default, parse and return a value from terminal.

parse(value)
    Take a string from the file, and return the appropriate object.

    Must be implemented in subclasses.

serialize(value)
    Take some object, and return the string to be saved to the file.

    Must be implemented in subclasses.

class sopel.config.types.ChoiceAttribute(name, choices, default=None)
    A config attribute which must be one of a set group of options.

    Currently, the choices can only be strings.

parse(value)
    Take a string from the file, and return the appropriate object.

    Must be implemented in subclasses.

serialize(value)
    Take some object, and return the string to be saved to the file.

    Must be implemented in subclasses.

class sopel.config.types.FilenameAttribute(name, relative=True, directory=False, default=None)
    A config attribute which must be a file or directory.

configure(prompt, default, parent, section_name)
    With the prompt and default, parse and return a value from terminal.

parse(main_config, this_section, value)
    Take a string from the file, and return the appropriate object.

    Must be implemented in subclasses.

serialize(main_config, this_section, value)
    Take some object, and return the string to be saved to the file.

    Must be implemented in subclasses.

class sopel.config.types.ListAttribute(name, strip=True, default=None)
    A config attribute containing a list of string values.

    Values are saved to the file as a comma-separated list. It does not currently support commas within items in the list. By default, the spaces before and after each item are stripped; you can override this by passing strip=False.

configure(prompt, default, parent, section_name)
    With the prompt and default, parse and return a value from terminal.

parse(value)
    Take a string from the file, and return the appropriate object.

    Must be implemented in subclasses.

serialize(value)
    Take some object, and return the string to be saved to the file.

    Must be implemented in subclasses.

class sopel.config.types.NO_DEFAULT
    A special value to indicate that there should be no default.

class sopel.config.types.StaticSection(config, section_name, validate=True)
    A configuration section with parsed and validated settings.

    This class is intended to be subclassed with added ValidatedAttributes.

configure_setting(name, prompt, default=<class 'sopel.config.types.NO_DEFAULT'>)
    Return a validated value for this attribute from the terminal.

    prompt will be the docstring of the attribute if not given.

    If default is passed, it will be used if no value is given by the user. If it is not passed, the current value of the setting, or the default value if it's unset, will be used. Note that if default is passed, the current value of the setting will be ignored, even if it is not the attribute's default.

class sopel.config.types.ValidatedAttribute(name, parse=None, serialize=None, default=None)

configure(prompt, default, parent, section_name)
    With the prompt and default, parse and return a value from terminal.

parse(value)
    Take a string from the file, and return the appropriate object.

    Must be implemented in subclasses.

serialize(value)
    Take some object, and return the string to be saved to the file.

    Must be implemented in subclasses.

  The [core] configuration section

class sopel.config.core_section.CoreSection(config, section_name, validate=True)
    The config section used for configuring the bot itself.

admin_accounts
    The list of accounts (other than the owner's) who can administer the bot.

    This should not be set for networks that do not support IRCv3 account capabilities.

admins
    The list of people (other than the owner) who can administer the bot

auth_method
    The method to use to authenticate with the server.

    Can be nickserv, authserv, Q, sasl, or server.

auth_password
    The password to use to authenticate with the server.

auth_target
    The user to use for nickserv authentication, or the SASL mechanism.

    May not apply, depending on auth_method. Defaults to NickServ for nickserv auth, and PLAIN for SASL auth.

auth_username
    The username/account to use to authenticate with the server.

    May not apply, depending on auth_method.

bind_host
    Bind the connection to a specific IP

ca_certs
    The path of the CA certs pem file

channels
    List of channels for the bot to join when it connects

db_filename
    The filename for Sopel's database.

default_time_format
    The default format to use for time in messages.

default_timezone
    The default timezone to use for time in messages.

enable
    A whitelist of the only modules you want to enable.

exclude
    A list of modules which should not be loaded.

extra
    A list of other directories you'd like to include modules from.

help_prefix
    The prefix to use in help

homedir
    The directory in which various files are stored at runtime.

    By default, this is the same directory as the config. It can not be changed at runtime.

host
    The server to connect to.

host_blocks
    A list of hostmasks which Sopel should ignore.

    Regular expression syntax is used

log_raw
    Whether a log of raw lines as sent and received should be kept.

logdir
    Directory in which to place logs.

logging_channel
    The channel to send logging messages to.

logging_level
    The lowest severity of logs to display.

modes
    User modes to be set on connection.

name
    The "real name" of your bot for WHOIS responses.

nick
    The nickname for the bot

nick_blocks
    A list of nicks which Sopel should ignore.

    Regular expression syntax is used.

not_configured
    For package maintainers. Not used in normal configurations.

    This allows software packages to install a default config file, with this set to true, so that the bot will not run until it has been properly configured.

owner
    The IRC name of the owner of the bot.

owner_account
    The services account name of the owner of the bot.

    This should only be set on networks which support IRCv3 account capabilities.

pid_dir
    The directory in which to put the file Sopel uses to track its process ID.

    You probably do not need to change this unless you're managing Sopel with systemd or similar.

port
    The port to connect on.

prefix
    The prefix to add to the beginning of commands.

    It is a regular expression (so the default, \., means commands start with a period), though using capturing groups will create problems.

reply_errors
    Whether to message the sender of a message that triggered an error with the exception.

throttle_join
    Slow down the initial join of channels to prevent getting kicked.

    Sopel will only join this many channels at a time, sleeping for a second between each batch. This is unnecessary on most networks.

timeout
    The amount of time acceptable between pings before timing out.

use_ssl
    Whether to use a SSL secured connection.

user
    The "user" for your bot (the part before the @ in the hostname).

verify_ssl
    Whether to require a trusted SSL certificate for SSL connections.

  The bot's database

class sopel.db.SopelDB(config)
    Availability: 5.0+

    This defines an interface for basic, common operations on a sqlite database. It simplifies those common operations, and allows direct access to the database, wherever the user has configured it to be.

    When configured with a relative filename, it is assumed to be in the same directory as the config.

alias_nick(nick, alias)
    Create an alias for a nick.

    Raises ValueError if the alias already exists. If nick does not already exist, it will be added along with the alias.

connect()
    Return a raw database connection object.

delete_nick_group(nick)
    Removes a nickname, and all associated aliases and settings.

execute(*args, **kwargs)
    Execute an arbitrary SQL query against the database.

    Returns a cursor object, on which things like .fetchall() can be called per PEP 249.

get_channel_value(channel, key)
    Retrieves the value for a given key associated with a channel.

get_nick_id(nick, create=True)
    Return the internal identifier for a given nick.

    This identifier is unique to a user, and shared across all of that user's aliases. If create is True, a new ID will be created if one does not already exist

get_nick_or_channel_value(name, key)
    Gets the value key associated to the nick or channel name.

get_nick_value(nick, key)
    Retrieves the value for a given key associated with a nick.

get_preferred_value(names, key)
    Gets the value for the first name which has it set.

    names is a list of channel and/or user names. Returns None if none of the names have the key set.

get_uri()
    Returns a URL for the database, usable to connect with SQLAlchemy.

merge_nick_groups(first_nick, second_nick)
    Merges the nick groups for the specified nicks.

    Takes two nicks, which may or may not be registered. Unregistered nicks will be registered. Keys which are set for only one of the given nicks will be preserved. Where multiple nicks have values for a given key, the value set for the first nick will be used.

    Note that merging of data only applies to the native key-value store. If modules define their own tables which rely on the nick table, they will need to have their merging done separately.

set_nick_value(nick, key, value)
    Sets the value for a given key to be associated with the nick.

unalias_nick(alias)
    Removes an alias.

    Raises ValueError if there is not at least one other nick in the group. To delete an entire group, use delete_group.

  Additional API features

Sopel includes a number of additional functions that are useful for various common IRC tasks.

Note that sopel.web was deprecated in 6.2.0, and is not included in this documentation, but is still in use in many modules. It's highly recommended that you switch to requests instead.

  Contents

•   Additional API features

•   sopel.tools

•   sopel.tools.time

•   sopel.tools.calculation

•   sopel.tools.target

•   sopel.tools.events

•   sopel.formatting

  sopel.tools

Useful miscellaneous tools and shortcuts for Sopel modules

Availability: 3+

class sopel.tools.Ddict(default=None)
    Class for multi-dimensional dict.

    A simple helper class to ease the creation of multi-dimensional dicts.

class sopel.tools.Identifier
    A unicode subclass which acts appropriately for IRC identifiers.

    When used as normal unicode objects, case will be preserved. However, when comparing two Identifier objects, or comparing a Identifier object with a unicode object, the comparison will be case insensitive. This case insensitivity includes the case convention conventions regarding [], {}, |, \, ^ and ~ described in RFC 2812.

is_nick()
    Returns True if the Identifier is a nickname (as opposed to channel)

lower()
    Return the identifier converted to lower-case per RFC 2812.

class sopel.tools.OutputRedirect(logpath, stderr=False, quiet=False)
    Redirect te output to the terminal and a log file.

    A simplified object used to write to both the terminal and a log file.

write(string)
    Write the given string to the logfile and terminal.

class sopel.tools.SopelMemory(*args)
    A simple thread-safe dict implementation.

    Availability: 4.0; available as ``Sopel.SopelMemory`` in 3.1.0 - 3.2.0

    In order to prevent exceptions when iterating over the values and changing them at the same time from different threads, we use a blocking lock on __setitem__ and contains.

contains(key)
    Backwards compatability with 3.x, use in operator instead.

class sopel.tools.SopelMemoryWithDefault(*args)
    Same as SopelMemory, but subclasses from collections.defaultdict.

contains(key)
    Backwards compatability with 3.x, use in operator instead.

sopel.tools.check_pid(pid)
    Check if a process is running with the given PID.

    Availability: Only on POSIX systems

    Return True if there is a process running with the given PID.

sopel.tools.get_command_regexp(prefix, command)
    Return a compiled regexp object that implements the command.

sopel.tools.get_hostmask_regex(mask)
    Return a compiled re.RegexObject for an IRC hostmask

sopel.tools.get_input(prompt)
    Get decoded input from the terminal (equivalent to python 3's input).

sopel.tools.get_raising_file_and_line(tb=None)
    Return the file and line number of the statement that raised the tb.

    Returns: (filename, lineno) tuple

sopel.tools.stderr(string)
    Print the given string to stderr.

    This is equivalent to print >> sys.stderr, string

  sopel.tools.time

Tools for getting and displaying the time.

sopel.tools.time.format_time(db=None, config=None, zone=None, nick=None, channel=None, time=None)
    Return a formatted string of the given time in the given zone.

    time, if given, should be a naive datetime.datetime object and will be treated as being in the UTC timezone. If it is not given, the current time will be used. If zone is given and pytz is available, zone must be present in the IANA Time Zone Database; get_timezone can be helpful for this. If zone is not given or pytz is not available, UTC will be assumed.

    The format for the string is chosen in the following order:

1.  The format for the nick nick in db, if one is set and valid.

2.  The format for the channel channel in db, if one is set and valid.

3.  The default format in config, if one is set and valid.

4.  ISO-8601

    If db is not given or is not set up, steps 1 and 2 are skipped. If config is not given, step 3 will be skipped.

sopel.tools.time.get_timezone(db=None, config=None, zone=None, nick=None, channel=None)
    Find, and return, the approriate timezone

    Time zone is pulled in the following priority: 1. zone, if it is valid 2. The timezone for the channel or nick zone in db if one is set and valid. 3. The timezone for the nick nick in db, if one is set and valid. 4. The timezone for the channel channel in db, if one is set and valid. 5. The default timezone in config, if one is set and valid.

    If db is not given, or given but not set up, steps 2 and 3 will be skipped. If config is not given, step 4 will be skipped. If no step yeilds a valid timezone, None is returned.

    Valid timezones are those present in the IANA Time Zone Database. Prior to checking timezones, two translations are made to make the zone names more human-friendly. First, the string is split on ', ', the pieces reversed, and then joined with '/'. Next, remaining spaces are replaced with '_'. Finally, strings longer than 4 characters are made title-case, and those 4 characters and shorter are made upper-case. This means "new york, america" becomes "America/New_York", and "utc" becomes "UTC".

    This function relies on pytz being available. If it is not available, None will always be returned.

sopel.tools.time.validate_format(tformat)
    Returns the format, if valid, else None

sopel.tools.time.validate_timezone(zone)
    Return an IETF timezone from the given IETF zone or common abbreviation.

    If the length of the zone is 4 or less, it will be upper-cased before being looked up; otherwise it will be title-cased. This is the expected case-insensitivity behavior in the majority of cases. For example, 'edt' and 'america/new_york' will both return 'America/New_York'.

    If the zone is not valid, ValueError will be raised. If pytz is not available, and the given zone is anything other than 'UTC', ValueError will be raised.

  sopel.tools.calculation

Tools to help safely do calculations from user input

sopel.tools.calculation.eval_equation = <sopel.tools.calculation.EquationEvaluator object>
    Evaluates a Python equation expression and returns the result.

    Supports addition (+), subtraction (-), multiplication (*), division (/), power (**) and modulo (%).

  sopel.tools.target

class sopel.tools.target.Channel(name)
    A representation of a channel Sopel is in.

name = None
    The name of the channel.

privileges = None
    The permissions of the users in the channel.

    This maps username Identifier``s to bitwise integer values. This can be compared to appropriate constants from ``sopel.module.

topic = None
    The topic of the channel.

users = None
    The users in the channel.

    This maps username Identifiers to channel objects.

class sopel.tools.target.User(nick, user, host)
    A representation of a user Sopel is aware of.

account = None
    The IRC services account of the user.

    This relies on IRCv3 account tracking being enabled.

away = None
    Whether the user is marked as away.

channels = None
    The channels the user is in.

    This maps channel name Identifiers to Channel objects.

host = None
    The user's hostname.

hostmask
    The user's full hostmask.

nick = None
    The user's nickname.

user = None
    The user's local username.

  sopel.tools.events

class sopel.tools.events
    An enumeration of all the standardized and notable IRC numeric events

    This allows you to do, for example, @module.event(events.RPL_WELCOME) rather than @module.event('001')

ERR_ALREADYREGISTRED = '462'

ERR_BADCHANMASK = '476'

ERR_BADCHANNELKEY = '475'

ERR_BADMASK = '415'

ERR_BANLISTFULL = '478'

ERR_BANNEDFROMCHAN = '474'

ERR_CANNOTSENDTOCHAN = '404'

ERR_CANTKILLSERVER = '483'

ERR_CHANNELISFULL = '471'

ERR_CHANOPRIVSNEEDED = '482'

ERR_ERRONEUSNICKNAME = '432'

ERR_FILEERROR = '424'

ERR_INVALIDCAPCMD = '410'

ERR_INVITEONLYCHAN = '473'

ERR_KEYINVALID = '767'

ERR_KEYNOPERMISSION = '769'

ERR_KEYNOTSET = '768'

ERR_KEYSET = '467'

ERR_METADATALIMIT = '764'

ERR_MONLISTFULL = '734'

ERR_NEEDMOREPARAMS = '461'

ERR_NICKCOLLISION = '436'

ERR_NICKLOCKED = '902'

ERR_NICKNAMEINUSE = '433'

ERR_NOADMININFO = '423'

ERR_NOCHANMODES = '477'

ERR_NOLOGIN = '444'

ERR_NOMATCHINGKEY = '766'

ERR_NOMOTD = '422'

ERR_NONICKNAMEGIVEN = '431'

ERR_NOOPERHOST = '491'

ERR_NOORIGIN = '409'

ERR_NOPERMFORHOST = '463'

ERR_NOPRIVILEGES = '481'

ERR_NORECIPIENT = '411'

ERR_NOSUCHCHANNEL = '403'

ERR_NOSUCHNICK = '401'

ERR_NOSUCHSERVER = '402'

ERR_NOSUCHSERVICE = '408'

ERR_NOTEXTTOSEND = '412'

ERR_NOTONCHANNEL = '442'

ERR_NOTOPLEVEL = '413'

ERR_NOTREGISTERED = '451'

ERR_PASSWDMISMATCH = '464'

ERR_RESTRICTED = '484'

ERR_SASLABORTED = '906'

ERR_SASLALREADY = '907'

ERR_SASLFAIL = '904'

ERR_SASLTOOLONG = '905'

ERR_STARTTLS = '691'

ERR_SUMMONDISABLED = '445'

ERR_TARGETINVALID = '765'

ERR_TOOMANYCHANNELS = '405'

ERR_TOOMANYTARGETS = '407'

ERR_UMODEUNKNOWNFLAG = '501'

ERR_UNAVAILRESOURCE = '437'

ERR_UNIQOPPRIVSNEEDED = '485'

ERR_UNKNOWNCOMMAND = '421'

ERR_UNKNOWNMODE = '472'

ERR_USERNOTINCHANNEL = '441'

ERR_USERONCHANNEL = '443'

ERR_USERSDISABLED = '446'

ERR_USERSDONTMATCH = '502'

ERR_WASNOSUCHNICK = '406'

ERR_WILDTOPLEVEL = '414'

ERR_YOUREBANNEDCREEP = '465'

ERR_YOUWILLBEBANNED = '466'

RPL_ADMINEMAIL = '259'

RPL_ADMINLOC1 = '257'

RPL_ADMINLOC2 = '258'

RPL_ADMINME = '256'

RPL_AWAY = '301'

RPL_BANLIST = '367'

RPL_BOUNCE = '005'

RPL_CHANNELMODEIS = '324'

RPL_CREATED = '003'

RPL_ENDOFBANLIST = '368'

RPL_ENDOFEXCEPTLIST = '349'

RPL_ENDOFINFO = '374'

RPL_ENDOFINVITELIST = '347'

RPL_ENDOFLINKS = '365'

RPL_ENDOFMONLIST = '733'

RPL_ENDOFMOTD = '376'

RPL_ENDOFNAMES = '366'

RPL_ENDOFSTATS = '219'

RPL_ENDOFUSERS = '394'

RPL_ENDOFWHO = '315'

RPL_ENDOFWHOIS = '318'

RPL_ENDOFWHOWAS = '369'

RPL_EXCEPTLIST = '348'

RPL_INFO = '371'

RPL_INVITELIST = '346'

RPL_INVITING = '341'

RPL_ISON = '303'

RPL_ISUPPORT = '005'

RPL_KEYVALUE = '761'

RPL_LINKS = '364'

RPL_LIST = '322'

RPL_LISTEND = '323'

RPL_LISTSTART = '321'

RPL_LOGGEDIN = '900'

RPL_LOGGEDOUT = '901'

RPL_LUSERCHANNELS = '254'

RPL_LUSERCLIENT = '251'

RPL_LUSERME = '255'

RPL_LUSEROP = '252'

RPL_LUSERUNKNOWN = '253'

RPL_METADATAEND = '762'

RPL_MONLIST = '732'

RPL_MONOFFLINE = '731'

RPL_MONONLINE = '730'

RPL_MOTD = '372'

RPL_MOTDSTART = '375'

RPL_MYINFO = '004'

RPL_NAMREPLY = '353'

RPL_NONE = '300'

RPL_NOTOPIC = '331'

RPL_NOUSERS = '395'

RPL_NOWAWAY = '306'

RPL_REHASHING = '382'

RPL_SASLMECHS = '908'

RPL_SASLSUCCESS = '903'

RPL_SERVLIST = '234'

RPL_SERVLISTEND = '235'

RPL_STARTTLS = '670'

RPL_STATSCLINE = '213'

RPL_STATSCOMMANDS = '212'

RPL_STATSHLINE = '244'

RPL_STATSILINE = '215'

RPL_STATSKLINE = '216'

RPL_STATSLINKINFO = '211'

RPL_STATSLLINE = '241'

RPL_STATSNLINE = '214'

RPL_STATSOLINE = '243'

RPL_STATSUPTIME = '242'

RPL_STATSYLINE = '218'

RPL_SUMMONING = '342'

RPL_TIME = '391'

RPL_TOPIC = '332'

RPL_TRACECLASS = '209'

RPL_TRACECONNECTING = '201'

RPL_TRACEEND = '262'

RPL_TRACEHANDSHAKE = '202'

RPL_TRACELINK = '200'

RPL_TRACELOG = '261'

RPL_TRACENEWTYPE = '208'

RPL_TRACEOPERATOR = '204'

RPL_TRACERECONNECT = '210'

RPL_TRACESERVER = '206'

RPL_TRACESERVICE = '207'

RPL_TRACEUNKNOWN = '203'

RPL_TRACEUSER = '205'

RPL_TRYAGAIN = '263'

RPL_UMODEIS = '221'

RPL_UNAWAY = '305'

RPL_UNIQOPIS = '325'

RPL_USERHOST = '302'

RPL_USERS = '393'

RPL_USERSSTART = '392'

RPL_VERSION = '351'

RPL_WELCOME = '001'

RPL_WHOISCHANNELS = '319'

RPL_WHOISIDLE = '317'

RPL_WHOISKEYVALUE = '760'

RPL_WHOISOPERATOR = '313'

RPL_WHOISSERVER = '312'

RPL_WHOISUSER = '311'

RPL_WHOREPLY = '352'

RPL_WHOSPCRPL = '354'

RPL_WHOWASUSER = '314'

RPL_YOUREOPER = '381'

RPL_YOURESERVICE = '383'

RPL_YOURHOST = '002'

  sopel.formatting

The formatting module includes functions to apply IRC formatting to text.

Availability: 4.5+

sopel.formatting.CONTROL_BOLD = '\x02'
    The control code to start or end bold formatting

sopel.formatting.CONTROL_COLOR = '\x03'
    The control code to start or end color formatting

sopel.formatting.CONTROL_NORMAL = '\x0f'
    The control code to reset formatting

sopel.formatting.CONTROL_UNDERLINE = '\x1f'
    The control code to start or end underlining

sopel.formatting.bold(text)
    Return the text, with bold IRC formatting.

sopel.formatting.color(text, fg=None, bg=None)
    Return the text, with the given colors applied in IRC formatting.

    The color can be a string of the color name, or an integer between 0 and 99. The known color names can be found in the colors class of this module.

class sopel.formatting.colors

BLACK = '01'

BLUE = '02'

BROWN = '05'

CYAN = '11'

FUCHSIA = '13'

GRAY = '14'

GREEN = '03'

GREY = '14'

LIGHT_BLUE = '12'

LIGHT_CYAN = '11'

LIGHT_GRAY = '15'

LIGHT_GREEN = '09'

LIGHT_GREY = '15'

LIGHT_PURPLE = '13'

LIME = '09'

MAROON = '05'

NAVY = '02'

OLIVE = '07'

ORANGE = '07'

PINK = '13'

PURPLE = '06'

RED = '04'

ROYAL = '12'

SILVER = '15'

TEAL = '10'

WHITE = '00'

YELLOW = '08'

sopel.formatting.underline(text)
    Return the text, with underline IRC formatting.

AUTHOR
Elsie Powell, et al.

COPYRIGHT
2012-2018, Elsie Powell, et al.