Files
Channel-Notifier/main.py
T

126 lines
3.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# - *- coding: utf- 8 - *-
import asyncio
import sys
import colorama
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
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
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()
# Запуск задач по расписанию
async def scheduler_start(bot: Bot) -> None:
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,
)
# Проверяем очередь напоминаний каждые 30 минут
from tgbot.routers.channel_requests import send_reminders
BOT_SCHEDULER.add_job(
send_reminders,
trigger="interval",
minutes=30,
args=(bot,),
id="send_reminders",
replace_existing=True,
coalesce=True,
misfire_grace_time=120,
)
if not BOT_SCHEDULER.running:
BOT_SCHEDULER.start()
# Запуск бота и базовой обвязки
async def main():
validate_bot_config()
await prepare_database()
dp = Dispatcher()
arSession = AsyncRequestSession()
bot = Bot(
token=BOT_TOKEN,
default=DefaultBotProperties(
parse_mode=ParseMode.HTML, link_preview_is_disabled=True
),
)
register_all_middlewares(dp)
register_all_routers(dp)
try:
await set_commands(bot)
await startup_notify(bot)
await scheduler_start(bot)
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("***** УКАЖИТЕ BOT_ADMIN_IDS В .env *****")
await bot.delete_webhook()
await bot.get_updates(offset=-1)
await dp.start_polling(
bot,
arSession=arSession,
allowed_updates=dp.resolve_used_update_types(),
)
finally:
if BOT_SCHEDULER.running:
BOT_SCHEDULER.shutdown(wait=False)
await arSession.close()
await bot.session.close()
await close_database()
if __name__ == "__main__":
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
bot_logger.warning("Бот остановлен")