Internal machinery

Important

This section contains modules and classes used by Sopel internally. They are subject to rapid changes between versions. They are documented here for completeness, and for the aid of Sopel’s core development.

sopel.loader

Utility functions to manage plugin callables from a Python module.

Important

Its usage and documentation is for Sopel core development and advanced developers. It is subject to rapid changes between versions without much (or any) warning.

Do not build your plugin based on what is here, you do not need to.

sopel.loader.clean_callable(func, config)

Clean the callable. (compile regexes, fix docs, set defaults)

Parameters
  • func (callable) – the callable to clean

  • config (sopel.config.Config) – Sopel’s settings

This function will set all the default attributes expected for a Sopel callable, i.e. properties related to threading, docs, examples, rate limiting, commands, rules, and other features.

sopel.loader.clean_module(module, config)

Clean a module and return its command, rule, job, etc. callables.

Parameters
Returns

a tuple with triggerable, job, shutdown, and url functions

Return type

tuple

This function will parse the module looking for callables:

  • shutdown actions

  • triggerables (commands, rules, etc.)

  • jobs

  • URL callbacks

This function will set all the default attributes expected for a Sopel callable, i.e. properties related to threading, docs, examples, rate limiting, commands, rules, and other features.

sopel.loader.is_limitable(obj)

Check if obj needs to carry attributes related to limits.

Parameters

obj – any function to check

Returns

True if obj must have limit-related attributes

Limitable callables aren’t necessarily triggerable directly, but they all must pass through Sopel’s rate-limiting machinery during dispatching. Therefore, they must have the attributes checked by that machinery.

sopel.loader.is_triggerable(obj)

Check if obj can handle the bot’s triggers.

Parameters

obj – any function to check

Returns

True if obj can handle the bot’s triggers

A triggerable is a callable that will be used by the bot to handle a particular trigger (i.e. an IRC message): it can be a regex rule, an event, an intent, a command, a nickname command, or an action command. However, it must not be a job or a URL callback.

See also

Many of the decorators defined in sopel.plugin make the decorated function a triggerable object.

sopel.loader.is_url_callback(obj)

Check if obj can handle a URL callback.

Parameters

obj – any function to check

Returns

True if obj can handle a URL callback

A URL callback handler is a callable that will be used by the bot to handle a particular URL in an IRC message.

See also

Both sopel.plugin.url() sopel.plugin.url_lazy() make the decorated function a URL callback handler.

sopel.loader.itervalues()

D.values() -> an object providing a view on D’s values

sopel.loader.trim_docstring(doc)

Get the docstring as a series of lines that can be sent.

Parameters

doc (str) – a callable’s docstring to trim

Returns

a list of trimmed lines

Return type

list

This function acts like inspect.cleandoc() but doesn’t replace tabs, and instead of a str it returns a list.

sopel.plugins

Sopel’s plugins interface.

New in version 7.0.

Sopel uses what are called Plugin Handlers as an interface between the bot and its plugins (formerly called “modules”). This interface is defined by the AbstractPluginHandler abstract class.

Plugins that can be used by Sopel are provided by get_usable_plugins() in an ordered dict. This dict contains one and only one plugin per unique name, using a specific order:

  • extra directories defined in the settings

  • homedir’s plugins directory

  • homedir’s modules directory

  • sopel.plugins setuptools entry points

  • sopel_modules’s subpackages

  • sopel.modules’s core plugins

(The coretasks plugin is always the one from sopel.coretasks and cannot be overridden.)

To find all plugins (no matter their sources), the enumerate_plugins() function can be used. For a more fine-grained search, find_* functions exist for each type of plugin.

sopel.plugins.enumerate_plugins(settings)

Yield Sopel’s plugins.

Parameters

settings (sopel.config.Config) – Sopel’s configuration

Returns

yield 2-value tuple: an instance of AbstractPluginHandler, and if the plugin is active or not

This function uses the find functions to find all of Sopel’s available plugins. It uses the bot’s settings to determine if the plugin is enabled or disabled.

See also

The find functions used are:

Changed in version 7.0: Previously, plugins were called “modules”, so this would load plugins from the $homedir/modules directory. Now it also loads plugins from the $homedir/plugins directory.

sopel.plugins.find_directory_plugins(directory)

List plugins from a directory.

Parameters

directory (str) – directory path to search

Returns

yield instances of PyFilePlugin found in directory

This function looks for single file and folder plugins in a directory.

sopel.plugins.find_entry_point_plugins(group='sopel.plugins')

List plugins from a setuptools entry point group.

Parameters

group (str) – setuptools entry point group to look for (defaults to sopel.plugins)

Returns

yield instances of EntryPointPlugin created from setuptools entry point given group

This function finds plugins declared under a setuptools entry point; by default it uses the sopel.plugins entry point.

sopel.plugins.find_internal_plugins()

List internal plugins.

Returns

yield instances of PyModulePlugin configured for sopel.modules.*

Internal plugins can be found under sopel.modules. This list does not include the coretasks plugin.

sopel.plugins.find_sopel_modules_plugins()

List plugins from sopel_modules.*.

Returns

yield instances of PyModulePlugin configured for sopel_modules.*

Before entry point plugins, the only way to package a plugin was to follow PEP 382 by using the sopel_modules namespace. This function is responsible to load such plugins.

sopel.plugins.get_usable_plugins(settings)

Get usable plugins, unique per name.

Parameters

