From 6908df4808ba483e5658c1c24169ee19f9785bbc Mon Sep 17 00:00:00 2001
From: Pavel Kirilin <win10@list.ru>
Date: Fri, 5 Feb 2021 09:50:35 +0400
Subject: [PATCH] Added excluded chats. Description: - Added chat exclusion
 env. - Added .cid function.

Signed-off-by: Pavel Kirilin <win10@list.ru>
---
 Dockerfiles/Dockerfile      |  2 +-
 Dockerfiles/test.Dockerfile |  2 +-
 deploy.sh                   |  1 +
 src/actions/basic.py        |  6 ++++++
 src/actions/fun.py          |  4 +++-
 src/actions/replies.py      | 12 +++++++-----
 src/config.py               |  4 ++++
 src/utils/responses.py      | 12 ++++++++++++
 static_messages/help.txt    |  1 +
 tests/conftest.py           |  6 ++++++
 10 files changed, 42 insertions(+), 8 deletions(-)

diff --git a/Dockerfiles/Dockerfile b/Dockerfiles/Dockerfile
index e3ab490..a25926c 100644
--- a/Dockerfiles/Dockerfile
+++ b/Dockerfiles/Dockerfile
@@ -2,7 +2,7 @@ FROM python:3.8
 
 # Installing requirements
 COPY requirements/requirements.base.txt /tmp/
-RUN pip install -r /tmp/requirements.base.txt
+RUN pip install --no-cache-dir -r /tmp/requirements.base.txt
 
 # Copying actuall application
 COPY src/ /app/src
diff --git a/Dockerfiles/test.Dockerfile b/Dockerfiles/test.Dockerfile
index 6536daa..e7c28c3 100644
--- a/Dockerfiles/test.Dockerfile
+++ b/Dockerfiles/test.Dockerfile
@@ -13,7 +13,7 @@ COPY --from=docker_linter /bin/hadolint /bin/
 RUN hadolint -v
 # Installing requirements
 COPY requirements/ /reqs
-RUN pip install -r /reqs/requirements.dev.txt
+RUN pip install --no-cache-dir -r /reqs/requirements.dev.txt
 
 # Copying actuall application
 COPY . /app
diff --git a/deploy.sh b/deploy.sh
index 02d2227..30e5461 100644
--- a/deploy.sh
+++ b/deploy.sh
@@ -5,6 +5,7 @@ TELEGRAM_APP_ID="${TELEGRM_APP_ID_MASKED//a/}"
   echo "TELEGRAM_API_HASH=${TELEGRAM_API_HASH}"
   echo "TELEGRAM_ACCOUNT_PHONE=${TELEGRAM_ACCOUNT_PHONE}"
   echo "LIBRARIES_IO_API_TOKEN=${LIBRARIES_IO_API_TOKEN}"
+  echo "EXCLUDED_CHATS=${EXCLUDED_CHATS}"
 } >>.env
 
 # Store some info in app.info file
diff --git a/src/actions/basic.py b/src/actions/basic.py
index ddad473..c3889ce 100644
--- a/src/actions/basic.py
+++ b/src/actions/basic.py
@@ -25,6 +25,12 @@ async def ci(event):
     await event.respond(contents)
 
 
+@config.telegram_client.on(events.NewMessage(pattern=r"^\.cid$"))
+@mark_unread
+async def get_chat_id(event):
+    await event.respond(str(event.chat.id))
+
+
 @config.telegram_client.on(events.NewMessage(pattern=r"^\.t$"))
 @mark_unread
 async def show_time(event):
diff --git a/src/actions/fun.py b/src/actions/fun.py
index 76ad074..921ef66 100644
--- a/src/actions/fun.py
+++ b/src/actions/fun.py
@@ -5,7 +5,7 @@ import re
 from datetime import datetime
 
 from src.config import config
-from src.utils.responses import mark_unread
+from src.utils.responses import danger_message, mark_unread
 from src.utils.str_helpers import Rotor
 from telethon import events
 
@@ -28,6 +28,7 @@ swearing = [
 
 
 @config.telegram_client.on(events.NewMessage(pattern=r"^\.bl (.*)", forwards=False))
+@danger_message
 @mark_unread
 async def blyaficate(event: events.NewMessage.Event):
     message = event.message.message.lstrip(".bl ").strip()
@@ -67,6 +68,7 @@ async def blyaficate(event: events.NewMessage.Event):
         outgoing=False,
     )
 )
