misc_reactions: handle weights on reactions

This commit is contained in:
dece 2020-11-05 23:52:02 +01:00
parent cc81956b58
commit 250d05e2f7

View file

@ -11,6 +11,10 @@ class MiscReactionsPlugin(Plugin):
field on the plugin configuration. As all reactions are optional, field on the plugin configuration. As all reactions are optional,
configurations for each reactions are optional as well and can be safely configurations for each reactions are optional as well and can be safely
removed from the configuration (as usual except fields in REQUIRED_CONFIGS). removed from the configuration (as usual except fields in REQUIRED_CONFIGS).
The types of reactions can appear with a different probability if the
configured reaction has a suffix of ":n", n being a number defining the
reaction weight. The default weight when no suffix is used is 1.
""" """
REQUIRED_CONFIGS = ["reactions", "rate"] REQUIRED_CONFIGS = ["reactions", "rate"]
@ -28,20 +32,35 @@ class MiscReactionsPlugin(Plugin):
def __init__(self, bot): def __init__(self, bot):
super().__init__(bot) super().__init__(bot)
self.priority = -10 self.priority = -10
self.reactions = self.get_reactions() self.reactions, self.weights = self.get_reactions()
def get_reactions(self): def get_reactions(self):
"""Get configured reactions in a dict mapping names to methods.""" """Get configured reactions in a method list, maybe with weights."""
reactions = {} reactions = []
available_reactions = self.REACTIONS & set(self.config["reactions"]) weights = []
for reaction in available_reactions: for reaction in self.config["reactions"]:
reactions[reaction] = getattr(self, f"react_with_{reaction}") weight = 1
return reactions if ":" in reaction:
reaction, weight_str = reaction.split(":", maxsplit=1)
try:
weight = int(weight_str)
except ValueError:
pass
if reaction not in self.REACTIONS:
continue
reactions.append(getattr(self, f"react_with_{reaction}"))
weights.append(weight)
return reactions, weights
def on_pubmsg(self, event): def on_pubmsg(self, event):
if proc(self.config["rate"]): if proc(self.config["rate"]):
method = random.choice(list(self.reactions.values())) if self.weights:
method = random.choices(self.reactions, self.weights)[0]
else:
method = random.choice(self.reactions)
method(event) method(event)
return True
return False
def react_with_sentence(self, event): def react_with_sentence(self, event):
"""React with a random sentence from config list.""" """React with a random sentence from config list."""