settings (sopel.config.Config) – Sopel’s configuration

Returns

an ordered dict of usable plugins

Return type

collections.OrderedDict

This function provides the plugins Sopel can use to load, enable, or disable, as an ordered dict. This dict contains one and only one plugin per unique name, using a specific order:

  • extra directories defined in the settings

  • homedir’s modules directory

  • sopel.plugins setuptools entry points

  • sopel_modules’s subpackages

  • sopel.modules’s core plugins

(The coretasks plugin is always the one from sopel.coretasks and cannot be overridden.)

See also

The enumerate_plugins() function is used to generate a list of all possible plugins, and its return value is used to populate the ordered dict.

sopel.plugins.exceptions

Sopel’s plugins exceptions.

exception sopel.plugins.exceptions.PluginError

Base class for plugin related exceptions.

exception sopel.plugins.exceptions.PluginNotRegistered(name)

Exception raised when a plugin is not registered.

exception sopel.plugins.exceptions.PluginSettingsError

Exception raised when a plugin is not properly configured.

This can be used in any place where a plugin requires a specific config, for example in its setup function, in any of its rules or commands, and in the loader function for the sopel.plugin.url_lazy() decorator.

sopel.plugins.handlers

Sopel’s plugin handlers.

New in version 7.0.

Between a plugin (or “module”) and Sopel’s core, Plugin Handlers are used. It is an interface (defined by the AbstractPluginHandler abstract class), that acts as a proxy between Sopel and the plugin, making a clear separation between how the bot behaves and how the plugins work.

From the Sopel class, a plugin must be:

Each subclass of AbstractPluginHandler must implement its methods in order to be used in the application.

At the moment, three types of plugin are handled:

  • PyModulePlugin: manage plugins that can be imported as Python module from a Python package, i.e. where from package import name works

  • PyFilePlugin: manage plugins that are Python files on the filesystem or Python directory (with an __init__.py file inside), that cannot be directly imported and extra steps are necessary

  • EntryPointPlugin: manage plugins that are declared by a setuptools entry point; other than that, it behaves like a PyModulePlugin

All expose the same interface and thereby abstract the internal implementation away from the rest of the application.

Important

This is all relatively new. Its usage and documentation is for Sopel core development and advanced developers. It is subject to rapid changes between versions without much (or any) warning.

Do not build your plugin based on what is here, you do not need to.

class sopel.plugins.handlers.AbstractPluginHandler

Base class for plugin handlers.

This abstract class defines the interface Sopel uses to configure, load, shutdown, etc. a Sopel plugin (or “module”).

It is through this interface that Sopel will interact with its plugins, whether internal (from sopel.modules) or external (from the Python files in a directory, to sopel_modules.* subpackages).

Sopel’s loader will create a “Plugin Handler” for each plugin it finds, to which it then delegates loading the plugin, listing its functions (commands, jobs, etc.), configuring it, and running any required actions on shutdown (either upon exiting Sopel or unloading that plugin).

configure(settings)

Configure Sopel’s settings for this plugin.

Parameters

settings (sopel.config.Config) – Sopel’s configuration

This method will be called by Sopel’s configuration wizard.

get_label()

Retrieve a display label for the plugin.

Returns

a human readable label for display purpose

Return type

str

This method should, at least, return <module_name> plugin.

get_meta_description()

Retrieve a meta description for the plugin.

Returns

meta description information

Return type

dict

The expected keys are:

  • name: a short name for the plugin

  • label: a descriptive label for the plugin

  • type: the plugin’s type

  • source: the plugin’s source (filesystem path, python import path, etc.)

has_configure()

Tell if the plugin has a configure action.

Returns

True if the plugin has a configure action, False otherwise

Return type

bool

has_setup()

Tell if the plugin has a setup action.

Returns

True if the plugin has a setup, False otherwise

Return type

bool

has_shutdown()

Tell if the plugin has a shutdown action.

Returns

True if the plugin has a shutdown action, False otherwise

Return type

bool

is_loaded()

Tell if the plugin is loaded or not.

Returns

True if the plugin is loaded, False otherwise

Return type

bool

This must return True if the load() method has been called with success.

load()

Load the plugin.

This method must be called first, in order to setup, register, shutdown, or configure the plugin later.

register(bot)

Register the plugin with the bot.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

reload()

Reload the plugin.

This method can be called once the plugin is already loaded. It will take care of reloading the plugin from its source.

setup(bot)

Run the plugin’s setup action.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

shutdown(bot)

Run the plugin’s shutdown action.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

unregister(bot)

Unregister the plugin from the bot.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

class sopel.plugins.handlers.EntryPointPlugin(entry_point)

Sopel plugin loaded from a setuptools entry point.

Parameters

entry_point – a setuptools entry point object

This handler loads a Sopel plugin exposed by a setuptools entry point. It expects to be able to load a module object from the entry point, and to work as a PyModulePlugin from that module.

By default, Sopel uses the entry point sopel.plugins. To use that for their plugin, developers must define an entry point either in their setup.py file or their setup.cfg file:

# in setup.py file
setup(
    name='my_plugin',
    version='1.0',
    entry_points={
        'sopel.plugins': [
            'custom = my_plugin.path.to.plugin',
        ],
    }
)

And this plugin can be loaded with:

>>> from pkg_resources import iter_entry_points
>>> from sopel.plugins.handlers import EntryPointPlugin
>>> plugin = [
...     EntryPointPlugin(ep)
...     for ep in iter_entry_points('sopel.plugins', 'custom')
... ][0]
>>> plugin.load()
>>> plugin.name
'custom'

