import random import string from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from django.conf import settings from django.apps import apps from django.utils import timezone from .models import Club, FailedApiCall, CustomUser, Log, DataAccess, ModelLog import requests def generate_unique_code(): characters = string.ascii_letters + string.digits while True: code = ''.join(random.sample(characters, 3)) if not Club.objects.filter(broadcast_code=code).exists(): return code @receiver(post_save, sender=Club) def assign_unique_code(sender, instance, created, **kwargs): if created and not instance.broadcast_code: instance.broadcast_code = generate_unique_code() instance.save() DISCORD_FAILED_CALLS_WEBHOOK_URL = 'https://discord.com/api/webhooks/1248191778134163486/sSoTL6cULCElWr2YFwyllsg7IXxHcCx_YMDJA_cUHtVUU4WOfN-5M7drCJuwNBBfAk9a' DISCORD_LOGS_WEBHOOK_URL = 'https://discord.com/api/webhooks/1257987637449588736/TtOUwzYgSlQH2d3Ps7SfIKRcFALQVa3hfkC-j9K4_UAcWtsfiw4v8NUPbnX2_ZPOYzuv' @receiver(post_save, sender=FailedApiCall) def notify_discord_on_create(sender, instance, created, **kwargs): notify_object_creation_on_discord(created, instance, DISCORD_FAILED_CALLS_WEBHOOK_URL) # @receiver(post_save, sender=CustomUser) # def notify_user_creation_on_discord(sender, instance, created, **kwargs): # notify_object_creation_on_discord(created, instance, DISCORD_LOGS_WEBHOOK_URL) @receiver(post_save, sender=Log) def notify_log_creation_on_discord(sender, instance, created, **kwargs): notify_object_creation_on_discord(created, instance, DISCORD_LOGS_WEBHOOK_URL) # WARNING: using this method requires the instance to have a discord_string method def notify_object_creation_on_discord(created, instance, webhook_url): if created: default_db_engine = settings.DATABASES['default']['ENGINE'] if default_db_engine != 'django.db.backends.sqlite3': message = f'New {instance.__class__.__name__} created: {instance.discord_string()}' send_discord_message(webhook_url, message) def send_discord_message(webhook_url, content): data = { "content": content } response = requests.post(webhook_url, json=data) if response.status_code != 204: raise ValueError( f'Error sending message to Discord webhook: {response.status_code}, {response.text}' ) @receiver(pre_delete, sender=DataAccess) def data_access_pre_delete(sender, instance, **kwargs): print('>>> delete data access signal') try: model_class = apps.get_model('tournaments', instance.model_name) obj = model_class.objects.get(id=instance.model_id) parent_model, parent_id = obj.get_parent_reference() store_id = None if hasattr(obj, 'store_id'): store_id = obj.store_id ModelLog.objects.create( user=instance.shared_with, model_id=instance.model_id, model_name=instance.model_name, operation='REVOKE_ACCESS', date=timezone.now(), store_id=store_id, parent_model_id=parent_id, parent_model_name=parent_model ) except Exception as e: print(f"Error in data_access_pre_delete signal: {e}")