Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New feature logging #16

Merged
merged 2 commits into from
Feb 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions bot/src/handlers/commands.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

from aiogram import F, Router
from aiogram.filters import Command, CommandStart
from aiogram.types import Message, ReplyKeyboardRemove
Expand All @@ -22,12 +24,14 @@
@router.message(CommandStart())
async def start(message: Message):
if (message.from_user.id == int(settings.manager_chat_id)):
logging.info('Координатор запустил бота')
return await message.answer(
HELLO_COORDINATOR.format(full_name=message.from_user.full_name)
)
await message.answer(
HELLO_MESSAGE.format(full_name=message.from_user.full_name)
)
logging.info('Пользователь запустил бота')
await message.answer(START_VOLUNTEERING_INFO)

open_meetings = await get_open_meetings()
Expand All @@ -38,9 +42,11 @@ async def start(message: Message):
),
reply_markup=get_invitation_keyboard(GO_TO_MEETING, REFUSE_MEETING)
)
logging.info('Встречи получены')
else:
await message.answer(NO_MEETINGS_MESSAGE)
await show_interview_invitation(message)
logging.error('Встречи не получены')


@router.message(Command(commands=['go_to_open_meeting']))
Expand All @@ -55,27 +61,32 @@ async def registration_for_metting(
)
)
await forms.show('registration-for-meeting-form')
logging.info('Форма регистрации на встречу открыта')
else:
await message.answer(NO_MEETINGS_MESSAGE)
await show_interview_invitation(message)
logging.error('Встречи не получены')


@router.message(F.text == GO_TO_MEETING)
async def show_metting_form(
message: Message, forms: FormsManager
) -> None:
await forms.show('registration-for-meeting-form')
logging.info('Форма регистрации на встречу открыта')


@router.message(F.text == REFUSE_MEETING)
async def show_interview_invitation(message: Message) -> None:
await message.answer(INTERVIEW_INVITATION)
logging.info('Приглашение на встречу отклонено')
await message.answer(
INTERVIEW_INVITATION_MESSAGE,
reply_markup=get_invitation_keyboard(
GO_TO_INTERVIEW, REFUSE_INTERVIEW
)
)
logging.info('Приглашение на встречу получено')


@router.message(Command(commands=['go_to_interview']))
Expand All @@ -93,16 +104,19 @@ async def command_help(message: Message) -> None:
HELP_INFO,
reply_markup=ReplyKeyboardRemove()
)
logging.info('Помощь получена')


@router.message(Command(commands=['contacts']))
async def command_contacts(message: Message) -> None:
await message.answer(CONTACTS_INFO)
logging.info('Контакты получены')


@router.message(Command(commands=['documents']))
async def get_documents_list(message: Message) -> None:
await message.answer(DOCUMENTS_FOR_INTERVIEW)
logging.info('Документы получены')


@router.message(Command(commands=['meeting_schedule']))
Expand All @@ -123,6 +137,8 @@ async def command_meeting_schedule(message: Message) -> None:
GO_TO_MEETING, REFUSE_MEETING
)
)
logging.info('Встречи получены')
else:
await message.answer(NO_MEETINGS_MESSAGE)
await show_interview_invitation(message)
logging.error('Встречи не получены')
20 changes: 19 additions & 1 deletion bot/src/main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import asyncio
import logging
from pathlib import Path
import sys

from aiogram import Bot, Dispatcher
from aiogram.types.bot_command import BotCommand
from aiogram.utils.callback_answer import CallbackAnswerMiddleware
from aiogram.fsm.storage.redis import RedisStorage, Redis
from aiogram_forms import dispatcher
from core import settings
from core.logging_config import configure_logging
from handlers import routers
from handlers.constants import (CONTACTS_COMMAND, GO_TO_INTERVIEW_COMMAND,
GO_TO_OPEN_MEETING_COMMND, HELP_COMMAND,
Expand All @@ -26,16 +30,26 @@ async def setup_bot_commands(bot: Bot):
BotCommand(command='/contacts', description=CONTACTS_COMMAND)
]
await bot.set_my_commands(main_menu_commands)
logging.info('Команды бота установлены')


async def main():
configure_logging(Path(__file__).parent / 'logs')
logging.info('Запуск бота')
redis = Redis(host=settings.redis_host)
storage = RedisStorage(redis=redis)
bot = Bot(settings.bot_token, parse_mode='HTML')
logging.info('Соединение с Redis создано')
try:
bot = Bot(settings.bot_token, parse_mode='HTML')
logging.info('Бот создан')
except Exception as error:
logging.exception(f'Бот не создан. Ошибка {error}')
sys.exit('Отсутствуют данные окружения. Завершаю работу.')
dp = Dispatcher(storage=storage)
dp.message.middleware(ThrottlingMiddleware(settings.throttle_time_spin,
settings.throttle_time_other))
dp.startup.register(setup_bot_commands)
logging.info('Команды для бота регистрированы')
dp.callback_query.middleware(CallbackAnswerMiddleware())
dispatcher.attach(dp)