In this example, the plugin custom is loaded from an entry point. Unlike the PyModulePlugin, the name is not derived from the actual Python module, but from its entry point’s name.

See also

Sopel uses the find_entry_point_plugins() function internally to search entry points.

Entry point is a standard feature of setuptools for Python, used by other applications (like pytest) for their plugins.

PLUGIN_TYPE = 'setup-entrypoint'

The plugin’s type.

Metadata for the plugin; this should be considered to be a constant and should not be modified at runtime.

get_meta_description()

Retrieve a meta description for the plugin.

Returns

meta description information

Return type

dict

This returns the same keys as PyModulePlugin.get_meta_description(); the source key is modified to contain the setuptools entry point:

{
    'name': 'example',
    'type: 'setup-entrypoint',
    'label: 'example plugin',
    'source': 'example = my_plugin.example',
}
load()

Load the plugin’s module using importlib.import_module().

This method assumes the module is available through sys.path.

class sopel.plugins.handlers.PyFilePlugin(filename)

Sopel plugin loaded from the filesystem outside of the Python path.

This plugin handler can be used to load a Sopel plugin from the filesystem, either a Python .py file or a directory containing an __init__.py file, and behaves like a PyModulePlugin:

>>> from sopel.plugins.handlers import PyFilePlugin
>>> plugin = PyFilePlugin('/home/sopel/.sopel/modules/custom.py')
>>> plugin.load()
>>> plugin.name
'custom'

In this example, the plugin custom is loaded from its filename despite not being in the Python path.

PLUGIN_TYPE = 'python-file'

The plugin’s type.

Metadata for the plugin; this should be considered to be a constant and should not be modified at runtime.

get_meta_description()

Retrieve a meta description for the plugin.

Returns

meta description information

Return type

dict

This returns the same keys as PyModulePlugin.get_meta_description(); the source key is modified to contain the source file’s path instead of its Python module dotted path:

{
    'name': 'example',
    'type: 'python-file',
    'label: 'example plugin',
    'source': '/home/username/.sopel/plugins/example.py',
}
load()

Load the plugin’s module using importlib.import_module().

This method assumes the module is available through sys.path.

reload()

Reload the plugin.

Unlike PyModulePlugin, it is not possible to use the reload function (either from imp or importlib), because the module might not be available through sys.path.

class sopel.plugins.handlers.PyModulePlugin(name, package=None)

Sopel plugin loaded from a Python module or package.

A PyModulePlugin represents a Sopel plugin that is a Python module (or package) that can be imported directly.

This:

>>> import sys
>>> from sopel.plugins.handlers import PyModulePlugin
>>> plugin = PyModulePlugin('xkcd', 'sopel.modules')
>>> plugin.module_name
'sopel.modules.xkcd'
>>> plugin.load()
>>> plugin.module_name in sys.modules
True

Is the same as this:

>>> import sys
>>> from sopel.modules import xkcd
>>> 'sopel.modules.xkcd' in sys.modules
True
PLUGIN_TYPE = 'python-module'

The plugin’s type.

Metadata for the plugin; this should be considered to be a constant and should not be modified at runtime.

configure(settings)

Configure Sopel’s settings for this plugin.

Parameters

settings (sopel.config.Config) – Sopel’s configuration

This method will be called by Sopel’s configuration wizard.

get_label()

Retrieve a display label for the plugin.

Returns

a human readable label for display purpose

Return type

str

By default, this is <name> plugin. If the plugin’s module has a docstring, its first line is used as the plugin’s label.

get_meta_description()

Retrieve a meta description for the plugin.

Returns

meta description information

Return type

dict

The keys are:

  • name: the plugin’s name

  • label: see get_label()

  • type: see PLUGIN_TYPE

  • source: the name of the plugin’s module

Example:

{
    'name': 'example',
    'type: 'python-module',
    'label: 'example plugin',
    'source': 'sopel_modules.example',
}
has_configure()

Tell if the plugin has a configure action.

Returns

True if the plugin has a configure action, False otherwise

Return type

bool

The plugin has a configure action if its module has a configure attribute. This attribute is expected to be a callable.

has_setup()

Tell if the plugin has a setup action.

Returns

True if the plugin has a setup, False otherwise

Return type

bool

The plugin has a setup action if its module has a setup attribute. This attribute is expected to be a callable.

has_shutdown()

Tell if the plugin has a shutdown action.

Returns

True if the plugin has a shutdown action, False otherwise

Return type

bool

The plugin has a shutdown action if its module has a shutdown attribute. This attribute is expected to be a callable.

is_loaded()

Tell if the plugin is loaded or not.

Returns

True if the plugin is loaded, False otherwise

Return type

bool

This must return True if the load() method has been called with success.

load()

Load the plugin’s module using importlib.import_module().

This method assumes the module is available through sys.path.

register(bot)

Register the plugin with the bot.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

reload()

Reload the plugin’s module using importlib.reload().

This method assumes the plugin is already loaded.

setup(bot)

Run the plugin’s setup action.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

shutdown(bot)

Run the plugin’s shutdown action.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

unregister(bot)

Unregister the plugin from the bot.

Parameters

bot (sopel.bot.Sopel) – instance of Sopel

sopel.plugins.jobs

Sopel’s plugin jobs management.

New in version 7.1.

