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 CTCP commands

  • allow echo-message

  • threaded execution or not

  • rate limiting feature

  • text parsing

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

abstract allow_bots() bool#

Tell if the rule should match bot commands.

Returns:

True when the rule allows bot commands, False otherwise

A “bot command” is any IRC protocol command or numeric that has been tagged as bot (or draft/bot) by the IRC server.

abstract allow_echo() bool#

Tell if the rule should match echo messages.

Returns:

True when the rule allows echo messages, False otherwise

Return type:

bool

abstract property channel_rate_limit: timedelta#

The rule’s channel rate limit.

abstract property channel_rate_template: str | None#

Give the message template to send with a NOTICE to nick.

Returns:

A formatted string, or None if no message is set.

This method is called by the bot when a trigger hits the channel rate limit (i.e. for the specified channel).

abstract execute(bot, trigger)#

Execute the triggered rule.

Parameters:

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

abstract classmethod from_callable(settings, handler) TypedRule#

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.

abstract get_channel_metrics(channel: Identifier) RuleMetrics#

Get the rule’s usage metrics for the given channel.

abstract get_doc() str#

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.

abstract get_global_metrics() RuleMetrics#

Get the rule’s global usage metrics.

abstract get_output_prefix() str#

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.

abstract get_plugin_name() str#

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.

abstract get_priority() str#

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.

abstract get_rule_label() str#

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.

abstract get_test_parameters() tuple#

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.

abstract get_usages() tuple#

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.

abstract get_user_metrics(nick: Identifier) RuleMetrics#

Get the rule’s usage metrics for the given user.

abstract property global_rate_limit: timedelta#

The rule’s global rate limit.

abstract property global_rate_template: str | None#

Give the message to send with a NOTICE to nick.

Returns:

A formatted string, or None if no message is set.

This method is called by the bot when a trigger hits the global rate limit (i.e. for any nick/channel).

abstract is_channel_rate_limited(
channel: Identifier,
at_time: datetime.datetime | None = None,
) bool#

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

Parameters:
  • channel – the channel associated with this check

  • at_time – optional aware datetime for the rate limit check; if not given, utcnow will be used

Returns:

True when the rule reached the limit, False otherwise.

abstract is_global_rate_limited(
at_time: datetime | None = None,
) bool#

Tell when the rule reached the global rate limit.

Parameters:

at_time – optional aware datetime for the rate limit check; if not given, utcnow will be used

Returns:

True when the rule reached the limit, False otherwise.

abstract is_threaded() bool#

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

abstract is_unblockable() bool#

Tell if the rule is unblockable.

Returns:

True when the rule is unblockable, False otherwise

abstract is_user_rate_limited(
nick: Identifier,
at_time: datetime.datetime | None = None,
) bool#

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

Parameters:
  • nick – the nick associated with this check

  • at_time – optional aware datetime for the rate limit check; if not given, utcnow will be used

Returns:

True when the rule reached the limit, False otherwise.

abstract match(bot, pretrigger) Iterable#

Match a pretrigger according to the rule.

Parameters:

This method must return a list of match objects.

abstract match_ctcp(command: str | None) bool#

Tell if the rule matches this CTCP command.

Parameters:

command – potential matching CTCP command

Returns:

True when command matches the rule, False otherwise

abstract match_event(event) bool#

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

abstract parse(text) Generator#

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”.

abstract property user_rate_limit: timedelta#

The rule’s user rate limit.

abstract property user_rate_template: str | None#

Give the message template to send with a NOTICE to nick.

Returns:

A formatted string, or None if no message is set.

This property is accessed by the bot when a trigger hits the user rate limit (i.e. for the specificed nick).

class sopel.plugins.rules.AbstractNamedRule(name, aliases=None, **kwargs)#

Abstract base class 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#
get_rule_label()#

Get the rule’s label.

Return type:

str

A named rule’s label is its name.

abstract get_rule_regex()#

Make the rule regex for this named rule.

Returns:

a compiled regex for this named rule and its aliases

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.TypedRule#

A TypeVar bound to AbstractRule.

When used in the AbstractRule.from_callable() class method, it means the return value must be an instance of the class used to call that method and not a different subclass of AbstractRule.

New in version 8.0: This TypeVar was added as part of a goal to start type-checking Sopel and is not used at runtime.

alias of TypeVar(‘TypedRule’, bound=AbstractRule)

class sopel.plugins.rules.RuleMetrics#

Tracker of a rule’s usage.

end() None#

Record a ending time (after execution).

is_limited(time_limit: datetime) bool#

Determine if the rule hits the time limit.

property last_time: datetime | None#

Last recorded start/end time for the associated rule.

set_return_value(value: Any) None#

Set the last return value of a rule.

