2020-10-09 10:40:37 +02:00
|
|
|
from dataclasses import dataclass
|
2020-10-09 16:03:09 +02:00
|
|
|
from pathlib import Path
|
2022-08-15 13:19:48 +02:00
|
|
|
from typing import Any, Optional
|
2020-10-09 10:40:37 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
from irc.client import NickMask # type: ignore
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Question:
|
|
|
|
preamble: str
|
|
|
|
content: str
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Command:
|
|
|
|
# Identifier as set in config. Set even when an alias has been used.
|
|
|
|
ident: str
|
|
|
|
# Content of the command when it has been parsed, empty str otherwise.
|
|
|
|
content: str
|
|
|
|
# Raw command content (minus name and suffix), always set.
|
|
|
|
raw: str
|
|
|
|
# Identifier matched, possibly an alias. Set only when matched.
|
|
|
|
matched: str = ""
|
2022-07-07 19:06:59 +02:00
|
|
|
|
2020-10-09 10:40:37 +02:00
|
|
|
|
|
|
|
class Plugin:
|
2020-11-04 19:09:32 +01:00
|
|
|
"""Base class for the bot plugins.
|
|
|
|
|
|
|
|
This class provides a lot of tools to facilitate the implementation of
|
|
|
|
plugins. Callbacks for all events handled by the IRC library can be
|
|
|
|
implemented here (if the Bot class supports it). Most bot features are put
|
|
|
|
in plugins to avoid cluttering the Bot class, and no plugins should be
|
|
|
|
required for the bot to run; plugins can depend on each other though.
|
|
|
|
|
|
|
|
A plugin loads his basic information from the config file. It can use the
|
|
|
|
bot's runtime values facilities to make runtime values available to other
|
|
|
|
plugins. It can also save data using the Bot's storage feature to be
|
|
|
|
available after a restart.
|
|
|
|
|
2022-09-04 15:27:13 +02:00
|
|
|
Initialisation should be very fast, no network connections or anything.
|
|
|
|
They are initialised before connecting to the server, so their `is_ready`
|
|
|
|
flag is set at that point. The loading order is more or less random, so a
|
|
|
|
plugin cannot assume another has been loaded during initialisation. If it
|
|
|
|
wants to interact with another plugin, the earliest point to do that is in
|
|
|
|
the on_welcome callback which is called after connecting to a server, and
|
|
|
|
can disable itself by setting its own `is_ready` flag to false.
|
2020-11-04 19:09:32 +01:00
|
|
|
|
2022-07-07 19:06:59 +02:00
|
|
|
A plugin can access its config once the base `__init__` has been called.
|
|
|
|
The configuration is valid only is `is_ready` is True, else accessing its
|
2020-11-04 22:46:09 +01:00
|
|
|
content is undefined behaviour.
|
|
|
|
|
2020-11-04 19:09:32 +01:00
|
|
|
Plugins can have priorities and calling their callbacks will respect it.
|
|
|
|
For now these levels are used:
|
|
|
|
- 0: default
|
|
|
|
- -3: low, misc parsing of messages, answer to various messages
|
2021-06-06 18:28:43 +02:00
|
|
|
- -6: handling of unknown commands
|
|
|
|
- -7: handling of unknown questions
|
|
|
|
- -8: handling any message that might match something
|
2020-11-04 22:46:09 +01:00
|
|
|
- -10: lowest, e.g. for random reactions usually with a very low rate
|
2020-11-04 19:09:32 +01:00
|
|
|
"""
|
2020-10-09 10:40:37 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
REQUIRED_CONFIGS: list[str] = []
|
2020-10-09 12:49:35 +02:00
|
|
|
|
2020-10-09 10:40:37 +02:00
|
|
|
def __init__(self, bot):
|
2022-08-15 13:19:48 +02:00
|
|
|
from edmond.bot import Bot
|
2022-08-15 13:35:42 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
self.bot: Bot = bot
|
|
|
|
# self.name is the plugin name, lowercased, without the Plugin suffix.
|
|
|
|
self.name: str = self.__class__.__name__.lower()[:-6]
|
|
|
|
self.priority: int = 0
|
|
|
|
self.config: dict = self.__get_config()
|
|
|
|
self.is_ready: bool = self.__check_config()
|
2020-10-09 10:40:37 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def callbacks(self):
|
|
|
|
"""List of callback types available for this plugin."""
|
|
|
|
return {
|
|
|
|
cb[3:]: getattr(self, cb)
|
|
|
|
for cb in dir(self)
|
|
|
|
if cb.startswith("on_") and callable(getattr(self, cb))
|
|
|
|
}
|
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def __get_config(self) -> dict:
|
2022-07-07 19:06:59 +02:00
|
|
|
"""Return the plugin section from the bot config plus common values."""
|
2020-10-09 10:40:37 +02:00
|
|
|
plugins_configs = self.bot.config["plugins"]
|
2020-10-09 13:30:52 +02:00
|
|
|
config = plugins_configs["common"].copy()
|
2020-10-09 12:49:35 +02:00
|
|
|
config.update(plugins_configs.get(self.name, {}))
|
2020-10-09 16:03:09 +02:00
|
|
|
# Load resources as config values.
|
2022-07-07 19:06:59 +02:00
|
|
|
res_dir = self.bot.config["resources_dir"]
|
|
|
|
for key, res_path in config.get("resources", {}).items():
|
|
|
|
res_path = Path(res_dir) / res_path
|
2020-10-09 21:59:21 +02:00
|
|
|
try:
|
2022-07-07 19:06:59 +02:00
|
|
|
with open(res_path, "rt") as res_file:
|
2022-08-15 13:19:48 +02:00
|
|
|
config[key] = [
|
|
|
|
line.strip() for line in res_file.readlines()
|
|
|
|
]
|
2020-10-09 21:59:21 +02:00
|
|
|
except OSError:
|
2022-07-07 19:06:59 +02:00
|
|
|
self.bot.log_e(f"Could not load resource at {res_path}.")
|
2020-10-09 12:49:35 +02:00
|
|
|
return config
|
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def __check_config(self) -> bool:
|
2020-10-09 12:49:35 +02:00
|
|
|
"""Return True if the plugin config is properly setup."""
|
|
|
|
missing = False
|
|
|
|
for key in self.REQUIRED_CONFIGS:
|
|
|
|
if key not in self.config:
|
2022-07-07 19:06:59 +02:00
|
|
|
self.bot.log_e(f"Missing '{key}' in {self.name} config.")
|
2020-10-09 12:49:35 +02:00
|
|
|
missing = True
|
2020-10-09 13:30:52 +02:00
|
|
|
return not missing
|
2020-10-09 12:19:58 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def get_runtime_value(
|
|
|
|
self, key: str, default: Any = None, ns: str = None
|
|
|
|
) -> Any:
|
2020-10-09 23:37:35 +02:00
|
|
|
"""Get a value from the plugin runtime dict.
|
|
|
|
|
2022-07-07 19:06:59 +02:00
|
|
|
This will get the value from the plugin namespace, but it is possible
|
|
|
|
to get runtime values from other plugins using their name as `ns`.
|
2020-10-09 23:37:35 +02:00
|
|
|
"""
|
2020-10-09 12:49:35 +02:00
|
|
|
if ns is None:
|
|
|
|
ns = self.name
|
2020-10-12 15:45:31 +02:00
|
|
|
return self.bot.values[ns].get(key, default)
|
2020-10-09 12:19:58 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def set_runtime_value(self, key: str, value: Any) -> Any:
|
2020-10-09 12:19:58 +02:00
|
|
|
"""Set a value in the plugin runtime dict."""
|
|
|
|
self.bot.values[self.name][key] = value
|
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def get_storage_value(self, key: str, default=None, ns: str = None) -> Any:
|
2021-06-06 19:02:19 +02:00
|
|
|
"""Get a value from the plugin persistent storage.
|
|
|
|
|
2022-07-07 19:06:59 +02:00
|
|
|
This will get the value from the plugin namespace, but it is possible
|
|
|
|
to get storage values from other plugins using their name as `ns`.
|
2021-06-06 19:02:19 +02:00
|
|
|
"""
|
|
|
|
if ns is None:
|
|
|
|
ns = self.name
|
|
|
|
return self.bot.storage.get(ns, {}).get(key, default)
|
2020-10-09 23:37:35 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def set_storage_value(self, key: str, value: Any, ns: str = None) -> None:
|
2020-10-09 23:37:35 +02:00
|
|
|
"""Set a value in the plugin persistent storage."""
|
2022-05-16 12:02:45 +02:00
|
|
|
name = ns or self.name
|
|
|
|
if name not in self.bot.storage:
|
|
|
|
self.bot.storage[name] = {key: value}
|
2020-10-09 23:37:35 +02:00
|
|
|
else:
|
2022-05-16 12:02:45 +02:00
|
|
|
self.bot.storage[name][key] = value
|
2022-08-15 13:35:42 +02:00
|
|
|
self.bot.save_storage()
|
2020-10-09 23:37:35 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def append_storage_list_value(self, key: str, value: Any) -> None:
|
2020-10-09 23:37:35 +02:00
|
|
|
"""Append a value to a list in the plugin persistent storage."""
|
|
|
|
if self.name not in self.bot.storage:
|
|
|
|
self.bot.storage[self.name] = {key: [value]}
|
|
|
|
elif key not in self.bot.storage[self.name]:
|
|
|
|
self.bot.storage[self.name][key] = [value]
|
|
|
|
else:
|
|
|
|
self.bot.storage[self.name][key].append(value)
|
2022-08-15 13:35:42 +02:00
|
|
|
self.bot.save_storage()
|
2020-10-09 23:37:35 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def remove_storage_list_value(self, key: str, value: Any) -> None:
|
2020-11-01 19:29:51 +01:00
|
|
|
"""Remove a value from a persistent storage list."""
|
2022-07-07 19:06:59 +02:00
|
|
|
if (
|
|
|
|
self.name in self.bot.storage
|
|
|
|
and key in self.bot.storage[self.name]
|
|
|
|
):
|
2020-10-12 15:45:31 +02:00
|
|
|
self.bot.storage[self.name][key].remove(value)
|
2022-08-15 13:35:42 +02:00
|
|
|
self.bot.save_storage()
|
2020-10-12 15:45:31 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def should_read_message(self, message: str) -> Optional[str]:
|
2020-11-04 19:09:18 +01:00
|
|
|
"""Return a message content if it has been addressed to me, else None.
|
|
|
|
|
|
|
|
If the message starts with one of the bot's names, the rest of the
|
|
|
|
message is returned. It might be an empty str if the message was only
|
|
|
|
someone saying a bot's name. In other cases, return None.
|
|
|
|
|
|
|
|
Note that you do not need to use this method for command/question
|
2020-11-05 22:45:33 +01:00
|
|
|
plugins, the next methods already check for this and do more precise
|
2022-07-07 19:06:59 +02:00
|
|
|
parsing of the message. This is rather for plugins reacting to a
|
|
|
|
message addressed to the bot that are neither commands or questions.
|
2020-11-04 19:09:18 +01:00
|
|
|
"""
|
|
|
|
first_word_and_rest = message.split(maxsplit=1)
|
|
|
|
num_parts = len(first_word_and_rest)
|
|
|
|
if num_parts == 0:
|
|
|
|
return None
|
2020-11-08 16:07:54 +01:00
|
|
|
# Are the config conditions to answer a question valid?
|
2021-07-03 01:36:18 +02:00
|
|
|
elif not self.respects_handling_conditions():
|
2020-11-09 15:09:29 +01:00
|
|
|
return None
|
2020-11-08 16:07:54 +01:00
|
|
|
# Is the message addressed to me?
|
2020-11-04 19:09:18 +01:00
|
|
|
elif first_word_and_rest[0] in self.bot.names:
|
|
|
|
if num_parts == 1:
|
2020-11-09 15:09:29 +01:00
|
|
|
content = ""
|
2020-11-04 19:09:18 +01:00
|
|
|
else:
|
2020-11-09 15:09:29 +01:00
|
|
|
content = first_word_and_rest[1].strip()
|
|
|
|
self.bot.log_i(f"Reading message from {self.name}: {content}")
|
|
|
|
return content
|
2022-08-15 13:19:48 +02:00
|
|
|
return None
|
2020-11-04 19:09:18 +01:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def should_answer_question(self, message: str) -> bool:
|
2020-11-04 19:09:32 +01:00
|
|
|
"""Store Question in object and return True if I should answer it.
|
|
|
|
|
2022-07-07 19:06:59 +02:00
|
|
|
To answer a question, the message must start with one of the bot's
|
|
|
|
names and optionally end with one or more question marks (they are
|
|
|
|
discarded). The bot checks that answering conditions are respected, and
|
|
|
|
they cannot be bypassed as with commands. A Question created is checked
|
|
|
|
from the plugin's registered questions and stored in the instance.
|
2020-11-04 19:09:32 +01:00
|
|
|
"""
|
2020-10-09 12:19:58 +02:00
|
|
|
words = message.split()
|
2020-11-02 12:51:26 +01:00
|
|
|
# Is the message addressed to me?
|
2020-11-04 19:09:18 +01:00
|
|
|
if len(words) == 0 or words[0].lower() not in self.bot.names:
|
2020-10-09 12:19:58 +02:00
|
|
|
return False
|
|
|
|
|
2020-11-02 12:51:26 +01:00
|
|
|
# Are the config conditions to answer a question valid?
|
2021-07-03 01:36:18 +02:00
|
|
|
if not self.respects_handling_conditions():
|
2020-11-02 12:51:26 +01:00
|
|
|
return False
|
|
|
|
|
|
|
|
# Is it a question I can answer?
|
2022-08-09 23:47:28 +02:00
|
|
|
question = message[len(words[0]) :].strip()
|
2020-11-05 22:45:21 +01:00
|
|
|
for preamble in self.config.get("questions", []):
|
|
|
|
aliases = self.config.get("aliases", {}).get(preamble, [])
|
|
|
|
for q in (preamble, *aliases):
|
|
|
|
if question.startswith(q):
|
2020-11-09 15:09:29 +01:00
|
|
|
self.__save_question(question, q, preamble)
|
2020-11-05 22:45:21 +01:00
|
|
|
return True
|
2020-10-09 12:19:58 +02:00
|
|
|
return False
|
2020-10-09 10:40:37 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def __save_question(self, question: str, matched: str, preamble: str):
|
2022-08-09 23:47:28 +02:00
|
|
|
content = question[len(matched) :].strip()
|
2020-11-09 15:09:29 +01:00
|
|
|
content = content.rstrip("?").rstrip()
|
2022-08-15 13:19:48 +02:00
|
|
|
self.question = Question(preamble, content)
|
|
|
|
self.bot.log_i(f"Answering from plugin {self.name}: {self.question}")
|
2020-11-09 15:09:29 +01:00
|
|
|
|
2020-11-02 13:23:19 +01:00
|
|
|
def should_handle_command(
|
|
|
|
self,
|
2022-08-15 13:19:48 +02:00
|
|
|
message: str,
|
|
|
|
no_content: bool = False,
|
|
|
|
exclude_conditions: Optional[dict] = None,
|
|
|
|
) -> bool:
|
2020-11-04 19:09:32 +01:00
|
|
|
"""Store Command in object and return True if I should handle it.
|
2020-11-02 13:23:19 +01:00
|
|
|
|
|
|
|
If no_content is True, the command does not parse command contents and
|
|
|
|
put all the command message (without suffix) to the command identifier.
|
2022-07-07 19:06:59 +02:00
|
|
|
This is useful for commands that have multiple words in their
|
|
|
|
identifier and do not have any content, or when the content parsing
|
|
|
|
should be done by the plugin itself.
|
2020-11-02 13:23:19 +01:00
|
|
|
|
|
|
|
If exclude_conditions is a collection of plugin namespaces, the
|
|
|
|
conditions of these plugins are not tested. A basic scenario is the
|
|
|
|
wakeup command from sleep plugin that requires excluding its own
|
|
|
|
condition (i.e. do not handle commands when sleeping).
|
|
|
|
"""
|
2020-11-02 12:51:26 +01:00
|
|
|
# Are the config conditions to handle a command valid?
|
2021-07-03 01:36:18 +02:00
|
|
|
if not self.respects_handling_conditions(exclude_conditions):
|
2020-11-02 12:51:26 +01:00
|
|
|
return False
|
|
|
|
|
|
|
|
# Is it a valid command?
|
2020-11-02 17:41:47 +01:00
|
|
|
parsed_command = self.__parse_command(message, no_content=no_content)
|
|
|
|
if not parsed_command:
|
2020-10-31 18:12:08 +01:00
|
|
|
return False
|
2020-11-02 12:51:26 +01:00
|
|
|
|
|
|
|
# Is it a command I can handle?
|
2020-11-02 17:41:47 +01:00
|
|
|
available_commands = self.config.get("commands", [])
|
|
|
|
aliases = self.config.get("aliases", {})
|
|
|
|
for ident in available_commands:
|
|
|
|
# Match commands differently according to no_content. If no_content
|
|
|
|
# is True, check the parsed command (pc) raw data as a string that
|
|
|
|
# may contain the available identifier (ai) at its beginning.
|
|
|
|
# If no_content is False (default), simply compare the parsed
|
|
|
|
# identifier with available identifiers.
|
|
|
|
if no_content:
|
2022-06-08 17:12:33 +02:00
|
|
|
matches = lambda pc, ai: (
|
2020-11-02 17:41:47 +01:00
|
|
|
pc.raw == ai or pc.raw.startswith(ai + " ")
|
|
|
|
)
|
|
|
|
else:
|
2022-06-08 17:12:33 +02:00
|
|
|
matches = lambda pc, ai: pc.ident == ai
|
2020-11-02 17:41:47 +01:00
|
|
|
# First case: the command identifier has been used.
|
2022-06-08 17:12:33 +02:00
|
|
|
if matches(parsed_command, ident):
|
2020-11-02 17:41:47 +01:00
|
|
|
parsed_command.ident = ident
|
2022-06-08 17:12:33 +02:00
|
|
|
parsed_command.matched = ident
|
2020-11-02 17:41:47 +01:00
|
|
|
self.__save_command(parsed_command)
|
|
|
|
return True
|
|
|
|
# Second case: an alias of the identifier has been used.
|
|
|
|
ident_aliases = aliases.get(ident, [])
|
|
|
|
for alias in ident_aliases:
|
2022-06-08 17:12:33 +02:00
|
|
|
if matches(parsed_command, alias):
|
2020-11-02 17:41:47 +01:00
|
|
|
parsed_command.ident = ident
|
2022-06-08 17:12:33 +02:00
|
|
|
parsed_command.matched = alias
|
2020-11-02 17:41:47 +01:00
|
|
|
self.__save_command(parsed_command)
|
|
|
|
return True
|
2020-10-09 10:40:37 +02:00
|
|
|
return False
|
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def __parse_command(
|
|
|
|
self, message: str, no_content: bool = False
|
|
|
|
) -> Optional[Command]:
|
2022-07-07 19:06:59 +02:00
|
|
|
"""Return a parsed Command if this message is a command, else None.
|
2020-11-02 17:41:47 +01:00
|
|
|
|
|
|
|
The command raw field is always set. The ident and content fields are
|
2020-11-04 19:09:32 +01:00
|
|
|
empty when no_content is True. The match field is never set by this
|
2020-11-02 17:41:47 +01:00
|
|
|
method.
|
|
|
|
"""
|
2020-10-09 10:40:37 +02:00
|
|
|
words = message.split()
|
2020-11-04 19:09:18 +01:00
|
|
|
if len(words) == 0:
|
|
|
|
return None
|
2020-10-09 12:49:35 +02:00
|
|
|
command_suffix = self.config["command_suffix"]
|
|
|
|
if words[0].lower() in self.bot.names and words[-1] == command_suffix:
|
2020-11-02 17:41:47 +01:00
|
|
|
raw = " ".join(words[1:-1])
|
2020-10-09 22:32:36 +02:00
|
|
|
if no_content:
|
2020-11-02 17:41:47 +01:00
|
|
|
ident = ""
|
2020-10-09 22:32:36 +02:00
|
|
|
content = ""
|
|
|
|
else:
|
|
|
|
ident = words[1]
|
|
|
|
content = " ".join(words[2:-1])
|
2020-11-02 17:41:47 +01:00
|
|
|
return Command(ident, content, raw)
|
2022-08-15 13:19:48 +02:00
|
|
|
return None
|
2020-10-09 10:40:37 +02:00
|
|
|
|
2022-08-15 13:19:48 +02:00
|
|
|
def __save_command(self, command: Command):
|
2020-11-05 22:45:33 +01:00
|
|
|
"""Save command in instance for further processing by the plugin."""
|
|
|
|
self.command = command
|
2022-07-07 19:06:59 +02:00
|
|
|
self.bot.log_i(f"Processing command from p. {self.name}: {command}")
|
2020-11-05 22:45:33 +01:00
|
|
|
|
2022-08-15 13:35:42 +02:00
|
|
|
def respects_handling_conditions(
|
|
|
|
self, exclude_conditions: Optional[dict] = None
|
|
|
|
):
|
2021-07-03 01:36:18 +02:00
|
|
|
"""Check if handling conditions are valid.
|
|
|
|
|
|
|
|
Handling conditions can be specified by each plugin to create states in
|
|
|
|
which handling messages can be disabled. It is currently only used by
|
|
|
|
the sleep plugin (sleeping must disable most interactions) but every
|
|
|
|
plugin is free to introduce their own condition.
|
|
|
|
"""
|
2020-11-02 12:51:26 +01:00
|
|
|
conditions = self.config.get("handling_conditions", {})
|
|
|
|
for plugin_ns, plugin_conditions in conditions.items():
|
2020-11-02 13:23:19 +01:00
|
|
|
if exclude_conditions and plugin_ns in exclude_conditions:
|
|
|
|
continue
|
2020-11-02 12:51:26 +01:00
|
|
|
for condition_key, condition_value in plugin_conditions.items():
|
|
|
|
value = self.get_runtime_value(condition_key, ns=plugin_ns)
|
|
|
|
if condition_value != value:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2020-10-09 22:34:47 +02:00
|
|
|
def signal_failure(self, target):
|
|
|
|
"""Signal a plugin failure to target."""
|
|
|
|
self.bot.say(target, self.bot.config["error_message"])
|
|
|
|
|
2022-07-07 19:06:59 +02:00
|
|
|
def on_privmsg(self, event):
|
|
|
|
"""Default behaviour on privmsg is to answer like a pubmsg.
|
|
|
|
|
|
|
|
Because most plugins assume messages are sent publicly, they send their
|
|
|
|
replies to `event.target` so we replace it with the event source nick.
|
|
|
|
If it causes an issue with a plugin requiring the original target even
|
|
|
|
on private message, override this method.
|
|
|
|
"""
|
2022-08-09 23:47:28 +02:00
|
|
|
if on_pubmsg := getattr(self, "on_pubmsg", None):
|
2022-07-07 19:06:59 +02:00
|
|
|
event.target = NickMask(event.source).nick
|
|
|
|
return on_pubmsg(event)
|
|
|
|
return False
|