Important

This is all fresh and new. Its usage and documentation is for Sopel core development and advanced developers. It is subject to rapid changes between versions without much (or any) warning.

Do not build your plugin based on what is here, you do not need to.

class sopel.plugins.jobs.Scheduler(manager)

Bases: sopel.tools.jobs.Scheduler

Plugin job scheduler.

Parameters

manager (sopel.bot.Sopel) – bot instance passed to jobs as argument

Scheduler that stores plugin jobs and behaves like its parent class.

New in version 7.1.

Note

This class is a specific implementation of the scheduler, made to store jobs by their plugins and be used by the bot (its manager). It follows a similar interface as the plugin rules manager.

Important

This is an internal tool used by Sopel to manage its jobs. To register a job, plugin authors should use sopel.plugin.interval().

clear_jobs()

Clear current Job queue and start fresh.

This method is thread safe. However, it won’t cancel or stop any currently running jobs.

register(job)

Register a Job to the current job queue.

Parameters

job (sopel.tools.jobs.Job) – job to register

This method is thread safe.

remove_callable_job(callable)

Remove callable from the job queue.

Parameters

callable (function) – the callable to remove

This method is thread safe. However, it won’t cancel or stop any currently running jobs.

unregister_plugin(plugin_name)

Unregister all the jobs from a plugin.

Parameters

plugin_name (str) – the name of the plugin to remove

Returns

the number of jobs unregistered for this plugin

Return type

int

All jobs of that plugin will be removed from the scheduler.

This method is thread safe. However, it won’t cancel or stop any currently running jobs.

sopel.plugins.rules

Sopel’s plugin rules management.

New in version 7.1.

Important

This is all fresh and new. Its usage and documentation is for Sopel core development and advanced developers. It is subject to rapid changes between versions without much (or any) warning.

Do not build your plugin based on what is here, you do not need to.

class sopel.plugins.rules.AbstractRule

Abstract definition of a plugin’s rule.

Any rule class must be an implementation of this abstract class, as it defines the Rule interface:

  • plugin name

  • priority

  • label

  • doc, usages, and tests

  • output prefix

  • matching patterns, events, and intents

  • allow echo-message

  • threaded execution or not

  • rate limiting feature

  • text parsing

  • and finally, trigger execution (i.e. actually doing something)

allow_echo()

Tell if the rule should match echo messages.

Returns

True when the rule allows echo messages, False otherwise

Return type

bool

execute(bot, trigger)

Execute the triggered rule.

Parameters

This is the method called by the bot when a rule matches a trigger.

classmethod from_callable(settings, handler)

Instantiate a rule object from settings and handler.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler

Returns

an instance of this class created from the handler

Return type

AbstractRule

Sopel’s function-based rule handlers are simple callables, decorated with sopel.plugin’s decorators to add attributes, such as rate limit, threaded execution, output prefix, priority, and so on. In order to load these functions as rule objects, this class method can be used; it takes the bot’s settings and a cleaned handler.

A “cleaned handler” is a function, decorated appropriately, and passed through the filter of the loader's clean function.

get_doc()

Get the rule’s documentation.

Return type

str

A rule’s documentation is a short text that can be displayed to a user on IRC upon asking for help about this rule. The equivalent of Python docstrings, but for IRC rules.

get_output_prefix()

Get the rule’s output prefix.

Return type

str

See also

See the sopel.bot.SopelWrapper class for more information on how the output prefix can be used.

get_plugin_name()

Get the rule’s plugin name.

Return type

str

The rule’s plugin name will be used in various places to select, register, unregister, and manipulate the rule based on its plugin, which is referenced by its name.

get_priority()

Get the rule’s priority.

Return type

str

A rule can have a priority, based on the three pre-defined priorities used by Sopel: PRIORITY_HIGH, PRIORITY_MEDIUM, and PRIORITY_LOW.

See also

The AbstractRule.priority_scale property uses this method to look up the numeric priority value, which is used to sort rules by priority.

get_rule_label()

Get the rule’s label.

Return type

str

A rule can have a label, which can identify the rule by string, the same way a plugin can be identified by its name. This label can be used to select, register, unregister, and manipulate the rule based on its own label. Note that the label has no effect on the rule’s execution.

get_test_parameters()

Get parameters for automated tests.

Return type

tuple

A rule can have automated tests attached to it, and this method must return the test parameters:

  • the expected IRC line

  • the expected line of results, as said by the bot

  • if the user should be an admin or not

  • if the results should be used as regex pattern

See also

sopel.plugin.example() for more about test parameters.

get_usages()

Get the rule’s usage examples.

Return type

tuple

A rule can have usage examples, i.e. a list of examples showing how the rule can be used, or in what context it can be triggered.

is_channel_rate_limited(channel)

Tell when the rule reached the channel’s rate limit.

Returns

True when the rule reached the limit, False otherwise

Return type

bool

is_global_rate_limited()

Tell when the rule reached the server’s rate limit.

Returns

True when the rule reached the limit, False otherwise

Return type

bool

is_rate_limited(nick)

Tell when the rule reached the nick’s rate limit.

Returns

True when the rule reached the limit, False otherwise

Return type

bool

is_threaded()

Tell if the rule’s execution should be in a thread.

Returns

True if the execution should be in a thread, False otherwise

Return type

bool

is_unblockable()

Tell if the rule is unblockable.

Returns

True when the rule is unblockable, False otherwise

Return type

