Configuration functionality

sopel.config

Sopel’s configuration module.

The Config object provides an interface to access Sopel’s configuration file. It exposes the configuration’s sections through its attributes as objects, which in turn expose their directives through their attributes.

For example, this is how to access core.nick on a Config object:

>>> from sopel import config
>>> settings = config.Config('/sopel/config.cfg')
>>> settings.core.nick
'Sopel'

The configuration file being:

[core]
nick = Sopel
host = irc.freenode.org
use_ssl = true
port = 6697
owner = dgw
channels =
    "#sopel"

A section can be represented by a subclass of StaticSection; for example a [spam] section with eggs and bacon can be defined like this:

from sopel import config

class SpamSection(config.types.StaticSection):
    eggs = config.types.ListAttribute('eggs')
    bacon = config.types.ValidatedAttribute('bacon')

The [core] section itself is represented by the CoreSection class, which is a subclass of StaticSection. It is automatically added when the Config object is instantiated; it uses Config.define_section() for that purpose.

New in version 6.0.0.

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

The bot’s configuration.

Parameters
  • filename (str) – the configuration file to load and use to populate this Config instance

  • validate (bool) – if True, validate values in the [core] section when it is loaded (optional; True by default)

The configuration object will load sections (see ConfigSection) from the file at filename during initialization. Calling save() writes any runtime changes to the loaded settings back to the same file.

Only the [core] section (see CoreSection) is added and made available by default; it is the only section required for Sopel to run. All other sections must be defined later, by the code that needs them, using define_section().

class ConfigSection(name, items, parent)

Represents a section of the config file.

Parameters
  • name (str) – name of this section

  • items (iterable of two-item tuples) – key-value pairs

  • parent (Config) – this section’s containing object

Contains all keys in the section as attributes.

get_list(name)

Legacy way of getting a list from a config value.

Parameters

name (str) – name of the attribute to fetch and interpret as a list

Returns

the value of name as a list

Return type

list

Deprecated since version 7.0: Use ListAttribute when storing a list value. This legacy method will be removed in Sopel 8.0.

add_section(name)

Add a new, empty section to the config file.

Parameters

name (str) – name of the new section

Returns

None if successful; False if a section named name already exists

Note

Plugin authors very rarely want or need to use this method.

You will almost always want to define (and optionally validate values within) a section with specific attributes using define_section() and a child class of StaticSection.

basename

The config’s base filename, i.e. the filename without the extension.

If the filename is freenode.config.cfg, then the basename will be freenode.config.

define_section(name, cls_, validate=True)

Define the available settings in a section.

Parameters
  • name (str) – name of the new section

  • cls_ (subclass of StaticSection) – class defining the settings within the section

  • validate (bool) – whether to validate the section’s values (optional; defaults to True)

Raises

ValueError – if the section name has been defined already with a different cls_

If validate is True, the section’s values will be validated, and an exception (usually ValueError or AttributeError) raised if they are invalid. This is desirable in a plugin’s setup() function, for example, but might not be in the configure() function.

filename

The config object’s associated file.

get

Shortcut to parser.get.

property homedir

The config file’s home directory.

If the core.homedir setting is available, that value is used. Otherwise, the default homedir is the directory portion of the Config’s filename.

option(question, default=False)

Ask the user a “y/n” question.

Parameters
  • question (str) – the question to ask the user

  • default (bool) – True to show [y] as the default choice; False to show [n] (optional; defaults to False)

Returns

the Boolean value corresponding to the user’s choice

Return type

bool

This will show a “y/n” prompt in the user’s terminal, and return True or False based on the response. question should be phrased as a question, but without a question mark at the end.

parser

The configuration parser object that does the heavy lifting.

See also

Python’s built-in configparser module and its RawConfigParser class.

save()

Write all changes to the config file.

Note

Saving the config file will remove any comments that might have existed, as Python’s configparser ignores them when parsing.

This will become less and less important as we continue to improve Sopel’s tools for making automated changes to config files and eliminate most users’ need to ever manually edit the text, but it’s still worth keeping in mind.

exception sopel.config.ConfigurationError(value)

Exception type for configuration errors.

Parameters

value (str) – a description of the error that has occurred

exception sopel.config.ConfigurationNotFound(filename)

