Skip to content

Структура Проекта

Предлагаю проверенный временем формат стартового шаблона. Шаблон может быть не идеален, но он прошел проверку множеством проектов. Эта структура удобна в поддержке и легко расширяется. Вот как она выглядит:

python
- db_handler/
  - __init__.py
  - db_class.py
- handlers/
  - __init__.py
  - start.py
- keyboards/
  - __init__.py
  - all_keyboards.py
- work_time/
  - __init__.py
  - time_func.py
- utils/
  - __init__.py
  - my_utils.py
- filters/
  - __init__.py
  - is_admin.py
- middlewares/
  - __init__.py
  - check_sub.py
- .env
- aiogram_run.py
- create_bot.py
- requirements.txt
- run.py

img.png

Теперь давайте разбираться со структурой и с наполнением каждого файла.

Начнем с файла .env:

TOKEN=772000:G200Ap6eotkMKJD_nwSAfg
ADMINS=00000000,000000001
PG_LINK=postgresql://USER_LOGIN:USER_PASSWORD@HOST_API:PORT/NAME_BD
  • TOKEN: Токен, выданный BotFather
  • ADMINS: Список телеграмм ID администраторов (можно хранить и в базе данных, но на старте так удобнее)
  • PG_LINK: Ссылка подключения к базе данных PostgreSQL

По поводу PostgreSQL. Разработан собственный класс на основе asyncpg, который позволяет универсально работать как с Telegram-ботами, так и с любыми другими проектами, где требуется асинхронное взаимодействие с базой данных.

Установка библиотек

shell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

(.venv) PS F:\code_last\bots\aiogram_3_bot> pip install -r requirements.txt
Collecting asyncpg (from -r requirements.txt (line 1))
  Obtaining dependency information for asyncpg from https://files.pythonhosted.org/packages/c8/a4/cec76
b3389c4c5ff66301cd100fe88c318563ec8a520e0b2e792b5b84972/asyncpg-0.30.0-cp313-cp313-win_amd64.whl.metadata
  Downloading asyncpg-0.30.0-cp313-cp313-win_amd64.whl.metadata (5.2 kB)
Collecting aiogram (from -r requirements.txt (line 2))
  Obtaining dependency information for aiogram from https://files.pythonhosted.org/packages/1e/58/b4decb5aff36c35d3ae25ade34ded04a96baa2de79deb2d1daa89e2736e2/aiogram-3.15.0-py3-none-any.whl.metadata       
  Downloading aiogram-3.15.0-py3-none-any.whl.metadata (7.5 kB)
Collecting python-decouple (from -r requirements.txt (line 3))
  Obtaining dependency information for python-decouple from https://files.pythonhosted.org/packages/a2/
d4/9193206c4563ec771faf2ccf54815ca7918529fe81f6adb22ee6d0e06622/python_decouple-3.8-py3-none-any.whl.metadata
  Downloading python_decouple-3.8-py3-none-any.whl.metadata (14 kB)
