Skip to content

Commit c74c4ba

Browse files
committed
Refactoring
1 parent a2699e9 commit c74c4ba

File tree

7 files changed

+69
-24
lines changed

7 files changed

+69
-24
lines changed

README.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# 🤖 Aiogram Fastapi Bot Template
22

3-
[![Actions status](https://github.com/BushlanovDev/aiogram-fastapi-bot-template/actions/workflows/check.yml/badge.svg)](https://github.com/BushlanovDev/aiogram-fastapi-bot-template/actions) [![Python](https://img.shields.io/badge/Python-3.12%2B-brightgreen)](https://www.python.org/downloads/) [![Aiogram](https://img.shields.io/badge/aiogram-3.17-brightgreen)](https://pypi.org/project/aiogram/)
3+
[![Actions status](https://github.com/BushlanovDev/aiogram-fastapi-bot-template/actions/workflows/check.yml/badge.svg)](https://github.com/BushlanovDev/aiogram-fastapi-bot-template/actions)
4+
[![Python](https://img.shields.io/badge/Python-3.12%2B-brightgreen)](https://www.python.org/downloads/)
5+
[![Aiogram](https://img.shields.io/badge/aiogram-3.17-brightgreen)](https://pypi.org/project/aiogram/)
6+
[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE)
47

58
A simple template for creating a telegram bot on webhooks using the **aiogram** and **fastapi**
69

@@ -39,3 +42,7 @@ Run bot `python main.py` or `docker compose up -d`
3942
| middlewares | Middlewares for localization, throttling |
4043
| services | Custom libraries |
4144
| states | State objects |
45+
46+
## 📄 License
47+
48+
This repository's source code is available under the [MIT License](LICENSE).

bot/handlers/handlers.py

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,22 @@
44
from aiogram.types import CallbackQuery, Message
55

66
from bot.callbacks.callback import SaveCallbackFactory
7-
from bot.i18n.lexicon import Lexicon
8-
from bot.keyboards.keyboards import Keyboards
9-
from bot.services.bot_service import BotService
7+
from bot.services.context import HandlerContext
108
from bot.states.bot_state import BotState
119

1210

1311
class Handlers:
14-
def __init__(self, bot: Bot, kb: Keyboards, bot_service: BotService):
12+
def __init__(self, bot: Bot):
1513
self.bot = bot
16-
self.kb = kb
17-
self.bot_service = bot_service
1814

19-
async def start_command(self, message: Message, lexicon: Lexicon, user_lang: str | None):
15+
async def start_command(self, message: Message, ctx: HandlerContext, user_lang: str | None):
2016
await message.answer(
21-
text=lexicon.get_text('Hi user! This start message.', user_lang),
22-
reply_markup=self.kb.get_start_button(),
17+
text=ctx.lexicon.get_text('Hi user! This start message.', user_lang),
18+
reply_markup=ctx.keyboards.get_start_button(ctx.lexicon, user_lang),
2319
)
2420

25-
async def help_command(self, message: Message, lexicon: Lexicon, user_lang: str | None):
26-
await message.answer(text=lexicon.get_text('This help message.', user_lang))
21+
async def help_command(self, message: Message, ctx: HandlerContext, user_lang: str | None):
22+
await message.answer(text=ctx.lexicon.get_text('This help message.', user_lang))
2723

2824
async def answer(self, message: Message, answer: str):
2925
await self.__send_message(message.chat.id, answer, message.message_id)
@@ -40,18 +36,18 @@ async def answer_fsm_state_1(self, message: Message, state: FSMContext):
4036
async def answer_fsm_state_2(self, message: Message, state: FSMContext):
4137
await state.update_data(step_2=message.text)
4238
data = await state.get_data()
43-
await message.answer(f"Step 1: {data['step_1']}\nStep 2: {data['step_2']}")
39+
await message.answer(f'Step 1: {data["step_1"]}\nStep 2: {data["step_2"]}')
4440
await state.clear()
4541

46-
async def answer_inline_button(self, message: Message, lexicon: Lexicon):
42+
async def answer_inline_button(self, message: Message, ctx: HandlerContext, user_lang: str | None):
4743
callback = SaveCallbackFactory(message_id=message.message_id).pack()
4844
await message.answer(
49-
text=lexicon.get_text('Inline button message'),
50-
reply_markup=self.kb.get_inline_button(callback_data=callback),
45+
text=ctx.lexicon.get_text('Inline button message'),
46+
reply_markup=ctx.keyboards.get_inline_button(ctx.lexicon, user_lang, callback),
5147
)
5248

53-
async def reply(self, message: Message):
54-
await message.reply(text=self.bot_service.upper(message.text))
49+
async def reply(self, message: Message, ctx: HandlerContext):
50+
await message.reply(text=ctx.bot_service.upper(message.text))
5551

5652
async def process_any_inline_button_press(self, callback: CallbackQuery, callback_data: SaveCallbackFactory):
5753
await callback.message.answer(text=callback_data.pack())

bot/i18n/ru.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
LEXICON_RU: dict[str, str] = {
2+
'hi': 'привет',
3+
'Save': 'Сохранить',
24
'Hi user! This start message.': 'Привет, пользователь! Это стартовое сообщение.',
35
'This help message.': 'Это справочное сообщение.',
46
}

bot/keyboards/keyboards.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,26 @@
11
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup
22

3+
from bot.i18n.lexicon import Lexicon
4+
35

46
class Keyboards:
57
def __init__(self):
68
pass
79

8-
def get_start_button(self) -> ReplyKeyboardMarkup:
10+
def get_start_button(self, lexicon: Lexicon, user_lang: str | None) -> ReplyKeyboardMarkup:
911
kb_list = [
10-
[KeyboardButton(text='hi'), KeyboardButton(text='test')],
12+
[KeyboardButton(text=lexicon.get_text('hi', user_lang)), KeyboardButton(text='test')],
1113
[KeyboardButton(text='inline button'), KeyboardButton(text='fsm')],
1214
]
1315

1416
return ReplyKeyboardMarkup(keyboard=kb_list, resize_keyboard=True, one_time_keyboard=True)
1517

16-
def get_inline_button(self, callback_data: str | None = None) -> InlineKeyboardMarkup:
18+
def get_inline_button(
19+
self, lexicon: Lexicon, user_lang: str | None, callback_data: str | None = None
20+
) -> InlineKeyboardMarkup:
1721
inline_kb_list = [
1822
[
19-
InlineKeyboardButton(text='Save', callback_data=callback_data),
23+
InlineKeyboardButton(text=lexicon.get_text('Save', user_lang), callback_data=callback_data),
2024
],
2125
]
2226

bot/middlewares/context.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from aiogram import BaseMiddleware
2+
3+
from bot.services.context import HandlerContext
4+
5+
6+
class ContextMiddleware(BaseMiddleware):
7+
async def __call__(self, handler, event, data):
8+
data['ctx'] = HandlerContext(
9+
lexicon=data['lexicon'],
10+
keyboards=data['keyboards'],
11+
bot_service=data['bot_service'],
12+
)
13+
14+
return await handler(event, data)

bot/services/context.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from dataclasses import dataclass
2+
3+
from bot.i18n.lexicon import Lexicon
4+
from bot.keyboards.keyboards import Keyboards
5+
from bot.services.bot_service import BotService
6+
7+
8+
@dataclass
9+
class HandlerContext:
10+
lexicon: Lexicon
11+
keyboards: Keyboards
12+
bot_service: BotService

main.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from bot.handlers.handlers import Handlers
1818
from bot.i18n.lexicon import Lexicon
1919
from bot.keyboards.keyboards import Keyboards
20+
from bot.middlewares.context import ContextMiddleware
2021
from bot.middlewares.i18n import I18nMiddleware
2122
from bot.middlewares.throttling import ThrottlingMiddleware
2223
from bot.services.bot_service import BotService
@@ -92,10 +93,19 @@ def register_handlers(dp: Dispatcher, hd: Handlers) -> None:
9293
def register_middlewares(dp: Dispatcher) -> None:
9394
dp.update.outer_middleware(I18nMiddleware())
9495
dp.update.outer_middleware(ThrottlingMiddleware())
96+
dp.update.outer_middleware(ContextMiddleware())
9597

9698

9799
def register_workflow_data(dp: Dispatcher, settings: Settings) -> None:
98100
dp.workflow_data.update({'answer': 'Hello', 'lexicon': Lexicon(settings.app.default_language)})
101+
dp.workflow_data.update(
102+
{
103+
'answer': 'Hello',
104+
'lexicon': Lexicon(settings.app.default_language),
105+
'keyboards': Keyboards(),
106+
'bot_service': BotService(),
107+
}
108+
)
99109

100110

101111
def create_app(bot: Bot, dp: Dispatcher, settings: App) -> FastAPI:
@@ -115,9 +125,9 @@ def main() -> None:
115125
bot = create_bot(settings.tg_bot)
116126
dp = create_dispatcher(MemoryStorage())
117127
app = create_app(bot, dp, settings.app)
118-
register_handlers(dp, Handlers(bot, Keyboards(), BotService()))
119-
register_middlewares(dp)
128+
register_handlers(dp, Handlers(bot))
120129
register_workflow_data(dp, settings)
130+
register_middlewares(dp)
121131

122132
logger.debug('Application is running')
123133

0 commit comments

Comments
 (0)