Exception type for use when the configuration file cannot be found.

Parameters

filename (str) – file path that could not be found

filename

Path to the configuration file that could not be found.

sopel.config.types

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 setting descriptor in a StaticSection.

Parameters
  • name (str) – the attribute name to use in the config file

  • default (str) – the value to be returned if the setting has no value (optional; defaults to None)

default also can be set to sopel.config.types.NO_DEFAULT, if the value must be configured by the user (i.e. there is no suitable default value). Trying to read an empty NO_DEFAULT value will raise AttributeError.

configure(prompt, default, parent, section_name)

With the prompt and default, parse and return a value from terminal.

parse(value, *args, **kwargs)

Take a string from the file, and return the appropriate object.

Must be implemented in subclasses.

serialize(value, *args, **kwargs)

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.

Parameters
  • name (str) – the attribute name to use in the config file

  • choices (list or tuple) – acceptable values; currently, only strings are supported

  • default (str) – which choice to use if none is set in the config file; to require explicit configuration, use sopel.config.types.NO_DEFAULT (optional)

parse(value)

Check the loaded value against the valid choices.

Parameters

value (str) – the value loaded from the config file

Returns

the value, if it is valid

Return type

str

Raises

ValueError – if value is not one of the valid choices

serialize(value)

Make sure value is valid and safe to write in the config file.

Parameters

value (str) – the value needing to be saved

Returns

the value, if it is valid

Return type

str

Raises

ValueError – if value is not one of the valid choices

class sopel.config.types.FilenameAttribute(name, relative=True, directory=False, default=None)

A config attribute which must be a file or directory.

Parameters
  • name (str) – the attribute name to use in the config file

  • relative (bool) – whether the path should be relative to the location of the config file (optional; note that absolute paths will always be interpreted as absolute)

  • directory (bool) – whether the path should indicate a directory, rather than a file (optional)

  • default (str) – the value to use if none is defined in the config file; to require explicit configuration, use sopel.config.types.NO_DEFAULT (optional)

configure(prompt, default, parent, section_name)

With the prompt and default, parse and return a value from terminal.

parse(value, main_config, this_section)

Used to validate value when loading the config.

Parameters
  • main_config (Config) – the config object which contains this attribute

  • this_section (StaticSection) – the config section which contains this attribute

Returns

the value, if it is valid

Return type

str

Raises

ValueError – if the value is not valid

serialize(value, main_config, this_section)

Used to validate value when it is changed at runtime.

Parameters
  • main_config (Config) – the config object which contains this attribute

  • this_section (StaticSection) – the config section which contains this attribute

Returns

the value, if it is valid

Return type

str

Raises

ValueError – if the value is not valid

class sopel.config.types.ListAttribute(name, strip=True, default=None)

A config attribute containing a list of string values.

Parameters
  • name (str) – the attribute name to use in the config file

  • strip (bool) – whether to strip whitespace from around each value (optional; applies only to legacy comma-separated lists; multi-line lists are always stripped)

  • default (list) – the default value if the config file does not define a value for this option; to require explicit configuration, use sopel.config.types.NO_DEFAULT (optional)

From this StaticSection:

class SpamSection(StaticSection):
    cheeses = ListAttribute('cheeses')

the option will be exposed as a Python list:

>>> config.spam.cheeses
['camembert', 'cheddar', 'reblochon', '#brie']

which comes from this configuration file:

[spam]
cheeses =
    camembert
    cheddar
    reblochon
    "#brie"

Note that the #brie item starts with a #, hence the double quote: without these quotation marks, the config parser would think it’s a comment. The quote/unquote is managed automatically by this field, and if and only if it’s necessary (see parse() and serialize()).

Changed in version 7.0: The option’s value will be split on newlines by default. In this case, the strip parameter has no effect.

See the parse() method for more information.

Note

About: backward compatibility with comma-separated values.

A ListAttribute option allows to write, on a single line, the values separated by commas. As of Sopel 7.x this behavior is discouraged. It will be deprecated in Sopel 8.x, then removed in Sopel 9.x.

Bot owners are encouraged to update their configurations to use newlines instead of commas.

The comma delimiter fallback does not support commas within items in the list.

