plugin: add question-type plugins

This commit is contained in:
dece 2020-10-09 12:19:58 +02:00
parent 3f6ec00ffe
commit dc941c1985
6 changed files with 70 additions and 11 deletions

View file

@ -1,4 +1,5 @@
import argparse import argparse
import random
import edmond.bot import edmond.bot
import edmond.config import edmond.config
@ -10,6 +11,8 @@ def main():
argparser.add_argument("-c", "--config", default="config.json") argparser.add_argument("-c", "--config", default="config.json")
args = argparser.parse_args() args = argparser.parse_args()
random.seed()
logger = edmond.log.get_logger(name="edmond") logger = edmond.log.get_logger(name="edmond")
config = edmond.config.load_config(args.config, logger=logger) config = edmond.config.load_config(args.config, logger=logger)
bot = edmond.bot.Bot(config, logger) bot = edmond.bot.Bot(config, logger)

View file

@ -16,6 +16,7 @@ class Bot(irc.client.SimpleIRCClient, Logger):
self.config = config self.config = config
self.logger = logger self.logger = logger
self.plugins = [] self.plugins = []
self.values = {}
@property @property
def nick(self): def nick(self):
@ -27,6 +28,7 @@ class Bot(irc.client.SimpleIRCClient, Logger):
def on_welcome(self, connection, event): def on_welcome(self, connection, event):
self.log_i(f"Connected to server {event.source}.") self.log_i(f"Connected to server {event.source}.")
self.run_plugin_callbacks(event)
for channel in self.config["channels"]: for channel in self.config["channels"]:
connection.join(channel) connection.join(channel)
@ -74,6 +76,7 @@ class Bot(irc.client.SimpleIRCClient, Logger):
class_name = plugin_name.capitalize() + "Plugin" class_name = plugin_name.capitalize() + "Plugin"
plugin_class = getattr(module, class_name) plugin_class = getattr(module, class_name)
self.plugins.append(plugin_class(self)) self.plugins.append(plugin_class(self))
self.values[plugin_name] = {}
self.log_d(f"Loaded {class_name}.") self.log_d(f"Loaded {class_name}.")
def say(self, target, message): def say(self, target, message):

View file

@ -5,6 +5,7 @@ class Plugin:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.name = self.__class__.__name__.lower()[:-6] # Remove "Plugin".
self.config = self.get_config() self.config = self.get_config()
@property @property
@ -18,9 +19,31 @@ class Plugin:
def get_config(self): def get_config(self):
"""Return the plugin section from the bot config.""" """Return the plugin section from the bot config."""
name = self.__class__.__name__.lower()[:-6] # Remove Plugin suffix.
plugins_configs = self.bot.config["plugins"] plugins_configs = self.bot.config["plugins"]
return plugins_configs.get(name, {}) return plugins_configs.get(self.name, {})
def get_runtime_value(self, key, plugin_name=None):
"""Get a value from the plugin runtime dict."""
if plugin_name is None:
plugin_name = self.name
return self.bot.values[self.name].get(key)
def set_runtime_value(self, key, value):
"""Set a value in the plugin runtime dict."""
self.bot.values[self.name][key] = value
def should_answer_question(self, message):
"""Store Question in object and return True if it should answer it."""
words = message.split()
if words[0].lower() not in self.bot.names:
return False
question = message[len(words[0]):].strip()
for q in self.QUESTIONS:
if question.startswith(q):
self.question = Question(q, question[len(q):].strip())
return True
return False
def should_handle_command(self, message): def should_handle_command(self, message):
"""Store Command in object and return True if it should handle it.""" """Store Command in object and return True if it should handle it."""
@ -39,6 +62,12 @@ class Plugin:
return Command(ident, content) return Command(ident, content)
@dataclass
class Question:
preambule: str
content: str
@dataclass @dataclass
class Command: class Command:
ident: str ident: str

View file

@ -19,3 +19,4 @@ class HoroscopePlugin(Plugin):
text = http_get(self.config["url"]) text = http_get(self.config["url"])
if text: if text:
self.bot.say(event.target, text) self.bot.say(event.target, text)
return True

31
edmond/plugins/mood.py Normal file
View file

@ -0,0 +1,31 @@
import random
from enum import Enum
from edmond.plugin import Plugin
class Mood(Enum):
CALM = 0
PISSED = 1
class MoodPlugin(Plugin):
QUESTIONS = ["how are you?"]
def __init__(self, bot):
super().__init__(bot)
def on_welcome(self, event):
mood = random.choice(list(Mood))
self.set_runtime_value("mood", mood)
def on_pubmsg(self, event):
if not self.should_answer_question(event.arguments[0]):
return False
mood = self.get_runtime_value("mood")
if mood == Mood.CALM:
self.bot.say(event.target, "I'm calm.")
elif mood == Mood.PISSED:
self.bot.say(event.target, "I'm pissed off.")
return True

View file

@ -1,8 +0,0 @@
from edmond.plugin import Plugin
class OpinionPlugin(Plugin):
def __init__(self, bot):
super().__init__(bot)