bool

match(bot, pretrigger)

Match a pretrigger according to the rule.

Parameters

This method must return a list of match objects.

match_event(event)

Tell if the rule matches this event.

Parameters

event (str) – potential matching event

Returns

True when event matches the rule, False otherwise

Return type

bool

match_intent(intent)

Tell if the rule matches this intent.

Parameters

intent (str) – potential matching intent

Returns

True when intent matches the rule, False otherwise

Return type

bool

parse(text)

Parse text and yield matches.

Parameters

text (str) – text to parse by the rule

Returns

yield a list of match object

Return type

generator of re.match

property priority_scale

Rule’s priority on a numeric scale.

This attribute can be used to sort rules between each other, the highest priority rules coming first. The default priority for a rule is “medium”.

class sopel.plugins.rules.NamedRuleMixin

Mixin for named rules.

A named rule is invoked by using a specific word, and is usually known as a “command”. For example, the command “hello” is triggered by using the word “hello” with some sort of prefix or context.

A named rule can be invoked by using one of its aliases, also.

property aliases
escape_name(name)

Escape the provided name if needed.

Note

Until now, Sopel has allowed command name to be regex pattern. It was mentioned in the documentation without much details, and there were no tests for it.

In order to ensure backward compatibility with previous versions of Sopel, we make sure to escape command name only when it’s needed.

It is not recommended to use a regex pattern for your command name. This feature will be removed in Sopel 8.0.

get_rule_label()

Get the rule’s label.

Return type

str

A named rule’s label is its name.

has_alias(name)

Tell when name is one of the rule’s aliases.

Parameters

name (str) – potential alias name

Returns

True when name is an alias, False otherwise

Return type

bool

property name
class sopel.plugins.rules.ActionCommand(name, aliases=None, **kwargs)

Bases: sopel.plugins.rules.NamedRuleMixin, sopel.plugins.rules.Rule

Action Command rule definition.

An action command rule is a named rule that can be triggered only when the trigger’s intent is an ACTION. Like the Command rule, it allows command aliases.

Here is an example with the dummy action command:

> user dummy
<Bot> You just invoked the action command 'dummy'
> user dummy-alias
<Bot> You just invoked the action command 'dummy' (as 'dummy-alias')

Apart from that, it behaves exactly like a generic rule.

classmethod from_callable(settings, handler)

Instantiate a rule object from settings and handler.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler

Returns

an instance of this class created from the handler

Return type

AbstractRule

Sopel’s function-based rule handlers are simple callables, decorated with sopel.plugin’s decorators to add attributes, such as rate limit, threaded execution, output prefix, priority, and so on. In order to load these functions as rule objects, this class method can be used; it takes the bot’s settings and a cleaned handler.

A “cleaned handler” is a function, decorated appropriately, and passed through the filter of the loader's clean function.

get_rule_regex()

Make the rule regex for this action command.

Returns

a compiled regex for this action command and its aliases

The command regex factors in:

  • the rule’s name (escaped for regex if needed),

  • all of its aliases (escaped for regex if needed),

to create a compiled regex to return.

match_intent(intent)

Tell if intent is an ACTION.

Parameters

intent (str) – potential matching intent

Returns

True when intent matches ACTION, False otherwise

Return type

bool

class sopel.plugins.rules.Command(name, prefix='\\.', help_prefix='.', aliases=None, **kwargs)

Bases: sopel.plugins.rules.NamedRuleMixin, sopel.plugins.rules.Rule

Command rule definition.

A command rule (or simply “a command”) is a named rule, i.e. it has a known name and must be invoked using that name (or one of its aliases, if any). Apart from that, it behaves exactly like a generic rule.

Here is an example with the dummy command:

<user> .dummy
<Bot> You just invoked the command 'dummy'
<user> .dummy-alias
<Bot> You just invoked the command 'dummy' (as 'dummy-alias')
classmethod from_callable(settings, handler)

Instantiate a rule object from settings and handler.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler

Returns

an instance of this class created from the handler

Return type

AbstractRule

Sopel’s function-based rule handlers are simple callables, decorated with sopel.plugin’s decorators to add attributes, such as rate limit, threaded execution, output prefix, priority, and so on. In order to load these functions as rule objects, this class method can be used; it takes the bot’s settings and a cleaned handler.

A “cleaned handler” is a function, decorated appropriately, and passed through the filter of the loader's clean function.

get_rule_regex()

Make the rule regex for this command.

Returns

a compiled regex for this command and its aliases

The command regex factors in:

  • the prefix regular expression,

  • the rule’s name (escaped for regex if needed),

  • all of its aliases (escaped for regex if needed),

to create a compiled regex to return.

get_usages()

Get the rule’s usage examples.

Return type

tuple

A rule can have usage examples, i.e. a list of examples showing how the rule can be used, or in what context it can be triggered.

class sopel.plugins.rules.FindRule(regexes, plugin=None, label=None, priority='medium', handler=None, events=None, intents=None, allow_echo=False, threaded=True, output_prefix=None, unblockable=False, rate_limit=0, channel_rate_limit=0, global_rate_limit=0, usages=None, tests=None, doc=None)

Bases: sopel.plugins.rules.Rule

Anonymous find rule definition.

A find rule is like an anonymous rule with a twist: instead of matching only once per IRC line, a find rule will execute for each non-overlapping match for each of its regular expressions.

For example, to match for each word starting with the letter h in a line, you can use the pattern h\w+:

