Skip to content

Commit

Permalink
update README.MD
Browse files Browse the repository at this point in the history
  • Loading branch information
taimast committed Jan 8, 2024
1 parent c609209 commit 2f4b865
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 38 deletions.
48 changes: 24 additions & 24 deletions README.MD
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Aiogram Project Template

#### Этот шаблон был разработан для создания ботов на основе aiogram 3, и включает в себя несколько базовых функций.
#### This template was designed to create bots based on aiogram 3, and includes several basic functions.


## Возможности
## Features

- Административная панель
- Промежуточное программное обеспечение (Middleware)
- Настройка локализации через Fluent
- Поддержка платёжных систем:
- Administrative panel
- Middleware
- Localization settings via Fluent
- Support for payment systems:
- [CryptoCloud](https://cryptocloud.plus/)
- [CryptoPay](https://github.com/LulzLoL231/pyCryptoPayAPI)
- [Qiwi](https://qiwi.com/p2p-admin/api/)
Expand All @@ -18,27 +18,27 @@
- [Cryptomus](https://cryptomus.com/)
- [WalletPay](https://pay.wallet.tg/)

- Командная строка (CLI)
- Настройка Вебхука
- ORM базы данных: [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/)
- Инструмент миграции БД: [Alembic](https://github.com/sqlalchemy/alembic)
- Удобное управление конфигурацией проекта через [Pydantic](https://github.com/pydantic/pydantic)
- Command Line (CLI)
- Configuring the Webhook
- Database ORM: [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy /)
- DB Migration Tool: [Alembic](https://github.com/sqlalchemy/alembic )
- Convenient project configuration management via [Pydantic](https://github.com/pydantic/pydantic )

## Инициализация проекта
## Initialization of the project

Для инициализации проекта запустите скрипт `init_project.py`, пример: `python3 init_project.py -p <your_project_dir> -d`
To initialize the project, run the script `init_project.py `, example: `python3 init_project.py -p <your_project_dir> -d`

- `-d` - установка зависимостей
- `-p` - путь к директории проекта, по умолчанию - `./`. Если указанная директория не существует, то будет создан новый
проект с использованием `poetry new <your_project_dir>`
- `-d` - installing dependencies
- `-p` is the path to the project directory, by default - `./`. If the specified directory does not exist, a new one will be created
a project using `poetry new <your_project_dir>`

## Локализация
## Localization

Для локализации используется [Fluent](https://projectfluent.org/fluent/guide/).
По умолчанию, папка с локализациями находится по пути `crying/locales`.
[Fluent] is used for localization(https://projectfluent.org/fluent/guide /).
By default, the folder with localizations is located at the path `crying/locales'.

## _Утилиты_
- `project/crying/utils/ftl_parser_cli.py` - Live генерация заглушек для локализации.
- `project/crying/utils/ftl_translator.py` - Автоматический перевод локализации на все языки через Google Translate и генерация ftl.
- `project/crying/apps/bot/callback_data/paginator.py` - Пагинатор страниц для InlineKeyboardMarkup.
- `project/crying/db/models/user/mixins.py` - Миксины для моделей пользователей. На данный момент для Рефералки и Подключения пользователей к друг другу через бота. (Пример подключения в `helpers/connect`)
## _utilities_
- `project/crying/utils/ftl_parser_cli.py ` - Live generation of stubs for localization.
- `project/crying/utils/ftl_translator.py ` - Automatic localization translation into all languages via Google Translate and ftl generation.
- `project/crying/apps/bot/callback_data/paginator.py ` - Paginator of pages for InlineKeyboardMarkup.
- `project/crying/db/models/user/mixins.py ` - Mixins for user models. At the moment, for Referrals and Connecting users to each other through a bot. (Example of connection in `helpers/connect')
2 changes: 2 additions & 0 deletions helpers/connect/src/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@


async def disconnect_user(bot: Bot, user: User, l10n: TranslatorRunner):
await user.awaitable_attrs.connected_user
if not user.connected_user:
return
connected_user = user.connected_user
Expand All @@ -44,6 +45,7 @@ async def end_conversation(message: types.Message, bot: Bot, user: User, l10n: T

@router.message(IsConnectedFilter(), ~Command(BaseCommands.START))
async def connected(message: types.Message, bot: Bot, user: User, settings: Settings, l10n: TranslatorRunner):
await user.awaitable_attrs.connected_user
connected_user = user.connected_user
# connected_is_admin = connected_user.id in settings.bot.admins
if user.id not in settings.bot.admins:
Expand Down
9 changes: 0 additions & 9 deletions project/crying/apps/bot/handlers/common/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,3 @@ async def start(
l10n.start(name=message.from_user.full_name),
reply_markup=common_kbs.inline_start()
)

@on.message()
async def media(message:types.Message):
builder = MediaGroupBuilder()
builder.add_photo(types.FSInputFile(MEDIA_DIR / "img.png"), caption="1")
builder.add_photo(types.FSInputFile(MEDIA_DIR / "img.png"))
builder.add_photo(types.FSInputFile(MEDIA_DIR / "img.png"))
group = builder.build()
await message.answer_media_group(group)
1 change: 0 additions & 1 deletion project/crying/apps/bot/middlewares/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@


class UserMiddleware(BaseMiddleware):

async def __call__(
self,
handler: Callable[[Message | CallbackQuery, dict[str, Any]], Awaitable[Any]],
Expand Down
3 changes: 3 additions & 0 deletions project/crying/db/models/user/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ async def today_count(cls, session: AsyncSession) -> int:
result = await session.execute(
select(cls).where(cls.created_at >= datetime.date.today()))
return len(result.all())

def pretty(self):
return f"{self.full_name} @{self.username}"
6 changes: 3 additions & 3 deletions project/crying/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@

from project.crying import setup
from project.crying.config import Settings
from project.crying.utils.other import send_info
from project.crying.utils.other import send_start_info


async def on_startup(bot: Bot):
_task = asyncio.create_task(send_info(bot))
_task = asyncio.create_task(send_start_info(bot, only_text=True))


async def on_shutdown():
async def on_shutdown(bot: Bot):
pass


Expand Down
20 changes: 20 additions & 0 deletions project/crying/utils/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ async def mailings(bot: Bot, text: str, users: list | int, *, reply_markup: Repl
await asyncio.sleep(0.5)
return mails

async def copy_mailings(message: types.Message, users: list | int, *, pre_text: str | None=None,
reply_markup: ReplyMarkup = None) -> list[types.Message]:
""" Send message to all users in list """
if isinstance(users, int):
users = [users]
mails = []
for user in users:
try:
if pre_text:
await message.bot.send_message(user, pre_text)
mails.append(
# await bot.send_message(user, text, reply_markup=reply_markup)
await message.copy_to(user, reply_markup=reply_markup)
)
except Exception as e:
print(e)
await asyncio.sleep(0.5)
return mails



async def split_sending_proper(message: types.Message,
answer_text: str,
Expand Down
5 changes: 4 additions & 1 deletion project/crying/utils/other.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ def get_archive():
return document


async def send_info(bot: Bot):
async def send_start_info(bot: Bot, only_text: bool = True):
username = (await bot.me()).username
info_text = f"Bot @{username} started"
logger.warning(info_text)
if only_text:
await bot.send_message(269019356, info_text)
return
document = await asyncio.to_thread(get_archive)
await bot.send_document(
269019356,
Expand Down

0 comments on commit 2f4b865

Please sign in to comment.