Template
mirror of
https://github.com/djimboy/djimbo_template_aio3.git
synced 2026-08-25 06:27:43 +00:00
Update aiogram 3 template
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
import colorama
|
||||
@@ -8,28 +7,52 @@ from aiogram import Bot, Dispatcher
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
from aiogram.enums import ParseMode
|
||||
|
||||
from tgbot.data.config import BOT_TOKEN, BOT_SCHEDULER, get_admins
|
||||
from tgbot.database.adb_helper import database_initialization
|
||||
from tgbot.middlewares import register_all_middlwares
|
||||
from tgbot.data.config import BOT_DATABASE_EXPORT, BOT_TOKEN, BOT_SCHEDULER, get_admins, validate_bot_config
|
||||
from tgbot.database.core import close_database
|
||||
from tgbot.database.repository import prepare_database
|
||||
from tgbot.middlewares import register_all_middlewares
|
||||
from tgbot.routers import register_all_routers
|
||||
from tgbot.services.api_session import AsyncRequestSession
|
||||
from tgbot.utils.misc.bot_commands import set_commands
|
||||
from tgbot.utils.misc.bot_logging import bot_logger
|
||||
from tgbot.utils.misc_functions import autobackup_admin, startup_notify
|
||||
|
||||
# Включаем мгновенный вывод print() без flush=True в каждом вызове
|
||||
def configure_console_output() -> None:
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(stream, "reconfigure"):
|
||||
stream.reconfigure(line_buffering=True, write_through=True)
|
||||
|
||||
|
||||
configure_console_output()
|
||||
colorama.init()
|
||||
|
||||
|
||||
# Start schedulers
|
||||
# Запуск задач по расписанию
|
||||
async def scheduler_start(bot):
|
||||
BOT_SCHEDULER.add_job(autobackup_admin, trigger="cron", hour=00, args=(bot,)) # Ежедневный Автобэкап в 00:00
|
||||
if BOT_DATABASE_EXPORT:
|
||||
BOT_SCHEDULER.add_job(
|
||||
autobackup_admin,
|
||||
trigger="cron",
|
||||
hour=0,
|
||||
args=(bot,),
|
||||
id="autobackup_admin",
|
||||
replace_existing=True,
|
||||
coalesce=True,
|
||||
misfire_grace_time=60,
|
||||
)
|
||||
|
||||
if not BOT_SCHEDULER.running:
|
||||
BOT_SCHEDULER.start()
|
||||
|
||||
|
||||
# Start bot and basic functions
|
||||
# Запуск бота и базовой обвязки
|
||||
async def main():
|
||||
BOT_SCHEDULER.start() # Start scheduler
|
||||
dp = Dispatcher() # Dispatcher image
|
||||
arSession = AsyncRequestSession() # Async session pool (aiohttp)
|
||||
validate_bot_config()
|
||||
await prepare_database() # Проверка готовности БД
|
||||
|
||||
dp = Dispatcher() # Диспетчер событий
|
||||
arSession = AsyncRequestSession() # Общая сессия aiohttp
|
||||
|
||||
bot = Bot( # Образ Бота
|
||||
token=BOT_TOKEN,
|
||||
@@ -38,44 +61,43 @@ async def main():
|
||||
),
|
||||
)
|
||||
|
||||
register_all_middlwares(dp) # Register all middlewares
|
||||
register_all_routers(dp) # Register all routers
|
||||
register_all_middlewares(dp) # Подключение мидлварей
|
||||
register_all_routers(dp) # Подключение роутера
|
||||
|
||||
try:
|
||||
await set_commands(bot) # Set commands for users
|
||||
await startup_notify(bot) # Notification that bot was started
|
||||
await scheduler_start(bot) # Connect schedulers
|
||||
await set_commands(bot) # Обновление команды в Telegram
|
||||
await startup_notify(bot) # Сообщаем админам о старте
|
||||
await scheduler_start(bot) # Подключение задач по расписанию
|
||||
|
||||
bot_logger.warning("BOT WAS STARTED")
|
||||
print(colorama.Fore.LIGHTYELLOW_EX + f"~~~~~ Bot was started - @{(await bot.get_me()).username} ~~~~~")
|
||||
bot_info = await bot.get_me()
|
||||
bot_logger.info("Бот запущен: @%s", bot_info.username)
|
||||
print(colorama.Fore.LIGHTYELLOW_EX + f"~~~~~ Бот запущен - @{bot_info.username} ~~~~~")
|
||||
print(colorama.Fore.LIGHTBLUE_EX + "~~~~~ TG developer - @djimbox ~~~~~")
|
||||
print(colorama.Fore.RESET)
|
||||
|
||||
if len(get_admins()) == 0: print("***** ENTER ADMIN ID IN settings.ini *****")
|
||||
if len(get_admins()) == 0:
|
||||
print("***** УКАЖИТЕ BOT_ADMIN_IDS В .env *****")
|
||||
|
||||
await bot.delete_webhook() # Deletes webhooks, if they was have
|
||||
await bot.get_updates(offset=-1) # Reset update pengings
|
||||
await bot.delete_webhook() # Сбрасывание вебхука, если он был
|
||||
await bot.get_updates(offset=-1) # Чистка старых апдейтов
|
||||
|
||||
# Run bot (polling method)
|
||||
# Запуск бота (polling режим)
|
||||
await dp.start_polling(
|
||||
bot,
|
||||
arSession=arSession,
|
||||
allowed_updates=dp.resolve_used_update_types(),
|
||||
)
|
||||
finally:
|
||||
await arSession.close() # Close async session (aiohttp)
|
||||
await bot.session.close() # Close bot session
|
||||
if BOT_SCHEDULER.running:
|
||||
BOT_SCHEDULER.shutdown(wait=False)
|
||||
|
||||
await arSession.close() # Закрытие сессии aiohttp
|
||||
await bot.session.close() # Закрытие сессии API Telegram
|
||||
await close_database() # Закрытие соединений с БД
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
database_initialization() # Initializate Database, tables and columns
|
||||
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
bot_logger.warning("Bot was stopped")
|
||||
finally:
|
||||
if sys.platform.startswith("win"):
|
||||
os.system("cls")
|
||||
else:
|
||||
os.system("clear")
|
||||
bot_logger.warning("Бот остановлен")
|
||||
|
||||
Reference in New Issue
Block a user