<user> hello here
<Bot> Found the word "hello"
<Bot> Found the word "here"
<user> sopelunker, how are you?
<Bot> Found the word "how"

See also

This rule uses re.finditer(). To know more about how it works, see the official Python documentation.

parse(text)

Parse text and yield matches.

Parameters

text (str) – text to parse by the rule

Returns

yield a list of match object

Return type

generator of re.match

class sopel.plugins.rules.Manager

Bases: object

Manager of plugin rules.

This manager stores plugin rules and can then provide the matching rules for a given trigger.

To register a rule:

Then to match the rules against a trigger, see the get_triggered_rules(), which returns a list of (rule, match), sorted by priorities (high first, medium second, and low last).

check_url_callback(bot, url)

Tell if the url matches any of the registered URL callbacks.

Parameters
Returns

True when url matches any URL callbacks, False otherwise

Return type

bool

get_all_action_commands()

Retrieve all the registered action commands, by plugin.

Returns

a list of 2-value tuples as (key, value), where each key is a plugin name, and the value is a dict of its action commands

get_all_commands()

Retrieve all the registered commands, by plugin.

Returns

a list of 2-value tuples as (key, value), where each key is a plugin name, and the value is a dict of its commands

get_all_generic_rules()

Retrieve all the registered generic rules, by plugin.

Returns

a list of 2-value tuples as (key, value), where each key is a plugin name, and the value is a list of its generic rules

get_all_nick_commands()

Retrieve all the registered nick commands, by plugin.

Returns

a list of 2-value tuples as (key, value), where each key is a plugin name, and the value is a dict of its nick commands

get_all_url_callbacks()

Retrieve all the registered URL callbacks, by plugin.

Returns

a list of 2-value tuples as (key, value), where each key is a plugin name, and the value is a list of its URL callbacks

get_triggered_rules(bot, pretrigger)

Get triggered rules with their match objects, sorted by priorities.

Parameters
Returns

a tuple of (rule, match), sorted by priorities

Return type

tuple

has_action_command(name, follow_alias=True, plugin=None)

Tell if the manager knows an action command with this name.

Parameters
  • label (str) – the label of the rule to look for

  • follow_alias (bool) – optional flag to include aliases

  • plugin (str) – optional filter on the plugin name

Returns

True if the command exists, False otherwise

Return type

bool

This method works like has_command(), but with action commands.

has_command(name, follow_alias=True, plugin=None)

Tell if the manager knows a command with this name.

Parameters
  • label (str) – the label of the rule to look for

  • follow_alias (bool) – optional flag to include aliases

  • plugin (str) – optional filter on the plugin name

Returns

True if the command exists, False otherwise

Return type

bool

By default, this method follows aliases to search commands. If the optional parameter follow_alias is False, then it won’t find commands by their aliases:

>>> command = Command('hi', prefix='"', aliases=['hey'])
>>> manager.register_command(command)
>>> manager.has_command('hi')
True
>>> manager.has_command('hey')
True
>>> manager.has_command('hey', follow_alias=False)
False

The optional parameter plugin can be provided to limit the commands to the ones of said plugin.

has_nick_command(name, follow_alias=True, plugin=None)

Tell if the manager knows a nick command with this name.

Parameters
  • label (str) – the label of the rule to look for

  • follow_alias (bool) – optional flag to include aliases

  • plugin (str) – optional filter on the plugin name

Returns

True if the command exists, False otherwise

Return type

bool

This method works like has_command(), but with nick commands.

has_rule(label, plugin=None)

Tell if the manager knows a rule with this label.

Parameters
  • label (str) – the label of the rule to look for

  • plugin (str) – optional filter on the plugin name

Returns

True if the rule exists, False otherwise

Return type

bool

The optional parameter plugin can be provided to limit the rules to only those from that plugin.

has_url_callback(label, plugin=None)

Tell if the manager knows a URL callback with this label.

Parameters
  • label (str) – the label of the URL callback to look for

  • plugin (str) – optional filter on the plugin name

Returns

True if the URL callback exists, False otherwise

Return type

bool

The optional parameter plugin can be provided to limit the URL callbacks to only those from that plugin.

register(rule)

Register a plugin rule.

Parameters

rule (Rule) – the rule to register

register_action_command(command)

Register a plugin action command.

Parameters

command (ActionCommand) – the action command to register

register_command(command)

Register a plugin command.

Parameters

command (Command) – the command to register

register_nick_command(command)

Register a plugin nick command.

Parameters

command (NickCommand) – the nick command to register

register_url_callback(url_callback)

Register a plugin URL callback.

Parameters

url_callback (URLCallback) – the URL callback to register

unregister_plugin(plugin_name)

Unregister all the rules from a plugin.

Parameters

plugin_name (str) – the name of the plugin to remove

Returns

the number of rules unregistered for this plugin

Return type

int

All rules, commands, nick commands, and action commands of that plugin will be removed from the manager.

class sopel.plugins.rules.NickCommand(nick, name, nick_aliases=None, aliases=None, **kwargs)

Bases: sopel.plugins.rules.NamedRuleMixin, sopel.plugins.rules.Rule

Nickname Command rule definition.

A nickname command rule is a named rule with a twist: instead of a prefix, the rule is triggered when the line starts with a registered nickname (or one of its aliases). The command’s name itself can have aliases too.

Here is an example with the dummy nickname command:

