Files
Touchh/bot/operations/notifications.py
2024-12-07 17:41:27 +09:00

74 lines
3.7 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 telegram import Bot
from django.core.mail import send_mail
from datetime import datetime
from asgiref.sync import sync_to_async
from users.models import User, NotificationSettings
async def send_telegram_notification(user, message):
"""Отправка уведомления через Telegram."""
if user.chat_id:
try:
bot = Bot(token="ВАШ_ТОКЕН")
await bot.send_message(chat_id=user.chat_id, text=message)
print(f"Telegram-уведомление отправлено пользователю {user.chat_id}: {message}")
except Exception as e:
print(f"Ошибка отправки Telegram-уведомления пользователю {user.chat_id}: {e}")
def send_email_notification(user, message):
"""Отправка уведомления через Email."""
if user.email:
try:
send_mail(
subject="Уведомление от системы",
message=message,
from_email="noreply@yourdomain.com",
recipient_list=[user.email],
fail_silently=False,
)
print(f"Email-уведомление отправлено на {user.email}: {message}")
except Exception as e:
print(f"Ошибка отправки Email-уведомления пользователю {user.email}: {e}")
async def schedule_notifications():
"""Планировщик уведомлений."""
print("Запуск планировщика уведомлений...")
now = datetime.now().strftime("%H:%M")
# Получение всех пользователей
users = await sync_to_async(list)(User.objects.all())
for user in users:
# Получение настроек уведомлений для каждого пользователя
settings, _ = await sync_to_async(NotificationSettings.objects.get_or_create)(user=user)
# Проверка времени уведомления
if settings.notification_time == now:
message = "Это ваше уведомление от системы."
if settings.telegram_enabled:
await send_telegram_notification(user, message)
if settings.email_enabled:
send_email_notification(user, message)
async def handle_notification_time(update, context):
"""Обработка ввода времени уведомлений."""
if context.user_data.get("set_time"):
user_id = update.message.from_user.id
new_time = update.message.text
try:
# Проверяем правильность формата времени
hour, minute = map(int, new_time.split(":"))
user = await sync_to_async(User.objects.filter(chat_id=user_id).first)()
if user:
# Обновляем настройки уведомлений
settings, _ = await sync_to_async(NotificationSettings.objects.get_or_create)(user=user)
settings.notification_time = f"{hour:02}:{minute:02}"
await sync_to_async(settings.save)()
print(f"Пользователь {user_id} установил новое время уведомлений: {new_time}")
await update.message.reply_text(f"Время уведомлений обновлено на {new_time}.")
except ValueError:
print(f"Пользователь {user_id} ввёл некорректное время: {new_time}")
await update.message.reply_text("Неверный формат. Введите время в формате HH:MM.")
finally:
context.user_data["set_time"] = False