Skip to content

Commit

Permalink
fix: error with no closed session; ref: better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
acruxtech committed Feb 26, 2025
1 parent c9fa3e9 commit 04300bd
Show file tree
Hide file tree
Showing 8 changed files with 30 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD=password
DB_VOLUME=./volume

LOGS_DIR=./logs
2 changes: 2 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class Config:
channel_chat_id: int
comment_chat_id: int
swear_words_file: str
logs_dir: str
db: DBConfig


Expand All @@ -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"),
Expand Down
2 changes: 2 additions & 0 deletions core/handlers/student.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions core/middlewares/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
2 changes: 2 additions & 0 deletions core/middlewares/user_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ services:
network: host
networks:
- host
volumes:
- ${LOGS_DIR:-./logs}:/bot/logs
depends_on:
bmstu-direct-db:
condition: service_healthy
Expand Down
15 changes: 11 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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()
]
)
Expand All @@ -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))
Expand Down
3 changes: 3 additions & 0 deletions services/db/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
"""
Expand Down

0 comments on commit 04300bd

Please sign in to comment.