Skip to content

Commit

Permalink
add management-command (#2775)
Browse files Browse the repository at this point in the history
* add management-command

* Fix formatting issues in check_keywords.py

* Update settings.py

* Update check_keywords.py

* precommit

* update

---------

Co-authored-by: DonnieBLT <[email protected]>
  • Loading branch information
sagnik3788 and DonnieBLT authored Oct 19, 2024
1 parent c6b9cb1 commit 44d4ed6
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions website/management/commands/check_keywords.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import requests
from bs4 import BeautifulSoup
from django.core.mail import send_mail
from django.core.management.base import BaseCommand
from django.utils import timezone

from website.models import Monitor


class Command(BaseCommand):
help = "Checks for keywords in monitored URLs"

def handle(self, *args, **options):
monitors = Monitor.objects.all()
for monitor in monitors:
try:
response = requests.get(monitor.url)
response.raise_for_status()

soup = BeautifulSoup(response.content, "html.parser")
page_content = soup.get_text()

if monitor.keyword in page_content:
new_status = "UP"
else:
new_status = "DOWN"

if monitor.status != new_status:
monitor.status = new_status
monitor.save()

user = monitor.user
self.notify_user(user.username, monitor.url, user.email, new_status)

monitor.last_checked_time = timezone.now()
monitor.save()

self.stdout.write(
self.style.SUCCESS(f"Monitoring {monitor.url}: status {monitor.status}")
)
except Exception as e:
self.stderr.write(self.style.ERROR(f"Error monitoring {monitor.url}: {str(e)}"))

def notify_user(self, username, website, email, status):
subject = f"Website Status Update: {website} is {status}"
message = (
f"Dear {username},\n\nThe website '{website}' you are monitoring is currently {status}."
)

send_mail(
subject,
message,
None,
[email],
fail_silently=False,
)

0 comments on commit 44d4ed6

Please sign in to comment.