<user> BotName: dummy
<Bot> You just invoked the nick command 'dummy'
<user> AliasBotName: dummy
<Bot> You just invoked the nick command 'dummy'
<user> BotName: dummy-alias
<Bot> You just invoked the nick command 'dummy' (as 'dummy-alias')
<user> AliasBotName: dummy-alias
<Bot> You just invoked the nick command 'dummy' (as 'dummy-alias')

Apart from that, it behaves exactly like a generic rule.

classmethod from_callable(settings, handler)

Instantiate a rule object from settings and handler.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler

Returns

an instance of this class created from the handler

Return type

AbstractRule

Sopel’s function-based rule handlers are simple callables, decorated with sopel.plugin’s decorators to add attributes, such as rate limit, threaded execution, output prefix, priority, and so on. In order to load these functions as rule objects, this class method can be used; it takes the bot’s settings and a cleaned handler.

A “cleaned handler” is a function, decorated appropriately, and passed through the filter of the loader's clean function.

get_rule_regex()

Make the rule regex for this nick command.

Returns

a compiled regex for this nick command and its aliases

The command regex factors in:

  • the nicks to react to,

  • the rule’s name (escaped for regex),

  • all of its aliases (escaped for regex),

to create a compiled regex to return.

get_usages()

Get the rule’s usage examples.

Return type

tuple

A rule can have usage examples, i.e. a list of examples showing how the rule can be used, or in what context it can be triggered.

class sopel.plugins.rules.Rule(regexes, plugin=None, label=None, priority='medium', handler=None, events=None, intents=None, allow_echo=False, threaded=True, output_prefix=None, unblockable=False, rate_limit=0, channel_rate_limit=0, global_rate_limit=0, usages=None, tests=None, doc=None)

Bases: sopel.plugins.rules.AbstractRule

Generic rule definition.

A generic rule (or simply “a rule”) uses regular expressions to match at most once per IRC line per regular expression, i.e. you can trigger between 0 and the number of regex the rule has per IRC line.

Here is an example with a rule with the pattern r'hello (\w+)':

<user> hello here
<Bot> You triggered a rule, saying hello to "here"
<user> hello sopelunkers
<Bot> You triggered a rule, saying hello to "sopelunkers"

Generic rules are not triggered by any specific name, unlike commands which have names and aliases.

allow_echo()

Tell if the rule should match echo messages.

Returns

True when the rule allows echo messages, False otherwise

Return type

bool

execute(bot, trigger)

Execute the triggered rule.

Parameters

This is the method called by the bot when a rule matches a trigger.

classmethod from_callable(settings, handler)

Instantiate a rule object from settings and handler.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler

Returns

an instance of this class created from the handler

Return type

AbstractRule

Sopel’s function-based rule handlers are simple callables, decorated with sopel.plugin’s decorators to add attributes, such as rate limit, threaded execution, output prefix, priority, and so on. In order to load these functions as rule objects, this class method can be used; it takes the bot’s settings and a cleaned handler.

A “cleaned handler” is a function, decorated appropriately, and passed through the filter of the loader's clean function.

classmethod from_callable_lazy(settings, handler)

Instantiate a rule object from a handler with lazy-loaded regexes.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler with a lazy-loader for the regexes

Returns

an instance of this class created from the handler

Return type

AbstractRule

Similar to the from_callable() classmethod, it requires a rule handler decorated with sopel.plugin’s decorators.

Unlike the from_callable() classmethod, the regexes are not already attached to the handler: its loader functions will be used to get the rule’s regexes. See the sopel.plugin.rule_lazy() decorator for more information about the handler and the loaders’ signatures.

See also

The handler can have more than one loader attached. In that case, these loaders are chained with sopel.tools.chain_loaders().

get_doc()

Get the rule’s documentation.

Return type

str

A rule’s documentation is a short text that can be displayed to a user on IRC upon asking for help about this rule. The equivalent of Python docstrings, but for IRC rules.

get_output_prefix()

Get the rule’s output prefix.

Return type

str

See also

See the sopel.bot.SopelWrapper class for more information on how the output prefix can be used.

get_plugin_name()

Get the rule’s plugin name.

Return type

str

The rule’s plugin name will be used in various places to select, register, unregister, and manipulate the rule based on its plugin, which is referenced by its name.

get_priority()

Get the rule’s priority.

Return type

str

A rule can have a priority, based on the three pre-defined priorities used by Sopel: PRIORITY_HIGH, PRIORITY_MEDIUM, and PRIORITY_LOW.

See also

The AbstractRule.priority_scale property uses this method to look up the numeric priority value, which is used to sort rules by priority.

get_rule_label()

Get the rule’s label.

Return type

str

Raises

RuntimeError – when the label is undefined

Return its label if it has one, or the value of its handler’s __name__, if it has a handler. If both methods fail, a RuntimeError is raised because the rule has an undefined label.

get_test_parameters()

Get parameters for automated tests.

Return type

tuple

A rule can have automated tests attached to it, and this method must return the test parameters:

  • the expected IRC line

  • the expected line of results, as said by the bot

  • if the user should be an admin or not

  • if the results should be used as regex pattern

See also

sopel.plugin.example() for more about test parameters.

get_usages()

Get the rule’s usage examples.

Return type

tuple

A rule can have usage examples, i.e. a list of examples showing how the rule can be used, or in what context it can be triggered.

is_channel_rate_limited(channel)

Tell when the rule reached the channel’s rate limit.

Returns