DELIMITER = ','
QUOTE_REGEX = re.compile('^"(?P<value>#.*)"$')

Regex pattern to match value that requires quotation marks.

This pattern matches values that start with # inside quotation marks only: "#sopel" will match, but "sopel" won’t, and neither will any variant that doesn’t conform to this pattern.

configure(prompt, default, parent, section_name)

With the prompt and default, parse and return a value from terminal.

parse(value)

Parse value into a list.

Parameters

value (str) – a multi-line string of values to parse into a list

Returns

a list of items from value

Return type

list

Changed in version 7.0: The value is now split on newlines, with fallback to comma when there is no newline in value.

When modified and saved to a file, items will be stored as a multi-line string (see serialize()).

parse_item(item)

Parse one item from the list.

Parameters

item (str) – one item from the list to parse

Return type

str

If item matches the QUOTE_REGEX pattern, then it will be unquoted. Otherwise it’s returned as-is.

serialize(value)

Serialize value into a multi-line string.

Parameters

value (list) – the input list

Return type

str

Raises

ValueError – if value is the wrong type (i.e. not a list)

serialize_item(item)

Serialize an item from the list value.

Parameters

item (str) – one item of the list to serialize

Return type

str

If item starts with a # it will be quoted in order to prevent the config parser from thinking it’s a comment.

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 and customized with added attributes containing BaseValidated-based objects.

configure_setting(name, prompt, default=<class 'sopel.config.types.NO_DEFAULT'>)

Return a validated value for this attribute from the terminal.

Parameters
  • name (str) – the name of the attribute to configure

  • prompt (str) – the prompt text to display in the terminal

  • default (depends on subclass) – the value to be used if the user does not enter one

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)

A descriptor for settings in a StaticSection.

Parameters
  • name (str) – the attribute name to use in the config file

  • parse (function) – a function to be used to read the string and create the appropriate object (optional; the string value will be returned as-is if not set)

  • serialize (function) – a function that, given an object, should return a string that can be written to the config file safely (optional; defaults to str)

configure(prompt, default, parent, section_name)

With the prompt and default, parse and return a value from terminal.

parse(value)

No-op: simply returns the given value, unchanged.

Parameters

value (str) – the string read from the config file

Return type

str

serialize(value)

Return the value as a Unicode string.

Parameters

value – the option value

Return type

str

sopel.config.core_section

class sopel.config.core_section.CoreSection(config, section_name, validate=True)

The config section used for configuring the bot itself.

Important

All Required values must be specified, or Sopel will fail to start.

admin_accounts

The list of admin accounts other than the owner’s.

Each account is allowed to administer the bot and can perform commands that are restricted to admins.

Important

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.

alias_nicks

List of alternate names users may call the bot.

These aliases are used along with the bot’s nick for $nick and $nickname regex substitutions.

For example, a bot named “William” (its nick) could have aliases “Bill”, “Will”, and “Liam”. This would then allow both “William: Hi!” and “Bill: Hi!” to work with nickname_commands().

auth_method

Simple method to authenticate with the server.

Can be one of nickserv, authserv, Q, sasl, server, or userserv.

This allows only a single authentication method; to use both a server-based authentication method and a nick-based authentication method, see server_auth_method and nick_auth_method.

For more information about these methods, see Authentication.

Note

If this is specified, nick_auth_method will be ignored, and this value will override server_auth_method.

auth_password

The password to use to authenticate with the auth_method.

See Authentication.

auth_target

Target for authentication.

Default

The nickname of the NickServ service, or the name of the desired SASL mechanism, if auth_method is set to one of these methods. This value is otherwise ignored.

See Authentication.

auth_username

The user/account name to use when authenticating.

May not apply, depending on auth_method. See Authentication.

auto_url_schemes

List of URL schemes that will trigger URL callbacks.

Default

['http', 'https', 'ftp']

Used by the URL callbacks feature to call plugins when links are posted in chat; see the sopel.module.url() decorator.

The default value allows http, https, and ftp.

bind_host

Bind the connection to a specific IP.

Default

0.0.0.0 (all interfaces)

ca_certs

The path to the CA certs .pem file.

If not specified, Sopel will try to find the certificate trust store itself.

channels

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

If a channel key needs to be provided, separate it from the channel name with a space, e.g. "#channel password".

