Files
Birthday-Pool-Bot/birthday_pool_bot/notifications/service.py
2026-01-15 09:47:43 +03:00

82 lines
3.1 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.
from datetime import date, timedelta
import facet
from aiogram import Bot
from aiogram.enums import ParseMode
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from .settings import NotificationsSettings
class NotificationsService(facet.AsyncioServiceMixin):
def __init__(
self,
settings: NotificationsSettings,
repositories_container: RepositoriesContainer,
):
self._settings = settings
self._repositories_container = repositories_container
self._bot = Bot(token=self._settings.telegram_bot_token)
async def start(self):
scheduler = AsyncIOScheduler()
scheduler.add_job(
func=self.send_notifications,
name="send_notifications",
trigger=CronTrigger.from_crontab(self._settings.cron),
)
scheduler.start()
async def send_notifications(self):
birthday = date.today() + timedelta(days=2)
users_repository = self._repositories_container.users
subscriptions_repository = self._repositories_container.subscriptions
async with users_repository.transaction():
users = await users_repository.get_users_by_birthdays(
birthday=birthday,
)
if not users:
return
async with subscriptions_repository.transaction():
subscriptions = await subscriptions_repository.get_to_users_subscriptions(
to_users_ids={user.id for user in users},
with_from_user=True,
with_to_user=True,
with_pool=True,
)
if not subscriptions:
return
for subscription in subscriptions:
if subscription.from_user.telegram_id is None:
continue
text = (
f"У {subscription.name} скоро день рождения: *{birthday.strftime('%d %B')}*\n\n"
)
if subscription.pool is not None:
if subscription.pool.owner_id == subscription.from_user.id:
text += "Вы собираете деньги на подарок\n\n"
else:
text += (
"Вы подписаны на сбор денег для подарка, вы можете отправить их сюда:\n"
f"_Телефон_: {subscription.pool.payment_data.phone}\n"
f"анк_: {subscription.pool.payment_data.bank.value}\n\n"
)
elif subscription.to_user.gift_payment_data is not None:
text += (
f"Вы можете отправить именнинику свой подарок сюда:\n"
f"_Телефон_: {subscription.to_user.gift_payment_data.phone}\n"
f"анк_: {subscription.to_user.gift_payment_data.bank.value}\n\n"
)
await self._bot.send_message(
text=text,
parse_mode=ParseMode.MARKDOWN,
chat_id=subscription.from_user.telegram_id,
)