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
module (module) – the module to clean
config (
sopel.config.Config
) – Sopel’s settings
- Returns
a tuple with triggerable, job, shutdown, and url functions
- Return type
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
ifobj
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
ifobj
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
ifobj
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
This function acts like
inspect.cleandoc()
but doesn’t replace tabs, and instead of astr
it returns alist
.
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
directoryhomedir’s
modules
directorysopel.plugins
setuptools entry pointssopel_modules
’s subpackagessopel.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:
find_internal_plugins()
for internal pluginsfind_sopel_modules_plugins()
forsopel_modules.*
pluginsfind_entry_point_plugins()
for plugins exposed by setuptools entry pointsfind_directory_plugins()
for plugins in$homedir/modules
,$homedir/plugins
, and in extra directories, as defined bysettings.core.extra
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 indirectory
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 givengroup
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 forsopel.modules.*
Internal plugins can be found under
sopel.modules
. This list does not include thecoretasks
plugin.
-
sopel.plugins.
find_sopel_modules_plugins
()¶ List plugins from
sopel_modules.*
.- Returns
yield instances of
PyModulePlugin
configured forsopel_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
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
directorysopel.plugins
setuptools entry pointssopel_modules
’s subpackagessopel.modules
’s core plugins
(The
coretasks
plugin is always the one fromsopel.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 theordered 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 thesopel.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:
loaded, using
load()
setup (if required), using
setup()
and eventually registered using
register()
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. wherefrom package import name
worksPyFilePlugin
: 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 necessaryEntryPointPlugin
: manage plugins that are declared by a setuptools entry point; other than that, it behaves like aPyModulePlugin
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, tosopel_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
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
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 aconfigure
action,False
otherwise- Return type
-
has_setup
()¶ Tell if the plugin has a setup action.
- Returns
True
if the plugin has a setup,False
otherwise- Return type
-
has_shutdown
()¶ Tell if the plugin has a shutdown action.
- Returns
True
if the plugin has ashutdown
action,False
otherwise- Return type
-
is_loaded
()¶ Tell if the plugin is loaded or not.
- Returns
True
if the plugin is loaded,False
otherwise- Return type
This must return
True
if theload()
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 aPyModulePlugin
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 theirsetup.py
file or theirsetup.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 thePyModulePlugin
, 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
This returns the same keys as
PyModulePlugin.get_meta_description()
; thesource
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 aPyModulePlugin
:>>> 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
This returns the same keys as
PyModulePlugin.get_meta_description()
; thesource
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 thereload
function (either from imp or importlib), because the module might not be available throughsys.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
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
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 aconfigure
action,False
otherwise- Return type
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
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 ashutdown
action,False
otherwise- Return type
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
This must return
True
if theload()
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 theplugin 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
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
-
execute
(bot, trigger)¶ Execute the triggered rule.
- Parameters
bot (
sopel.bot.SopelWrapper
) – Sopel wrappertrigger (
sopel.trigger.Trigger
) – IRC line
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
andhandler
.- Parameters
settings (
sopel.config.Config
) – Sopel’s settingshandler (callable) – a function-based rule handler
- Returns
an instance of this class created from the
handler
- Return type
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’ssettings
and a cleanedhandler
.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
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
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
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
A rule can have a priority, based on the three pre-defined priorities used by Sopel:
PRIORITY_HIGH
,PRIORITY_MEDIUM
, andPRIORITY_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
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
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
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
-
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
-
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
-
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
-
is_unblockable
()¶ Tell if the rule is unblockable.
- Returns
True
when the rule is unblockable,False
otherwise- Return type
-
match
(bot, pretrigger)¶ Match a pretrigger according to the rule.
- Parameters
bot (
sopel.bot.Sopel
) – Sopel instancepretrigger (
sopel.trigger.PreTrigger
) – line to match
This method must return a list of match objects.
-
match_event
(event)¶ Tell if the rule matches this
event
.
-
match_intent
(intent)¶ Tell if the rule matches this
intent
.
-
parse
(text)¶ Parse
text
and yield matches.
-
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.
-
has_alias
(name)¶ Tell when
name
is one of the rule’s aliases.
-
property
name
¶
-
property
-
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 theCommand
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
andhandler
.- Parameters
settings (
sopel.config.Config
) – Sopel’s settingshandler (callable) – a function-based rule handler
- Returns
an instance of this class created from the
handler
- Return type
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’ssettings
and a cleanedhandler
.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.
-
classmethod
-
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
andhandler
.- Parameters
settings (
sopel.config.Config
) – Sopel’s settingshandler (callable) – a function-based rule handler
- Returns
an instance of this class created from the
handler
- Return type
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’ssettings
and a cleanedhandler
.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.
-
classmethod
-
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 patternh\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.
-
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:
register()
for generic rulesregister_command()
for named rules with a prefixregister_nick_command()
for named rules based on nick callingregister_action_command()
for named rules based onACTION
register_url_callback()
for URL callback rules
Then to match the rules against a
trigger
, see theget_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
bot (
sopel.bot.Sopel
) – Sopel instanceurl (str) – URL to check
- Returns
True
whenurl
matches any URL callbacks,False
otherwise- Return type
-
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 adict
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 adict
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 alist
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 adict
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 alist
of its URL callbacks
-
get_triggered_rules
(bot, pretrigger)¶ Get triggered rules with their match objects, sorted by priorities.
- Parameters
bot (
sopel.bot.Sopel
) – Sopel instancepretrigger (
sopel.trigger.PreTrigger
) – IRC line
- Returns
a tuple of
(rule, match)
, sorted by priorities- Return type
-
has_action_command
(name, follow_alias=True, plugin=None)¶ Tell if the manager knows an action command with this
name
.- Parameters
- Returns
True
if the command exists,False
otherwise- Return type
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
- Returns
True
if the command exists,False
otherwise- Return type
By default, this method follows aliases to search commands. If the optional parameter
follow_alias
isFalse
, 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
- Returns
True
if the command exists,False
otherwise- Return type
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
- Returns
True
if the rule exists,False
otherwise- Return type
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
- Returns
True
if the URL callback exists,False
otherwise- Return type
The optional parameter
plugin
can be provided to limit the URL callbacks to only those from that plugin.
-
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
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
andhandler
.- Parameters
settings (
sopel.config.Config
) – Sopel’s settingshandler (callable) – a function-based rule handler
- Returns
an instance of this class created from the
handler
- Return type
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’ssettings
and a cleanedhandler
.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.
-
classmethod
-
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
-
execute
(bot, trigger)¶ Execute the triggered rule.
- Parameters
bot (
sopel.bot.SopelWrapper
) – Sopel wrappertrigger (
sopel.trigger.Trigger
) – IRC line
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
andhandler
.- Parameters
settings (
sopel.config.Config
) – Sopel’s settingshandler (callable) – a function-based rule handler
- Returns
an instance of this class created from the
handler
- Return type
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’ssettings
and a cleanedhandler
.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 settingshandler (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
Similar to the
from_callable()
classmethod, it requires a rule handler decorated withsopel.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 thesopel.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
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
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
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
A rule can have a priority, based on the three pre-defined priorities used by Sopel:
PRIORITY_HIGH
,PRIORITY_MEDIUM
, andPRIORITY_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
- 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, aRuntimeError
is raised because the rule has an undefined label.
-
get_test_parameters
()¶ Get parameters for automated tests.
- Return type
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
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
-
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
-
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
-
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
-
is_unblockable
()¶ Tell if the rule is unblockable.
- Returns
True
when the rule is unblockable,False
otherwise- Return type
-
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
This classmethod takes the
handler
’s attributes to generate a map of keyword arguments for the class. This can be used by thefrom_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
bot (
sopel.bot.Sopel
) – Sopel instancepretrigger (
sopel.trigger.PreTrigger
) – line to match
This method must return a list of match objects.
-
match_event
(event)¶ Tell if the rule matches this
event
.
-
match_intent
(intent)¶ Tell if the rule matches this
intent
.
-
-
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 patternh\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.
-
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: thematch
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, thetrigger
and thematch
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
andhandler
.- Parameters
settings (
sopel.config.Config
) – Sopel’s settingshandler (callable) – a function-based rule handler
- Returns
an instance of this class created from the
handler
- Return type
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’ssettings
and a cleanedhandler
.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 settingshandler (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
Similar to the
from_callable()
classmethod, it requires a rule handlers decorated withsopel.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 thesopel.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
bot (
sopel.bot.Sopel
) – Sopel instancepretrigger (
sopel.trigger.PreTrigger
) – line to match
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.
-
classmethod