commands_on_connect

A list of commands to send upon successful connection to the IRC server.

Each line is a message that will be sent to the server once connected. Example:

commands_on_connect =
    PRIVMSG Q@CServe.quakenet.org :AUTH my_username MyPassword,@#$%!
    PRIVMSG MyOwner :I'm here!

$nickname can be used in a command as a placeholder, and will be replaced with the bot’s nick. For example, if the bot’s nick is Sopel, MODE $nickname +Xxw will be expanded to MODE Sopel +Xxw.

New in version 7.0.

db_driver

The driver to use for connecting to the database.

This is optional, but can be specified if user wants to use a different driver than the default for the chosen db_type.

See also

Refer to SQLAlchemy’s documentation for more information.

db_filename

The filename for Sopel’s database.

Used only for SQLite. Ignored for all other db_type values.

db_host

The host for Sopel’s database.

Ignored when using SQLite.

db_name

The name of Sopel’s database.

Ignored when using SQLite.

db_pass

The password for Sopel’s database.

Ignored when using SQLite.

db_port

The port for Sopel’s database.

Ignored when using SQLite.

db_type

The type of database Sopel should connect to.

Default

sqlite (part of Python’s standard library)

The full list of values Sopel recognizes is:

  • firebird

  • mssql

  • mysql

  • oracle

  • postgres

  • sqlite

  • sybase

Here are the additional PyPI packages you may need to install to use one of the most commonly requested alternatives:

mysql

pip install mysql-python (Python 2)

pip install mysqlclient (Python 3)

postgres

pip install psycopg2

mssql

pip install pymssql

See also

Refer to SQLAlchemy’s documentation for more information about the different dialects it supports.

Note

Plugins originally written for Sopel 6.x and older might not work correctly with db_types other than sqlite.

db_user

The user for Sopel’s database.

Ignored when using SQLite.

default_time_format

The default format to use for time in messages.

Default

%Y-%m-%d - %T%Z

Used when plugins format times with sopel.tools.time.format_time().

See also

Time format reference is available in the documentation for Python’s time.strftime() function.

default_timezone

The default timezone to use for time in messages.

Default

UTC

Used when plugins format times with sopel.tools.time.format_time().

enable

A list of the only plugins you want to enable.

If set, Sopel will only load the plugins named here. All other available plugins will be ignored.

To load all available plugins, clear this setting.

To disable only a few plugins, see exclude.

See Plugins for an overview of all plugin-related settings.

exclude

A list of plugins which should not be loaded.

If set, Sopel will load all available plugins except those named here.

A plugin named both here and in enable will not be loaded; exclude takes priority.

See Plugins for an overview of all plugin-related settings.

extra

A list of other directories in which to search for plugin files.

See Plugins for an overview of all plugin-related settings.

flood_burst_lines

How many messages can be sent in burst mode.

Default

4

See Flood Prevention to learn what each flood-related setting does.

New in version 7.0.

flood_empty_wait

How long to wait between sending messages when not in burst mode, in seconds.

Default

0.7

See Flood Prevention to learn what each flood-related setting does.

New in version 7.0.

flood_refill_rate

How quickly burst mode recovers, in messages per second.

Default

1

See Flood Prevention to learn what each flood-related setting does.

New in version 7.0.

help_prefix

The prefix to use in help output.

Default

.

If prefix is changed from the default, this setting must be updated to reflect the prefix your bot will actually respond to, or the built-in help functionality will provide incorrect example usage.

property homedir

The directory in which various files are stored at runtime.

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

host

The IRC server to connect to.

Default

chat.freenode.net

Required.

host_blocks

A list of hostnames which Sopel should ignore.

Messages from any user whose connection hostname matches one of these values will be ignored. Regular expression syntax is supported.

Also see the nick_blocks list.

log_raw

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

See Raw Logs.

logdir

Directory in which to place logs.

See Logging.

logging_channel

The channel to send logging messages to.

See Log to a Channel.

logging_channel_datefmt

The format string to use for timestamps in IRC channel logs.

If not specified, this falls back to using logging_datefmt.

See Log to a Channel.

New in version 7.0.

See also

Time format reference is available in the documentation for Python’s time.strftime() function.

logging_channel_format