Expand All @@ -47,8 +61,12 @@ async def main():
bot,
allowed_updates=dp.resolve_used_update_types()
)
logging.info('Бот запущен')
except Exception as error:
logging.exception(f'Бот упал с ошибкой {error}')
finally:
await bot.session.close()
logging.info('Сеанс бота закрыт')


if __name__ == '__main__':
Expand Down
17 changes: 17 additions & 0 deletions bot/src/services/meetings.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
from collections.abc import Generator
from http import HTTPStatus
import logging
from pathlib import Path

import aiohttp
from aiohttp import ClientResponse

from core import settings
from core.logging_config import configure_logging
from schemas import meetings
from services.exceptions import HTTPRequestError


configure_logging(Path(__file__).parent / 'logs')


class MeetingService:
def __init__(self):
self._path = '/meetings'

async def get_meetings(self) -> Generator[meetings.GetMeeting]:
async with aiohttp.ClientSession(settings.url) as session:
async with session.get(self._path) as response:
logging.info('Получение списка встреч')
return await self._get_meetings(response)

async def create_meeting(
Expand All @@ -26,8 +33,10 @@ async def create_meeting(
self._path, json=meeting.model_dump()
) as response:
if response.status == HTTPStatus.OK:
logging.info('Встреча создана')
return meetings.GetMeeting(**(await response.json()))
res = await response.json()
logging.error('Не удалось создать встречу')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}'
)
Expand All @@ -41,13 +50,15 @@ async def update_meeting(
async with session.patch(
f'{self._path}/{id}', json=meeting.model_dump()
) as response:
logging.info('Встреча обновлена')
return await self._get_meeting(response)

async def delete_meeting(self, id: int):
async with aiohttp.ClientSession(settings.url) as session:
async with session.delete(f'{self._path}/{id}') as response:
if not (response.status == HTTPStatus.OK):
res = await response.json()
logging.error('Не удалось удалить встречу')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}.'
)
Expand All @@ -57,18 +68,22 @@ async def get_participants_list(self, id: int):
async with session.get(
f'{self._path}/{id}/participants') as response:
if response.status == HTTPStatus.OK:
logging.info('Список участников получен')
return meetings.MeetingParticipants(
**(await response.json()))
res = await response.json()
logging.error('Не удалось получить список участников')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}'
)

async def _get_meeting(self,
response: ClientResponse) -> meetings.GetMeeting:
if response.status == HTTPStatus.OK:
logging.info('Встреча получена')
return meetings.GetMeeting(**(await response.json()))
res = await response.json()
logging.error('Не удалось получить встречу')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}'
)
Expand All @@ -77,9 +92,11 @@ async def _get_meetings(
self, response: ClientResponse
) -> Generator[meetings.GetMeeting]:
if response.status == HTTPStatus.OK:
logging.info('Список встреч получен')
return (meetings.GetMeeting(**json) for json in
await response.json())
res = await response.json()
logging.error('Не удалось получить список встреч')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}'
)
14 changes: 14 additions & 0 deletions bot/src/services/users.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,62 @@
from collections.abc import Generator
from http import HTTPStatus
import logging
from pathlib import Path

import aiohttp
from aiohttp import ClientResponse

from core import settings
from core.logging_config import configure_logging
from schemas import users
from services.exceptions import HTTPRequestError


configure_logging(Path(__file__).parent / 'logs')


class UserService:
def __init__(self):
self._path = '/users'

async def get_users(self) -> Generator[users.GetUser]:
async with aiohttp.ClientSession(settings.url) as session:
async with session.get(self._path) as response:
logging.info('Получение списка пользователей')
return await self._get_users(response)

async def create_user(self, user: users.UserCreate) -> users.GetUser:
async with aiohttp.ClientSession(settings.url) as session:
async with session.post(self._path,
json=user.model_dump()) as response:
logging.info('Создание пользователя')
return await self._get_user(response)

async def update_user(self, id: int,
user: users.UserUpdate) -> users.GetUser:
async with aiohttp.ClientSession(settings.url) as session:
async with session.post(f'self._path/{id}',
json=user.model_dump()) as response:
logging.info('Обновление пользователя')
return await self._get_user(response)

async def delete_user(self, id: int):
async with aiohttp.ClientSession(settings.url) as session:
async with session.delete(f'{self._path}/{id}') as response:
if not (response.status == HTTPStatus.OK):
res = await response.json()
logging.error('Не удалось удалить пользователя')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}'
)

async def _get_user(self,
response: ClientResponse) -> users.GetUser:
if response.status == HTTPStatus.OK:
logging.info('Пользователь получен')
return users.GetUser(**(await response.json()))
res = await response.json()
logging.error('Не удалось получить пользователя')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}'
)
Expand All @@ -53,9 +65,11 @@ async def _get_users(
self, response: ClientResponse
) -> Generator[users.GetUser]:
if response.status == HTTPStatus.OK:
logging.info('Список пользователей получен')
return (users.GetUser(**json) for json in
await response.json())
res = await response.json()
logging.error('Не удалось получить список пользователей')
raise HTTPRequestError(
f'Ошибка запроса: {res["detail"]}'
)