backend/links/views.py

39 lines
1.2 KiB
Python

from requests import post
from rest_framework import viewsets
from link_backend.settings import ENABLE_TELEGRAM_BOT, TELEGRAM_CHAT_ID, TELEGRAM_BOT_TOKEN
from links.serializers import LinkSerializer
from links.models import Link
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Link)
def new_link_notification(sender, instance, created, **kwargs):
if created:
if ENABLE_TELEGRAM_BOT:
print("test")
response = post(
url=f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
json={
"chat_id": TELEGRAM_CHAT_ID,
"text": f"""<b>🔗 Link created!</b>
📛 Link shorted name: <b>{instance.name}</b>
🖼️ Original URL: <b>{instance.url}</b>""",
"parse_mode": "HTML"
}
)
print(response.text)
class LinkViewSet(viewsets.ModelViewSet):
serializer_class = LinkSerializer
def get_queryset(self):
link_name = self.request.query_params.get("link")
if link_name:
return Link.objects.filter(name=link_name)
return []