Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Make sure python and pip are already installed on the computer/server
- # Make sure you've also run 'pip install requests beautifulsoup4 schedule' because they're needed for this script
- import requests
- from bs4 import BeautifulSoup
- import schedule
- import time
- import smtplib
- import sys
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
- SMTP_SERVER = "smtp.gmail.com"
- SMTP_PORT = 587
- SENDER_EMAIL = "[email protected]"
- # !! Not safe to secure a plaintext password in a script if AWS instance security group has inbound rule that is open to all of the internet
- SENDER_PASSWORD = "your app password"
- RECEIVER_EMAIL = "[email protected]"
- # archived in-stock version for testing
- # PRODUCT_URL = "https://web.archive.org/web/20240117232056/https://www.k9mask.com/products/k9-mask%C2%AE-for-dogs-with-3-extreme-breathe-n95-active-carbon-air-filters?variant=33008752623669"
- PRODUCT_URL = "https://www.k9mask.com/products/k9-mask%C2%AE-for-dogs-with-3-extreme-breathe-n95-active-carbon-air-filters"
- def send_email():
- subject = "Medium K9 masks in stock!"
- body = f"Masks are in stock\n\n{PRODUCT_URL}"
- msg = MIMEMultipart()
- msg["From"] = SENDER_EMAIL
- msg["To"] = RECEIVER_EMAIL
- msg["Subject"] = subject
- msg.attach(MIMEText(body, "plain"))
- try:
- with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
- server.starttls()
- server.login(SENDER_EMAIL, SENDER_PASSWORD)
- server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, msg.as_string())
- print("Email sent")
- except Exception as e:
- print(f"Error sending email: {e}")
- def check_stock():
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
- }
- try:
- response = requests.get(PRODUCT_URL, headers=headers)
- response.raise_for_status()
- soup = BeautifulSoup(response.text, 'html.parser')
- medium_option = soup.find("option", string=lambda text: "Medium" in text and "Sold Out" in text)
- if medium_option:
- return False
- else:
- return True
- except requests.exceptions.RequestException as e:
- print(f"Error checking stock: {e}")
- def email_if_in_stock():
- if check_stock():
- send_email()
- sys.exit(0)
- else:
- print("Sold out")
- schedule.every(1).minutes.do(email_if_in_stock)
- while True:
- schedule.run_pending()
- time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment