TwitchDownloader/modules/notifications.py

68 lines
2.2 KiB
Python

"""
Email notification functionality for Twitch Archive.
"""
import os
import socket
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from colorama import Fore, Style
class NotificationManager:
"""Handles email notifications via Gmail SMTP."""
def __init__(self, enabled: bool = False, username: str = ""):
"""
Initialize the notification manager.
Args:
enabled: Whether notifications are enabled
username: Streamer username for notification subject
"""
self.enabled = enabled
self.username = username
def send(self, subject: str, content: str) -> None:
"""
Send email notification via Gmail SMTP.
Only sends if notifications are enabled in configuration.
Requires SENDER, RECEIVER, and PASSWD in .env file.
Args:
subject: Email subject line
content: Email body content
"""
if not self.enabled:
return
try:
sender = os.getenv("SENDER")
receiver = os.getenv("RECEIVER")
password = os.getenv("PASSWD")
if not all([sender, receiver, password]):
print(f'{Fore.YELLOW}⚠ Notification skipped: Missing email credentials in .env{Style.RESET_ALL}')
return
# Construct email
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = f"{self.username} - {subject}"
body = f"Stream: {self.username}\n\n{content}"
msg.attach(MIMEText(body, 'plain'))
# Send via Gmail SMTP
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(sender, password)
server.sendmail(sender, receiver, msg.as_string())
except socket.error as e:
print(f'{Fore.YELLOW}⚠ Notification failed: {str(e)}{Style.RESET_ALL}')
except Exception as e:
print(f'{Fore.YELLOW}⚠ Notification error: {str(e)}{Style.RESET_ALL}')