all repos — webpage-monitor @ 999a6716a27e218779a8fb0cf3f5da063d7d112c

Monitor.py (view raw)

 1import requests
 2from time import ctime, sleep
 3import smtplib
 4
 5DEFAULT_INTERVAL = 30
 6DEFAULT_SMTP_URL = "smtp.gmail.com"
 7DEFAULT_SMTP_PORT = 587
 8DEFAULT_SUBJECT = "Webpage Content Changed"
 9DEFAULT_MESSAGE = """Subject: {s}
10
11The contents of the webpage have changed! {u}
12
13Previous content:
14{p}
15
16Current content:
17{c}"""
18
19def monitor(url: str, sender_email: str, sender_password: str,
20            recipient_email=None, interval=DEFAULT_INTERVAL,
21            subject=DEFAULT_SUBJECT, message=DEFAULT_MESSAGE,
22            smtp_url=DEFAULT_SMTP_URL, smtp_port=DEFAULT_SMTP_PORT):
23
24    if recipient_email is None:
25        recipient_email = sender_email
26
27    previous_content = None
28
29    def send_notification(previous_content, current_content):
30        msg = message.format(s=subject,
31                                 p=previous_content,
32                                 c=current_content,
33                                 u=url
34                                ).encode("utf-8")
35        try:
36            with smtplib.SMTP(smtp_url, smtp_port) as smtp:
37                smtp.ehlo()
38                smtp.starttls()
39                smtp.ehlo()
40                smtp.login(sender_email, sender_password)
41                smtp.sendmail(sender_email, recipient_email, msg)
42        except Exception as e:
43            print(f"Error sending email: {e}")
44
45    print(f"{ctime()}: started monitoring {url}.")
46    while True:
47        print(f"{ctime()}: downloading page.")
48        response = requests.get(url)
49        current_content = response.text
50        if previous_content and previous_content != current_content:
51            print(f"{ctime()}: change detected.")
52            send_notification(previous_content, current_content)
53        previous_content = current_content
54        sleep(interval * 60) # wait for `interval` minutes