-
-
Notifications
You must be signed in to change notification settings - Fork 135
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* 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
1 parent
c6b9cb1
commit 44d4ed6
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
) |