The logging format string to use in IRC channel logs.

If not specified, this falls back to using logging_format.

See Log to a Channel.

New in version 7.0.

logging_channel_level

The lowest severity of logs to display in IRC channel logs.

If not specified, this falls back to using logging_level.

See Log to a Channel.

New in version 7.0.

logging_datefmt

The format string to use for timestamps in logs.

If not set, the datefmt argument is not provided, and logging will use the Python default.

New in version 7.0.

See also

Time format reference is available in the documentation for Python’s time.strftime() function.

logging_format

The logging format string to use for logs.

Default

[%(asctime)s] %(name)-20s %(levelname)-8s - %(message)s

The default log line format will output the timestamp, the package that generated the log line, the log level of the line, and (finally) the actual message. For example:

[2019-10-21 12:47:44,272] sopel.irc            INFO     - Connected.

New in version 7.0.

See also

Python’s logging format documentation: LogRecord attributes

logging_level

The lowest severity of logs to display.

Default

INFO

Valid values sorted by increasing verbosity:

  • CRITICAL

  • ERROR

  • WARNING

  • INFO

  • DEBUG

modes

User modes to be set on connection.

Default

B

Include only the mode letters; this value is automatically prefixed with + before Sopel sends the MODE command to IRC.

name

The “real name” of your bot for WHOIS responses.

Default

Sopel: https://sopel.chat/

nick

The nickname for the bot.

Default

Sopel

Required.

nick_auth_method

The nick authentication method.

Can be one of nickserv, authserv, Q, or userserv.

See Authentication for more details.

New in version 7.0.

nick_auth_password

The password to use to authenticate the bot’s nick.

See Authentication for more details.

New in version 7.0.

nick_auth_target

The target user for nick authentication.

Default

NickServ for nickserv authentication; UserServ for userserv authentication

May not apply, depending on the chosen nick_auth_method. See Authentication for more details.

New in version 7.0.

nick_auth_username

The username/account to use for nick authentication.

Default

the value of nick

May not apply, depending on the chosen nick_auth_method. See Authentication for more details.

New in version 7.0.

nick_blocks

A list of nicks which Sopel should ignore.

Messages from any user whose nickname matches one of these values will be ignored. Regular expression syntax is supported.

Also see the host_blocks list.

not_configured

For package maintainers. Not used in normal configurations.

Default

False

This allows software packages to install a default config file, with this option 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.

Required even if owner_account is set.

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.

Default

.

If the given value is not an absolute path, it will be interpreted relative to the directory containing the config file with which Sopel was started.

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

port

The port to connect on.

Default

6667 normally; 6697 if use_ssl is True

Required.

prefix

The prefix to add to the beginning of commands.

Default

\.

Required.

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 reply to the sender of a message that triggered an error.

Default

True

If True, Sopel will send information about the triggered exception to the sender of the message that caused the error.

If False, Sopel will only log the error and will appear to fail silently from the triggering IRC user’s perspective.

server_auth_method

The server authentication method.

Can be sasl or server.

New in version 7.0.

server_auth_password

The password to use to authenticate with the server.

New in version 7.0.

server_auth_sasl_mech

The SASL mechanism.

Default

PLAIN

New in version 7.0.

server_auth_username

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

New in version 7.0.

throttle_join

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

Default

0

Sopel will only join this many channels at a time, sleeping for a second between each batch to avoid getting kicked for joining too quickly. This is unnecessary on most networks.

If not set, or set to 0, Sopel won’t slow down the initial join.

See also

throttle_wait controls Sopel’s waiting time between joining batches of channels.

throttle_wait

Time in seconds Sopel waits between joining batches of channels.

Default

1

For example, with throttle_join = 2 and throttle_wait = 5 it will wait 5s every 2 channels it joins.

If throttle_join is 0, this setting has no effect.

See also

throttle_join controls channel batch size.

timeout

The number of seconds acceptable between pings before timing out.

Default

120

use_ssl

Whether to use a SSL/TLS encrypted connection.

Default

False

user

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

Default

sopel

Required.

verify_ssl

Whether to require a trusted certificate for encrypted connections.

Default

True

sopel.config.core_section.configure(config)

Interactively configure the bot’s [core] config section.

Parameters

config (Config) – the bot’s config object