+@danger_message
 @mark_unread
 async def swearing_reply(event):
     await event.reply(
diff --git a/src/actions/replies.py b/src/actions/replies.py
index d682744..a834cf1 100644
--- a/src/actions/replies.py
+++ b/src/actions/replies.py
@@ -3,17 +3,16 @@ import random
 import re
 
 from src.config import config
-from src.utils.responses import check_if_only_smiles, mark_unread
+from src.utils.responses import check_if_only_smiles, danger_message, mark_unread
 from telethon import events
 
 logger = logging.getLogger(__name__)
 
 
 @config.telegram_client.on(events.ChatAction())
+@danger_message
 @mark_unread
 async def welcome(event: events.ChatAction.Event):
-    if str(event.chat.id) in ["-414207303", "-1001151788445"]:
-        return
     if event.user_joined:
         await event.respond(
             random.choice(
@@ -33,16 +32,18 @@ async def welcome(event: events.ChatAction.Event):
         outgoing=False,
     )
 )
+@danger_message
 @mark_unread
-async def hello(event):
+async def hello(event: events.ChatAction.Event):
     await event.respond(
-        random.choice(["Здравствуйте!", "Добрый день!", "Приветствую."])
+        random.choice(["Здравствуйте!", "Добрый день!", "Приветствую.", "Привет!"])
     )
 
 
 @config.telegram_client.on(
     events.NewMessage(pattern=check_if_only_smiles, outgoing=False)
 )
+@danger_message
 @mark_unread
 async def smile(event: events.NewMessage.Event):
     await event.respond(event.message.message)
@@ -55,6 +56,7 @@ async def smile(event: events.NewMessage.Event):
         forwards=False,
     )
 )
+@danger_message
 @mark_unread
 async def hello_fucker(event: events.NewMessage.Event):
     await event.respond(
diff --git a/src/config.py b/src/config.py
index 3ed8fd8..938d672 100644
--- a/src/config.py
+++ b/src/config.py
@@ -1,3 +1,5 @@
+from typing import List
+
 from pydantic import BaseSettings
 from pydantic.fields import Field
 from telethon import TelegramClient
@@ -22,6 +24,8 @@ class Config(BaseSettings):
 
     flask_port: str = Field(name="flask_port", default="8080", env="FLASK_PORT")
 
+    excluded_chats: List[str] = Field([], env="EXCLUDED_CHATS")
+
     telegram_client: TelegramClient = None
 
 
diff --git a/src/utils/responses.py b/src/utils/responses.py
index 8da5772..160fa50 100644
--- a/src/utils/responses.py
+++ b/src/utils/responses.py
@@ -3,6 +3,7 @@ import functools
 import logging
 import random
 
+from src.config import config
 from telethon import events, functions
 
 logger = logging.getLogger(__name__)
@@ -74,5 +75,16 @@ def mark_unread(f):
     return wrapper
 
 
+def danger_message(f):
+    @functools.wraps(f)
+    async def wrapper(event: events.NewMessage.Event):
+        if str(event.chat.id) in set(config.excluded_chats):
+            logger.debug("Skipping sending message")
+            return
+        await f(event)
+
+    return wrapper
+
+
 def check_if_only_smiles(message: str):
     return all([x in ")0." for x in message])
diff --git a/static_messages/help.txt b/static_messages/help.txt
index 1f6d008..8f01655 100644
--- a/static_messages/help.txt
+++ b/static_messages/help.txt
@@ -14,6 +14,7 @@
 
 Также умею ещё пару забавных штук.
 `.sc` посмотреть поддерживаемые курсы валют для автоматической конвертации.
+`.cid` Вернуть id текущего чата.
 `.scc` Посмотреть курсы криптовалют.
 `.rl` Создать бегущую строку из сообщения.
 `.i <запрос>` вернет пачку картинок с интернетиков.
diff --git a/tests/conftest.py b/tests/conftest.py
index 9b5fda3..4ce8a6b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -31,6 +31,12 @@ class NewMessageTestEvent(object):
         message.message = self._msg
         return message
 
+    @property
+    def chat(self):
+        chat = MagicMock()
+        chat.id = "123123123"
+        return chat
+
     async def get_chat(self):
         return MagicMock()
 
-- 
GitLab