start() None#

Record a starting time (before execution).

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

Bases: AbstractNamedRule

Action Command rule definition.

An action command rule is a named rule that can be triggered only when the trigger’s CTCP command 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_ctcp(command: str | None) bool#

Tell if command is an ACTION.

Parameters:

command – potential matching CTCP command

Returns:

True when command matches ACTION, False otherwise

class sopel.plugins.rules.Command(
name,
prefix=COMMAND_DEFAULT_PREFIX,
help_prefix=COMMAND_DEFAULT_HELP_PREFIX,
aliases=None,
**kwargs,
)#

Bases: AbstractNamedRule

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=PRIORITY_MEDIUM,
handler=None,
events=None,
ctcp=None,
allow_bots=False,
allow_echo=False,
threaded=True,
output_prefix=None,
unblockable=False,
user_rate_limit=0,
channel_rate_limit=0,
global_rate_limit=0,
user_rate_message=None,
channel_rate_message=None,
global_rate_message=None,
default_rate_message=None,
usages=None,
tests=None,
doc=None,
)#

Bases: 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: AbstractNamedRule

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=PRIORITY_MEDIUM,
handler=None,
events=None,
ctcp=None,
allow_bots=False,
allow_echo=False,
threaded=True,
output_prefix=None,
unblockable=False,
user_rate_limit=0,
channel_rate_limit=0,
global_rate_limit=0,
user_rate_message=None,
channel_rate_message=None,
global_rate_message=None,
default_rate_message=None,
usages=None,
tests=None,
doc=None,
)#

Bases: 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_bots()#

Tell if the rule should match bot commands.

Returns:

True when the rule allows bot commands, False otherwise

A “bot command” is any IRC protocol command or numeric that has been tagged as bot (or draft/bot) by the IRC server.

allow_echo()#

Tell if the rule should match echo messages.

Returns:

True when the rule allows echo messages, False otherwise

Return type:

bool

property channel_rate_limit: timedelta#

The rule’s channel rate limit.

property channel_rate_template: str | None#

Give the message template to send with a NOTICE to nick.

Returns:

A formatted string, or None if no message is set.

This method is called by the bot when a trigger hits the channel rate limit (i.e. for the specified channel).

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_channel_metrics(channel: Identifier) RuleMetrics#

Get the rule’s usage metrics for the given channel.

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_global_metrics() RuleMetrics#

Get the rule’s global usage metrics.

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.

get_user_metrics(nick: Identifier) RuleMetrics#

Get the rule’s usage metrics for the given user.

property global_rate_limit: timedelta#

The rule’s global rate limit.

property global_rate_template: str | None#

Give the message to send with a NOTICE to nick.

Returns:

A formatted string, or None if no message is set.

This method is called by the bot when a trigger hits the global rate limit (i.e. for any nick/channel).

is_channel_rate_limited(
channel: Identifier,
at_time: datetime.datetime | None = None,
) bool#

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

Parameters:
  • channel – the channel associated with this check

  • at_time – optional aware datetime for the rate limit check; if not given, utcnow will be used

Returns:

True when the rule reached the limit, False otherwise.

is_global_rate_limited(at_time: datetime | None = None) bool#

Tell when the rule reached the global rate limit.

Parameters:

at_time – optional aware datetime for the rate limit check; if not given, utcnow will be used

Returns:

True when the rule reached the limit, False otherwise.

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

is_user_rate_limited(
nick: Identifier,
at_time: datetime.datetime | None = None,
) bool#

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

Parameters:
  • nick – the nick associated with this check

  • at_time – optional aware datetime for the rate limit check; if not given, utcnow will be used

Returns:

True when the rule reached the limit, False otherwise.

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_ctcp(command: str | None) bool#

Tell if the rule matches this CTCP command.

Parameters:

command – potential matching CTCP command

Returns:

True when command matches the rule, False otherwise

match_event(event) bool#

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

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 user_rate_limit: timedelta#

The rule’s user rate limit.

property user_rate_template: str | None#

Give the message template to send with a NOTICE to nick.

Returns:

A formatted string, or None if no message is set.

This property is accessed by the bot when a trigger hits the user rate limit (i.e. for the specificed nick).

class sopel.plugins.rules.SearchRule(
regexes,
plugin=None,
label=None,
priority=PRIORITY_MEDIUM,
handler=None,
events=None,
ctcp=None,
allow_bots=False,
allow_echo=False,
threaded=True,
output_prefix=None,
unblockable=False,
user_rate_limit=0,
channel_rate_limit=0,
global_rate_limit=0,
user_rate_message=None,
channel_rate_message=None,
global_rate_message=None,
default_rate_message=None,
usages=None,
tests=None,
doc=None,
)#

Bases: 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: 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