deepsite / management /tasks.py
coerxso's picture
Upload 73 files
3e8a166 verified
raw
history blame
7.52 kB
# management/tasks.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import requests
import json
import os
import datetime
from celery import shared_task
from django.db import connections, connection
from django.conf import settings
from django.utils import timezone
from .models import (
Panel,
AdminLevel2,
AdminLevel3,
EndUser,
Payment,
CustomUser,
Subscription,
)
from django.core.management import call_command
# --- Utilities ---
# FIXED: Renamed function to match imports in other files
@shared_task
def send_telegram_message(chat_id, message, bot_token):
"""
Sends a message to a specific Telegram chat using a bot token.
"""
if not bot_token:
print("Telegram bot token is not configured.")
return
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {
"chat_id": chat_id,
"text": message,
"parse_mode": "Markdown"
}
try:
response = requests.post(url, json=payload)
response.raise_for_status()
print(f"Notification sent successfully to chat_id {chat_id}")
except requests.RequestException as e:
print(f"Failed to send notification to chat_id {chat_id}: {e}")
# --- Celery Tasks ---
@shared_task(name="management.tasks.schedule_reminders")
def schedule_reminders():
"""
Celery task to send periodic reminders to admins and users.
"""
now = timezone.now().date()
# 1. License expiry warnings for AdminLevel2s (resellers)
three_days_from_now = now + datetime.timedelta(days=3)
admin_level2s = AdminLevel2.objects.filter(license_expiry_date__lte=three_days_from_now)
for admin in admin_level2s:
# Assuming AdminLevel2 is linked to a Panel through its CustomUser owner
# This part might need adjustment based on the final model structure
try:
panel = Panel.objects.get(owner=admin.user)
if admin.telegram_chat_id and panel.telegram_bot_token:
message = (
f"🚨 **هشدار انقضای لایسنس!**\n\n"
f"ادمین {admin.user.username}، لایسنس شما در تاریخ {admin.license_expiry_date} منقضی خواهد شد. لطفاً برای تمدید آن اقدام کنید."
)
send_telegram_message(
chat_id=admin.telegram_chat_id,
message=message,
bot_token=panel.telegram_bot_token
)
except Panel.DoesNotExist:
print(f"Panel for admin {admin.user.username} not found.")
@shared_task
def send_payment_receipt_to_admin(payment_id):
"""
Sends a payment receipt notification to the relevant admin via Telegram.
"""
try:
payment = Payment.objects.get(id=payment_id)
admin = payment.admin
panel = payment.subscription.panel
if not admin.admin_level_3.telegram_chat_id or not panel.telegram_bot_token:
print(f"Admin telegram_chat_id or bot token not found for payment {payment_id}.")
return
message = (
f"🔔 **رسید پرداخت جدید!**\n\n"
f"یک کاربر ({payment.subscription.end_user.username}) رسید پرداختی را برای تمدید اشتراک ارسال کرده است.\n"
f"مبلغ: {payment.amount} تومان\n"
f"توکن پرداخت: `{payment.payment_token}`\n"
f"لطفا به پنل خود مراجعه کرده و پرداخت را تایید کنید."
)
if payment.receipt_image:
message += f"\n\nتصویر رسید پرداخت آپلود شده است."
elif payment.receipt_text:
message += f"\n\nمتن رسید پرداخت: {payment.receipt_text}"
send_telegram_message(
chat_id=admin.admin_level_3.telegram_chat_id,
message=message,
bot_token=panel.telegram_bot_token
)
except Payment.DoesNotExist:
print(f"Payment with id {payment_id} not found.")
except Exception as e:
print(f"Error sending payment receipt to admin: {e}")
@shared_task
def send_payment_confirmation_to_user(end_user_id, amount, status):
"""
Sends a payment confirmation message to the end-user.
"""
try:
end_user = EndUser.objects.get(id=end_user_id)
panel = end_user.panel
if not panel or not panel.telegram_bot_token or not end_user.telegram_chat_id:
print(f"EndUser panel, bot token or telegram_chat_id not found for user {end_user_id}.")
return
if status == 'approved':
message = (
f"✅ **پرداخت شما تأیید شد**\n\n"
f"مبلغ {amount} تومان برای پنل {panel.name} با موفقیت تأیید شد. سرویس شما به زودی فعال خواهد شد."
)
else:
message = (
f"❌ **پرداخت شما رد شد**\n\n"
f"پرداخت {amount} تومان برای پنل {panel.name} رد شد. لطفاً رسید معتبر را ارسال کنید."
)
send_telegram_message(
chat_id=end_user.telegram_chat_id,
message=message,
bot_token=panel.telegram_bot_token
)
except EndUser.DoesNotExist:
print(f"EndUser with id {end_user_id} not found.")
except Exception as e:
print(f"Error sending payment confirmation to user: {e}")
@shared_task(name="management.tasks.check_subscription_expiry")
def check_subscription_expiry():
"""
Celery task to check subscription expiry and send notifications.
"""
now = timezone.now().date()
# Send reminder 3 days before expiry
three_days_from_now = now + datetime.timedelta(days=3)
expiring_soon_subscriptions = Subscription.objects.filter(
end_date__date=three_days_from_now,
status='active'
)
for sub in expiring_soon_subscriptions:
if sub.end_user.telegram_chat_id and sub.panel.telegram_bot_token:
message = (
f"⏳ **اشتراک شما به زودی منقضی می‌شود!**\n\n"
f"کاربر {sub.end_user.username}، اشتراک شما در تاریخ {sub.end_date.strftime('%Y-%m-%d')} منقضی خواهد شد. برای تمدید آن از طریق بات اقدام کنید."
)
send_telegram_message(
chat_id=sub.end_user.telegram_chat_id,
message=message,
bot_token=sub.panel.telegram_bot_token
)
# Deactivate expired subscriptions
expired_subscriptions = Subscription.objects.filter(end_date__lte=now, status='active')
for sub in expired_subscriptions:
sub.status = 'expired'
sub.save()
if sub.end_user.telegram_chat_id and sub.panel.telegram_bot_token:
message = (
f"❌ **اشتراک شما منقضی شد!**\n\n"
f"کاربر {sub.end_user.username}، اشتراک شما منقضی شده است. لطفا برای تمدید اقدام کنید."
)
send_telegram_message(
chat_id=sub.end_user.telegram_chat_id,
message=message,
bot_token=sub.panel.telegram_bot_token
)