diff --git a/.env.example b/.env.example index ee2411b..4b738d4 100644 --- a/.env.example +++ b/.env.example @@ -10,3 +10,5 @@ DB_NAME=postgres DB_USER=postgres DB_PASSWORD=password DB_VOLUME=./volume + +LOGS_DIR=./logs diff --git a/config.py b/config.py index 55ecd0b..3e82a9a 100644 --- a/config.py +++ b/config.py @@ -38,6 +38,7 @@ class Config: channel_chat_id: int comment_chat_id: int swear_words_file: str + logs_dir: str db: DBConfig @@ -47,6 +48,7 @@ class Config: channel_chat_id=int(env_required("CHANNEL_CHAT_ID")), comment_chat_id=int(env_required("COMMENT_CHAT_ID")), swear_words_file=env_with_default("SWEAR_WORDS", "assets/swear_words.txt"), + logs_dir=env_with_default("LOGS_DIR", "./logs"), db=DBConfig( host=env_with_default("DB_HOST", "localhost"), port=env_with_default("DB_PORT", "5432"), diff --git a/core/handlers/student.py b/core/handlers/student.py index 3f56df6..05112c9 100644 --- a/core/handlers/student.py +++ b/core/handlers/student.py @@ -226,6 +226,7 @@ async def handle_input_full_name(message: Message, state: FSMContext): 2 <= len(words) <= 3 and all(re.match(r"^[А-ЯЁа-яё\-]+$", word) for word in words) ): + logger.info(f"Invalid input full name: {message.text}") return await send_input_full_name_invalid(message) full_name = [] for word in words: @@ -257,6 +258,7 @@ async def send_input_study_group(message: Message): async def handle_input_study_group(message: Message, state: FSMContext): study_group = message.text.upper() if not validate_group(study_group): + logger.info(f"Invalid input study group: {message.text}") return await send_input_study_group_invalid(message) async with state.proxy() as data: data[DATA_STUDY_GROUP_KEY] = study_group diff --git a/core/middlewares/db.py b/core/middlewares/db.py index d363307..9484b90 100644 --- a/core/middlewares/db.py +++ b/core/middlewares/db.py @@ -15,3 +15,9 @@ async def pre_process(self, obj, data, *args): db: AsyncSession = self.pool() data["db"] = db data["store"] = Storage(db) + + async def post_process(self, obj, data, *args): + del data["store"] + db = data.get("db") + if db: + await db.close() diff --git a/core/middlewares/user_control.py b/core/middlewares/user_control.py index 4e8f3e7..2543ab9 100644 --- a/core/middlewares/user_control.py +++ b/core/middlewares/user_control.py @@ -36,6 +36,8 @@ async def pre_process(self, obj: TelegramObjectType, data, *args): elif this_user.id in config.admin_ids: role = domain.Role.ADMIN elif await store.is_user_banned(this_user.id): + logger.info(f"User with id={this_user.id} is banned. Handling skipped") raise CancelHandler() data["role"] = role + logger.info(f"Update (type={type(obj).__name__}) from user with id={this_user.id}. User role={role}") diff --git a/docker-compose.yml b/docker-compose.yml index c499072..d042885 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,6 +7,8 @@ services: network: host networks: - host + volumes: + - ${LOGS_DIR:-./logs}:/bot/logs depends_on: bmstu-direct-db: condition: service_healthy diff --git a/main.py b/main.py index e9de7c1..c477652 100644 --- a/main.py +++ b/main.py @@ -2,6 +2,8 @@ import asyncio import logging +from aiogram import Bot +from aiogram.types import BotCommand from aiogram.utils import executor from sqlalchemy.orm import sessionmaker @@ -18,16 +20,20 @@ logger = logging.getLogger(__name__) -async def main(): - if os.path.isfile("bot.log"): - os.remove("bot.log") +async def set_commands(bot: Bot): + commands = [ + BotCommand(command="/start", description="Подать обращение"), + ] + await bot.set_my_commands(commands) + +async def main(): logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", encoding="UTF-8", handlers=[ - logging.FileHandler("bot.log"), + logging.FileHandler(os.path.join(config.logs_dir, "bot.log")), logging.StreamHandler() ] ) @@ -42,6 +48,7 @@ async def main(): echo=False, ) + await set_commands(bot) bot_obj = await bot.get_me() logger.info(f"Bot username: {bot_obj.username}") dp.middleware.setup(DbMiddleware(db_pool)) diff --git a/services/db/storage.py b/services/db/storage.py index 0a4f691..850ac68 100644 --- a/services/db/storage.py +++ b/services/db/storage.py @@ -34,6 +34,7 @@ async def save_ticket(self, ticket: domain.Ticket) -> domain.TicketRecord: model = models.Ticket.from_domain(ticket) self._db.add(model) await self._db.commit() + logger.info(f"Add new ticket from chat id {ticket.owner_chat_id}") return model.to_domain() async def update_ticket(self, ticket_id: int, **kwargs) -> domain.TicketRecord: @@ -57,6 +58,7 @@ async def save_banned_user(self, user: domain.BannedUser) -> domain.BannedUser: model = models.BannedUser.from_domain(user) self._db.add(model) await self._db.commit() + logger.info(f"Banned user with id={user.chat_id}") return model.to_domain() async def is_user_banned(self, chat_id: int) -> bool: @@ -77,6 +79,7 @@ async def save_message(self, message: domain.Message) -> None: model = models.GroupMessage.from_domain(message) self._db.add(model) await self._db.commit() + logger.info(f"Add new message with chat_id={message.chat_id} and message_id={message.message_id}") async def message_id(self, _id: int) -> domain.Message: """