all repos — webpage-monitor @ 9b60a31aefb8db1efd18913f5ce818e663ce1242

first commit
Marco Andronaco andronacomarco@gmail.com
Mon, 30 Jan 2023 13:05:03 +0100
commit

9b60a31aefb8db1efd18913f5ce818e663ce1242

6 files changed, 72 insertions(+), 0 deletions(-)

jump to
A .env.example

@@ -0,0 +1,3 @@

+url="https://localhost:8000" +email="example@gmail.com" +password="abcdefghijklmnop"
A .gitignore

@@ -0,0 +1,2 @@

+__pycache__ +.env
A Monitor.py

@@ -0,0 +1,53 @@

+import requests +import time +import smtplib + +DEFAULT_INTERVAL = 5 +DEFAULT_SMTP_URL = "smtp.gmail.com" +DEFAULT_SMTP_PORT = 587 +DEFAULT_SUBJECT = "Webpage Content Changed" +DEFAULT_MESSAGE = """Subject: {s} + +The contents of the webpage have changed! {u} + +Previous content: +{p} + +Current content: +{c}""" + +def monitor(url: str, sender_email: str, sender_password: str, + recipient_email=None, interval=DEFAULT_INTERVAL, + subject=DEFAULT_SUBJECT, message=DEFAULT_MESSAGE, + smtp_url=DEFAULT_SMTP_URL, smtp_port=DEFAULT_SMTP_PORT): + + if recipient_email is None: + recipient_email = sender_email + + previous_content = None + + def send_notification(previous_content, current_content): + msg = message.format(s=subject, + p=previous_content, + c=current_content, + u=url + ).encode("utf-8") + try: + with smtplib.SMTP(smtp_url, smtp_port) as smtp: + smtp.ehlo() + smtp.starttls() + smtp.ehlo() + smtp.login(sender_email, sender_password) + smtp.sendmail(sender_email, recipient_email, msg) + except Exception as e: + print(f"Error sending email: {e}") + + print(f"{time.ctime()}: started monitoring {url}.") + while True: + response = requests.get(url) + current_content = response.text + if previous_content and previous_content != current_content: + print(f"{time.ctime()}: change detected.") + send_notification(previous_content, current_content) + previous_content = current_content + time.sleep(interval * 60) # wait for `interval` minutes
A README.md

@@ -0,0 +1,5 @@

+# Simple webpage checker in Python. + +While `main.py` is just an example of usage, the main function is in `Monitor.py` and it has zero requirements. + +`main.py`'s only requirement is `python-dotenv`, in order to load environment variables from a provided `.env` file.
A main.py

@@ -0,0 +1,8 @@

+import os +from Monitor import monitor +from dotenv import load_dotenv +load_dotenv() + +if __name__ == "__main__": + monitor(os.getenv("url"), os.getenv("email"), os.getenv("password"), interval=1) +
A requirements.txt

@@ -0,0 +1,1 @@

+python-dotenv