Collecting aiofiles<24.2,>=23.2.1 (from aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for aiofiles<24.2,>=23.2.1 from https://files.pythonhosted.org/packa
ges/a5/45/30bb92d442636f570cb5651bc661f52b610e2eec3f891a5dc3a4c3667db0/aiofiles-24.1.0-py3-none-any.whl.metadata
  Downloading aiofiles-24.1.0-py3-none-any.whl.metadata (10 kB)
Collecting aiohttp<3.11,>=3.9.0 (from aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for aiohttp<3.11,>=3.9.0 from https://files.pythonhosted.org/package
s/28/1d/18ef37549901db94717d4389eb7be807acbfbdeab48a73ff2993fc909118/aiohttp-3.10.11-cp313-cp313-win_amd64.whl.metadata
  Downloading aiohttp-3.10.11-cp313-cp313-win_amd64.whl.metadata (8.0 kB)
Collecting certifi>=2023.7.22 (from aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for certifi>=2023.7.22 from https://files.pythonhosted.org/packages/
12/90/3c9ff0512038035f59d279fddeb79f5f1eccd8859f06d6163c58798b9487/certifi-2024.8.30-py3-none-any.whl.metadata
  Using cached certifi-2024.8.30-py3-none-any.whl.metadata (2.2 kB)
Collecting magic-filter<1.1,>=1.0.12 (from aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for magic-filter<1.1,>=1.0.12 from https://files.pythonhosted.org/pa
ckages/cc/75/f620449f0056eff0ec7c1b1e088f71068eb4e47a46eb54f6c065c6ad7675/magic_filter-1.0.12-py3-none-any.whl.metadata
  Downloading magic_filter-1.0.12-py3-none-any.whl.metadata (1.5 kB)
Collecting pydantic<2.10,>=2.4.1 (from aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for pydantic<2.10,>=2.4.1 from https://files.pythonhosted.org/packag
es/df/e4/ba44652d562cbf0bf320e0f3810206149c8a4e99cdbf66da82e97ab53a15/pydantic-2.9.2-py3-none-any.whl.metadata
  Using cached pydantic-2.9.2-py3-none-any.whl.metadata (149 kB)
Collecting typing-extensions<=5.0,>=4.7.0 (from aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for typing-extensions<=5.0,>=4.7.0 from https://files.pythonhosted.o
rg/packages/26/9f/ad63fc0248c5379346306f8668cda6e2e2e9c95e01216d2b8ffd9ff037d0/typing_extensions-4.12.2-py3-none-any.whl.metadata
  Using cached typing_extensions-4.12.2-py3-none-any.whl.metadata (3.0 kB)
Collecting aiohappyeyeballs>=2.3.0 (from aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for aiohappyeyeballs>=2.3.0 from https://files.pythonhosted.org/pack
ages/b9/74/fbb6559de3607b3300b9be3cc64e97548d55678e44623db17820dbd20002/aiohappyeyeballs-2.4.4-py3-none-any.whl.metadata
  Downloading aiohappyeyeballs-2.4.4-py3-none-any.whl.metadata (6.1 kB)
Collecting aiosignal>=1.1.2 (from aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for aiosignal>=1.1.2 from https://files.pythonhosted.org/packages/76
/ac/a7305707cb852b7e16ff80eaf5692309bde30e2b1100a1fcacdc8f731d97/aiosignal-1.3.1-py3-none-any.whl.metadata
  Downloading aiosignal-1.3.1-py3-none-any.whl.metadata (4.0 kB)
Collecting attrs>=17.3.0 (from aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for attrs>=17.3.0 from https://files.pythonhosted.org/packages/6a/21/5b6702a7f963e95456c0de2d495f67bf5fd62840ac655dc451586d23d39a/attrs-24.2.0-py3-none-any.whl.metadata   
  Using cached attrs-24.2.0-py3-none-any.whl.metadata (11 kB)
Collecting frozenlist>=1.1.1 (from aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for frozenlist>=1.1.1 from https://files.pythonhosted.org/packages/1
7/c4/b7db1206a3fea44bf3b838ca61deb6f74424a8a5db1dd53ecb21da669be6/frozenlist-1.5.0-cp313-cp313-win_amd64.whl.metadata
  Downloading frozenlist-1.5.0-cp313-cp313-win_amd64.whl.metadata (14 kB)
Collecting multidict<7.0,>=4.5 (from aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for multidict<7.0,>=4.5 from https://files.pythonhosted.org/packages
/7e/a5/17ee3a4db1e310b7405f5d25834460073a8ccd86198ce044dfaf69eac073/multidict-6.1.0-cp313-cp313-win_amd64.whl.metadata
  Downloading multidict-6.1.0-cp313-cp313-win_amd64.whl.metadata (5.1 kB)
Collecting yarl<2.0,>=1.12.0 (from aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for yarl<2.0,>=1.12.0 from https://files.pythonhosted.org/packages/f
5/d5/688db678e987c3e0fb17867970700b92603cadf36c56e5fb08f23e822a0c/yarl-1.18.3-cp313-cp313-win_amd64.whl.metadata
  Downloading yarl-1.18.3-cp313-cp313-win_amd64.whl.metadata (71 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 71.4/71.4 kB 168.2 kB/s eta 0:00:00
Collecting annotated-types>=0.6.0 (from pydantic<2.10,>=2.4.1->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for annotated-types>=0.6.0 from https://files.pythonhosted.org/packa
ges/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl.metadata
  Using cached annotated_types-0.7.0-py3-none-any.whl.metadata (15 kB)
Collecting pydantic-core==2.23.4 (from pydantic<2.10,>=2.4.1->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for pydantic-core==2.23.4 from https://files.pythonhosted.org/packag
es/a5/ae/e14b0ff8b3f48e02394d8acd911376b7b66e164535687ef7dc24ea03072f/pydantic_core-2.23.4-cp313-none-win_amd64.whl.metadata
  Downloading pydantic_core-2.23.4-cp313-none-win_amd64.whl.metadata (6.7 kB)
Collecting idna>=2.0 (from yarl<2.0,>=1.12.0->aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for idna>=2.0 from https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl.metadata
  Using cached idna-3.10-py3-none-any.whl.metadata (10 kB)
Collecting propcache>=0.2.0 (from yarl<2.0,>=1.12.0->aiohttp<3.11,>=3.9.0->aiogram->-r requirements.txt (line 2))
  Obtaining dependency information for propcache>=0.2.0 from https://files.pythonhosted.org/packages/f4
/33/d6f5420252a36034bc8a3a01171bc55b4bff5df50d1c63d9caa50693662f/propcache-0.2.1-cp313-cp313-win_amd64.whl.metadata
  Downloading propcache-0.2.1-cp313-cp313-win_amd64.whl.metadata (9.5 kB)
Downloading asyncpg-0.30.0-cp313-cp313-win_amd64.whl (621 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 621.6/621.6 kB 2.2 MB/s eta 0:00:00
Downloading aiogram-3.15.0-py3-none-any.whl (603 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 603.9/603.9 kB 2.5 MB/s eta 0:00:00
Downloading python_decouple-3.8-py3-none-any.whl (9.9 kB)
Downloading aiofiles-24.1.0-py3-none-any.whl (15 kB)
Downloading aiohttp-3.10.11-cp313-cp313-win_amd64.whl (378 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 378.1/378.1 kB 2.5 MB/s eta 0:00:00
Using cached certifi-2024.8.30-py3-none-any.whl (167 kB)
Downloading magic_filter-1.0.12-py3-none-any.whl (11 kB)
Using cached pydantic-2.9.2-py3-none-any.whl (434 kB)
Downloading pydantic_core-2.23.4-cp313-none-win_amd64.whl (1.9 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.9/1.9 MB 2.6 MB/s eta 0:00:00
Using cached typing_extensions-4.12.2-py3-none-any.whl (37 kB)
Downloading aiohappyeyeballs-2.4.4-py3-none-any.whl (14 kB)
Downloading aiosignal-1.3.1-py3-none-any.whl (7.6 kB)
Using cached annotated_types-0.7.0-py3-none-any.whl (13 kB)
Using cached attrs-24.2.0-py3-none-any.whl (63 kB)
Downloading frozenlist-1.5.0-cp313-cp313-win_amd64.whl (51 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 51.2/51.2 kB 3.0 MB/s eta 0:00:00
Downloading multidict-6.1.0-cp313-cp313-win_amd64.whl (28 kB)
Downloading yarl-1.18.3-cp313-cp313-win_amd64.whl (315 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 315.7/315.7 kB 3.0 MB/s eta 0:00:00
Using cached idna-3.10-py3-none-any.whl (70 kB)
Downloading propcache-0.2.1-cp313-cp313-win_amd64.whl (43 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 43.4/43.4 kB 2.8 MB/s eta 0:00:00
Installing collected packages: python-decouple, typing-extensions, propcache, multidict, magic-filter, 
idna, frozenlist, certifi, attrs, asyncpg, annotated-types, aiohappyeyeballs, aiofiles, yarl, pydantic-core, aiosignal, pydantic, aiohttp, aiogram
Successfully installed aiofiles-24.1.0 aiogram-3.15.0 aiohappyeyeballs-2.4.4 aiohttp-3.10.11 aiosignal-
gic-filter-1.0.12 multidict-6.1.0 propcache-0.2.1 pydantic-2.9.2 pydantic-core-2.23.4 python-decouple-3.8 typing-extensions-4.12.2 yarl-1.18.3

[notice] A new release of pip is available: 23.2.1 -> 24.3.1
[notice] To update, run: python.exe -m pip install --upgrade pip
(.venv) PS F:\code_last\bots\aiogram_3_bot> python.exe -m pip install --upgrade pip
Requirement already satisfied: pip in f:\code_last\bots\aiogram_3_bot\.venv\lib\site-packages (23.2.1)
Collecting pip
  Obtaining dependency information for pip from https://files.pythonhosted.org/packages/ef/7d/500c9ad20238fcfcb4cb9243eede163594d7020ce87bd9610c9e02771876/pip-24.3.1-py3-none-any.whl.metadata
  Downloading pip-24.3.1-py3-none-any.whl.metadata (3.7 kB)
Using cached pip-24.3.1-py3-none-any.whl (1.8 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 23.2.1
    Uninstalling pip-23.2.1:
      Successfully uninstalled pip-23.2.1
Successfully installed pip-24.3.1
(.venv) PS F:\code_last\bots\aiogram_3_bot>

До запуска скрипта бот не работает и не отвечает:

img.png

img_1.png

python
import asyncio
from aiogram import Bot, Dispatcher
from decouple import config

bot = Bot(token=config('TOKEN'))    # Объект бота
dp = Dispatcher()                   # Диспетчер

async def main():
    await dp.start_polling(bot)

asyncio.run(main())             # Запуск процесса

img_3.png

img_2.png

python
import asyncio
import logging
from aiogram import Bot, Dispatcher, types
from decouple import config

# Включаем логирование, чтобы не пропустить важные сообщения
logging.basicConfig(level=logging.INFO)
bot = Bot(token=config('TOKEN'))    # Объект бота
dp = Dispatcher()                   # Диспетчер

# Запуск процесса поллинга новых апдейтов
async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

img_4.png

img_5.png

Contacts: teffal@mail.ru