True when the rule reached the limit, False otherwise

Return type

bool

is_global_rate_limited()

Tell when the rule reached the server’s rate limit.

Returns

True when the rule reached the limit, False otherwise

Return type

bool

is_rate_limited(nick)

Tell when the rule reached the nick’s rate limit.

Returns

True when the rule reached the limit, False otherwise

Return type

bool

is_threaded()

Tell if the rule’s execution should be in a thread.

Returns

True if the execution should be in a thread, False otherwise

Return type

bool

is_unblockable()

Tell if the rule is unblockable.

Returns

True when the rule is unblockable, False otherwise

Return type

bool

classmethod kwargs_from_callable(handler)

Generate the keyword arguments to create a new instance.

Parameters

handler (callable) – callable used to generate keyword arguments

Returns

a map of keyword arguments

Return type

dict

This classmethod takes the handler’s attributes to generate a map of keyword arguments for the class. This can be used by the from_callable() classmethod to instantiate a new rule object.

The expected attributes are the ones set by decorators from the sopel.plugin module.

match(bot, pretrigger)

Match a pretrigger according to the rule.

Parameters

This method must return a list of match objects.

match_event(event)

Tell if the rule matches this event.

Parameters

event (str) – potential matching event

Returns

True when event matches the rule, False otherwise

Return type

bool

match_intent(intent)

Tell if the rule matches this intent.

Parameters

intent (str) – potential matching intent

Returns

True when intent matches the rule, False otherwise

Return type

bool

parse(text)

Parse text and yield matches.

Parameters

text (str) – text to parse by the rule

Returns

yield a list of match object

Return type

generator of re.match

class sopel.plugins.rules.SearchRule(regexes, plugin=None, label=None, priority='medium', handler=None, events=None, intents=None, allow_echo=False, threaded=True, output_prefix=None, unblockable=False, rate_limit=0, channel_rate_limit=0, global_rate_limit=0, usages=None, tests=None, doc=None)

Bases: sopel.plugins.rules.Rule

Anonymous search rule definition.

A search rule is like an anonymous rule with a twist: it will execute exactly once per regular expression that matches anywhere in a line, not just from the start.

For example, to search if any word starts with the letter h in a line, you can use the pattern h\w+:

<user> hello here
<Bot> Found the word "hello"
<user> sopelunker, how are you?
<Bot> Found the word "how"

The match object it returns contains the first element that matches the expression in the line.

See also

This rule uses re.search(). To know more about how it works, see the official Python documentation.

parse(text)

Parse text and yield matches.

Parameters

text (str) – text to parse by the rule

Returns

yield a list of match object

Return type

generator of re.match

class sopel.plugins.rules.URLCallback(regexes, schemes=None, **kwargs)

Bases: sopel.plugins.rules.Rule

URL callback rule definition.

A URL callback rule (or simply “a URL rule”) detects URLs in a trigger then it uses regular expressions to match at most once per URL per regular expression, i.e. you can trigger between 0 and the number of regex the URL callback has per URL in the IRC line.

Here is an example with a URL rule with the pattern r'https://example\.com/(.*)':

<user> https://example.com/test
<Bot> You triggered a URL callback, with the "/test" path
<user> and this URL is https://example.com/other can you get it?
<Bot> You triggered a URL callback, with the "/other" path

Like generic rules, URL callback rules are not triggered by any specific name and they don’t have aliases.

Note

Unlike generic rules and commands, the url() decorator expects its decorated function to have the bot and the trigger with a third parameter: the match parameter.

To use this class with an existing URL callback handler, the from_callable() classmethod must be used: it will wrap the handler to work as intended. In that case, the trigger and the match arguments will be the same when the rule executes.

This behavior makes the match parameter obsolete, which will be removed in Sopel 9.

classmethod from_callable(settings, handler)

Instantiate a rule object from settings and handler.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler

Returns

an instance of this class created from the handler

Return type

AbstractRule

Sopel’s function-based rule handlers are simple callables, decorated with sopel.plugin’s decorators to add attributes, such as rate limit, threaded execution, output prefix, priority, and so on. In order to load these functions as rule objects, this class method can be used; it takes the bot’s settings and a cleaned handler.

A “cleaned handler” is a function, decorated appropriately, and passed through the filter of the loader's clean function.

classmethod from_callable_lazy(settings, handler)

Instantiate a rule object from a handler with lazy-loaded regexes.

Parameters
  • settings (sopel.config.Config) – Sopel’s settings

  • handler (callable) – a function-based rule handler with a lazy-loader for the regexes

Returns

an instance of this class created from the handler

Return type

AbstractRule

Similar to the from_callable() classmethod, it requires a rule handlers decorated with sopel.plugin’s decorators.

Unlike the from_callable() classmethod, the regexes are not already attached to the handler: its loader functions will be used to get the rule’s regexes. See the sopel.plugin.url_lazy() decorator for more information about the handler and the loaders’ signatures.

See also

The handler can have more than one loader attached. In that case, these loaders are chained with sopel.tools.chain_loaders().

match(bot, pretrigger)

Match URL(s) in a pretrigger according to the rule.

Parameters

This method looks for URLs in the IRC line, and for each it yields match objects using its regexes.

See also

To detect URLs, this method uses the core.auto_url_schemes option.

parse(text)

Parse text and yield matches.

Parameters

text (str) – text to parse by the rule

Returns

yield a list of match object

Return type

generator of re.match