From f6ad89ebb8856b45e0e3f544467359c27f41adfb Mon Sep 17 00:00:00 2001
From: Vladislav Bakaev <vlad@bakaev.tech>
Date: Tue, 25 Jul 2023 15:20:49 +0400
Subject: [PATCH] More smart answer

---
 lenochka/brain/brain.py      |  6 ++----
 lenochka/brain/brain_cell.py | 32 +++++++++++---------------------
 2 files changed, 13 insertions(+), 25 deletions(-)

diff --git a/lenochka/brain/brain.py b/lenochka/brain/brain.py
index c393afa..74883cd 100644
--- a/lenochka/brain/brain.py
+++ b/lenochka/brain/brain.py
@@ -24,7 +24,5 @@ class Brain:
         :param state_of_mind: lenochka's current state of mind.
             It's always clear in order to make the most thoughtful answer.
         """
-        if not self.cell.do_i_need_to_say_something():
-            return
-        thoughtful_answer = self.cell.create_reply(message.text)
-        await message.reply(thoughtful_answer)
+        if thoughtful_answer := self.cell.create_reply(message.text):
+            await message.reply(thoughtful_answer)
diff --git a/lenochka/brain/brain_cell.py b/lenochka/brain/brain_cell.py
index bab5b7f..14caba3 100644
--- a/lenochka/brain/brain_cell.py
+++ b/lenochka/brain/brain_cell.py
@@ -1,6 +1,9 @@
 import re
 import secrets
+from typing import Optional
 
+
+MAX_TRIGGER_WORDS = 3
 WORD_PATTERN = re.compile(r"(\w+)")
 
 
@@ -11,20 +14,7 @@ class BrainCell:
     It decides when and what to say.
     """
 
-    def do_i_need_to_say_something(self) -> bool:
-        """
-        One of the most important decisions.
-
-        This brain cell's function looks
-        deep inside the palaces of the mind,
-        searching through the secrets of the universe
-        and decides if she want to say something.
-
-        :return: The decision.
-        """
-        return secrets.randbelow(11) < 1  # noqa: WPS432
-
-    def create_reply(self, sentence: str) -> str:
+    def create_reply(self, sentence: str) -> Optional[str]:
         """
         The hardest action to accomplish.
 
@@ -36,10 +26,10 @@ class BrainCell:
         :return: actual reply.
         """
         tokens = WORD_PATTERN.findall(sentence)
-        for token in reversed(tokens):
-            token_parts = token.lower().split("да")
-            if len(token_parts) > 1:
-                postfix = token_parts[-1]
-                break
-
-        return f"Пизда{postfix}."
+        if not tokens or len(tokens) > MAX_TRIGGER_WORDS:
+            return None
+        *_, last_token = tokens
+        last_token_parts = last_token.lower().split("да")
+        if len(last_token_parts) > 1:
+            return f"Пизда{last_token_parts[-1]}."
+        return None
-- 
GitLab