Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -38,7 +38,8 @@ logger = logging.getLogger(__name__)
|
|
| 38 |
|
| 39 |
# Email settings
|
| 40 |
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS", "")
|
| 41 |
-
|
|
|
|
| 42 |
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD", "")
|
| 43 |
BREVO_API_KEY = os.getenv("BREVO_API_KEY", "")
|
| 44 |
|
|
@@ -67,21 +68,28 @@ SESSION_EXPIRED = False
|
|
| 67 |
# STATE MANAGEMENT (Task 1)
|
| 68 |
# ==============================================================================
|
| 69 |
def load_state():
|
| 70 |
-
global LAST_EVENT_ID
|
| 71 |
if os.path.exists(STATE_FILE):
|
| 72 |
try:
|
| 73 |
with open(STATE_FILE, "r") as f:
|
| 74 |
content = f.read().strip()
|
| 75 |
if content:
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
logger.info(f"Loaded LAST_EVENT_ID from state: {LAST_EVENT_ID}")
|
| 78 |
except Exception as e:
|
| 79 |
logger.error(f"Failed to read state file: {e}")
|
| 80 |
|
| 81 |
-
def save_state(event_id):
|
| 82 |
try:
|
| 83 |
with open(STATE_FILE, "w") as f:
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
| 85 |
except Exception as e:
|
| 86 |
logger.error(f"Failed to write state file: {e}")
|
| 87 |
|
|
@@ -92,7 +100,10 @@ import smtplib
|
|
| 92 |
from email.mime.text import MIMEText
|
| 93 |
from email.mime.multipart import MIMEMultipart
|
| 94 |
|
| 95 |
-
def send_email_message(subject: str, body: str, is_html=False):
|
|
|
|
|
|
|
|
|
|
| 96 |
# Cloud Safe Alternative (Brevo API)
|
| 97 |
if BREVO_API_KEY:
|
| 98 |
logger.debug("--> send_email_message called via Brevo API")
|
|
@@ -104,12 +115,13 @@ def send_email_message(subject: str, body: str, is_html=False):
|
|
| 104 |
"content-type": "application/json"
|
| 105 |
}
|
| 106 |
|
| 107 |
-
recipient_list = [{"email": e.strip()} for e in
|
| 108 |
|
| 109 |
payload = {
|
| 110 |
"sender": {"name": "BIP Auto Notifier", "email": EMAIL_ADDRESS},
|
| 111 |
-
"
|
| 112 |
-
"subject": subject
|
|
|
|
| 113 |
}
|
| 114 |
|
| 115 |
if is_html:
|
|
@@ -135,14 +147,14 @@ def send_email_message(subject: str, body: str, is_html=False):
|
|
| 135 |
|
| 136 |
# Local Fallback (SMTP)
|
| 137 |
logger.debug("--> send_email_message called via Standard SMTP")
|
| 138 |
-
if not EMAIL_ADDRESS or not EMAIL_PASSWORD or not
|
| 139 |
logger.warning(f"Email credentials not configured. The following alert '{subject}' would have been sent.")
|
| 140 |
return False
|
| 141 |
|
| 142 |
try:
|
| 143 |
msg = MIMEMultipart()
|
| 144 |
msg['From'] = EMAIL_ADDRESS
|
| 145 |
-
msg['
|
| 146 |
msg['Subject'] = subject
|
| 147 |
|
| 148 |
if is_html:
|
|
@@ -150,7 +162,7 @@ def send_email_message(subject: str, body: str, is_html=False):
|
|
| 150 |
else:
|
| 151 |
msg.attach(MIMEText(body, 'plain'))
|
| 152 |
|
| 153 |
-
recipient_list = [e.strip() for e in
|
| 154 |
|
| 155 |
server = smtplib.SMTP('smtp.gmail.com', 587)
|
| 156 |
server.starttls()
|
|
@@ -193,7 +205,7 @@ def send_event_alerts(events):
|
|
| 193 |
f"<a href='{ev.get('web_url', '#')}'>View Event Here</a><br>"
|
| 194 |
f"<hr>"
|
| 195 |
)
|
| 196 |
-
send_email_message("π’ New BIP Event(s) Found!", msg, is_html=True)
|
| 197 |
|
| 198 |
|
| 199 |
# ==============================================================================
|
|
@@ -335,7 +347,7 @@ def process_tick():
|
|
| 335 |
if LAST_EVENT_ID is None:
|
| 336 |
LAST_EVENT_ID = new_events[0]["id"]
|
| 337 |
LAST_EVENT_CODE = new_events[0].get('event_code', LAST_EVENT_ID)
|
| 338 |
-
save_state(LAST_EVENT_ID)
|
| 339 |
logger.info(f"EVENT ID : {LAST_EVENT_CODE} (Tracking started)")
|
| 340 |
|
| 341 |
# Send the startup notification
|
|
@@ -350,13 +362,14 @@ def process_tick():
|
|
| 350 |
send_event_alerts(new_events)
|
| 351 |
LAST_EVENT_ID = new_events[0]["id"]
|
| 352 |
LAST_EVENT_CODE = new_events[0].get('event_code', LAST_EVENT_ID)
|
| 353 |
-
save_state(LAST_EVENT_ID)
|
| 354 |
|
| 355 |
for ev in new_events:
|
| 356 |
code = ev.get('event_code', ev['id'])
|
| 357 |
logger.info(f"π¨ NEW EVENT ID : {code} (Alert Sent!)")
|
| 358 |
else:
|
| 359 |
-
|
|
|
|
| 360 |
|
| 361 |
except Exception as e:
|
| 362 |
logger.error(f"CRITICAL EXCEPTION in process_tick: {e}")
|
|
@@ -428,12 +441,16 @@ def get_latest_event():
|
|
| 428 |
|
| 429 |
def test_email_alert():
|
| 430 |
"""Sends a dummy test message to the configured Email."""
|
| 431 |
-
logger.info("Sending test exact alert to Email...")
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
else:
|
| 436 |
-
logger.error("β Failed to send test
|
| 437 |
|
| 438 |
def test_real_event_alert():
|
| 439 |
"""Fetches the actual latest event from BIP and sends it as a test alert."""
|
|
|
|
| 38 |
|
| 39 |
# Email settings
|
| 40 |
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS", "")
|
| 41 |
+
EVENT_EMAIL_RECIPIENT = os.getenv("EVENT_EMAIL_RECIPIENT", os.getenv("EMAIL_RECIPIENT", EMAIL_ADDRESS))
|
| 42 |
+
WARNING_EMAIL_RECIPIENT = os.getenv("WARNING_EMAIL_RECIPIENT", os.getenv("EMAIL_RECIPIENT", EMAIL_ADDRESS))
|
| 43 |
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD", "")
|
| 44 |
BREVO_API_KEY = os.getenv("BREVO_API_KEY", "")
|
| 45 |
|
|
|
|
| 68 |
# STATE MANAGEMENT (Task 1)
|
| 69 |
# ==============================================================================
|
| 70 |
def load_state():
|
| 71 |
+
global LAST_EVENT_ID, LAST_EVENT_CODE
|
| 72 |
if os.path.exists(STATE_FILE):
|
| 73 |
try:
|
| 74 |
with open(STATE_FILE, "r") as f:
|
| 75 |
content = f.read().strip()
|
| 76 |
if content:
|
| 77 |
+
# In case the file has multiple lines (id and code)
|
| 78 |
+
parts = content.split(",")
|
| 79 |
+
LAST_EVENT_ID = int(parts[0])
|
| 80 |
+
if len(parts) > 1:
|
| 81 |
+
LAST_EVENT_CODE = parts[1]
|
| 82 |
logger.info(f"Loaded LAST_EVENT_ID from state: {LAST_EVENT_ID}")
|
| 83 |
except Exception as e:
|
| 84 |
logger.error(f"Failed to read state file: {e}")
|
| 85 |
|
| 86 |
+
def save_state(event_id, event_code=None):
|
| 87 |
try:
|
| 88 |
with open(STATE_FILE, "w") as f:
|
| 89 |
+
if event_code:
|
| 90 |
+
f.write(f"{event_id},{event_code}")
|
| 91 |
+
else:
|
| 92 |
+
f.write(str(event_id))
|
| 93 |
except Exception as e:
|
| 94 |
logger.error(f"Failed to write state file: {e}")
|
| 95 |
|
|
|
|
| 100 |
from email.mime.text import MIMEText
|
| 101 |
from email.mime.multipart import MIMEMultipart
|
| 102 |
|
| 103 |
+
def send_email_message(subject: str, body: str, is_html=False, recipient=None):
|
| 104 |
+
if recipient is None:
|
| 105 |
+
recipient = WARNING_EMAIL_RECIPIENT
|
| 106 |
+
|
| 107 |
# Cloud Safe Alternative (Brevo API)
|
| 108 |
if BREVO_API_KEY:
|
| 109 |
logger.debug("--> send_email_message called via Brevo API")
|
|
|
|
| 115 |
"content-type": "application/json"
|
| 116 |
}
|
| 117 |
|
| 118 |
+
recipient_list = [{"email": e.strip()} for e in recipient.split(",") if e.strip()]
|
| 119 |
|
| 120 |
payload = {
|
| 121 |
"sender": {"name": "BIP Auto Notifier", "email": EMAIL_ADDRESS},
|
| 122 |
+
"bcc": recipient_list,
|
| 123 |
+
"subject": subject,
|
| 124 |
+
"replyTo": {"name": "BIP Auto Notifier", "email": "noreply@bip.notifier"}
|
| 125 |
}
|
| 126 |
|
| 127 |
if is_html:
|
|
|
|
| 147 |
|
| 148 |
# Local Fallback (SMTP)
|
| 149 |
logger.debug("--> send_email_message called via Standard SMTP")
|
| 150 |
+
if not EMAIL_ADDRESS or not EMAIL_PASSWORD or not recipient:
|
| 151 |
logger.warning(f"Email credentials not configured. The following alert '{subject}' would have been sent.")
|
| 152 |
return False
|
| 153 |
|
| 154 |
try:
|
| 155 |
msg = MIMEMultipart()
|
| 156 |
msg['From'] = EMAIL_ADDRESS
|
| 157 |
+
msg['Bcc'] = recipient
|
| 158 |
msg['Subject'] = subject
|
| 159 |
|
| 160 |
if is_html:
|
|
|
|
| 162 |
else:
|
| 163 |
msg.attach(MIMEText(body, 'plain'))
|
| 164 |
|
| 165 |
+
recipient_list = [e.strip() for e in recipient.split(",") if e.strip()]
|
| 166 |
|
| 167 |
server = smtplib.SMTP('smtp.gmail.com', 587)
|
| 168 |
server.starttls()
|
|
|
|
| 205 |
f"<a href='{ev.get('web_url', '#')}'>View Event Here</a><br>"
|
| 206 |
f"<hr>"
|
| 207 |
)
|
| 208 |
+
send_email_message("π’ New BIP Event(s) Found!", msg, is_html=True, recipient=EVENT_EMAIL_RECIPIENT)
|
| 209 |
|
| 210 |
|
| 211 |
# ==============================================================================
|
|
|
|
| 347 |
if LAST_EVENT_ID is None:
|
| 348 |
LAST_EVENT_ID = new_events[0]["id"]
|
| 349 |
LAST_EVENT_CODE = new_events[0].get('event_code', LAST_EVENT_ID)
|
| 350 |
+
save_state(LAST_EVENT_ID, LAST_EVENT_CODE)
|
| 351 |
logger.info(f"EVENT ID : {LAST_EVENT_CODE} (Tracking started)")
|
| 352 |
|
| 353 |
# Send the startup notification
|
|
|
|
| 362 |
send_event_alerts(new_events)
|
| 363 |
LAST_EVENT_ID = new_events[0]["id"]
|
| 364 |
LAST_EVENT_CODE = new_events[0].get('event_code', LAST_EVENT_ID)
|
| 365 |
+
save_state(LAST_EVENT_ID, LAST_EVENT_CODE)
|
| 366 |
|
| 367 |
for ev in new_events:
|
| 368 |
code = ev.get('event_code', ev['id'])
|
| 369 |
logger.info(f"π¨ NEW EVENT ID : {code} (Alert Sent!)")
|
| 370 |
else:
|
| 371 |
+
display_code = LAST_EVENT_CODE if LAST_EVENT_CODE else LAST_EVENT_ID
|
| 372 |
+
logger.info(f"EVENT ID : {display_code}")
|
| 373 |
|
| 374 |
except Exception as e:
|
| 375 |
logger.error(f"CRITICAL EXCEPTION in process_tick: {e}")
|
|
|
|
| 441 |
|
| 442 |
def test_email_alert():
|
| 443 |
"""Sends a dummy test message to the configured Email."""
|
| 444 |
+
logger.info("Sending test exact alert to Event Email...")
|
| 445 |
+
success1 = send_email_message("π€ Test Alert - Event Receivers", "π€ <b>Test Alert from BIP CLI Notifier</b><br><br>Event emails are working perfectly!", is_html=True, recipient=EVENT_EMAIL_RECIPIENT)
|
| 446 |
+
|
| 447 |
+
logger.info("Sending test exact alert to Warning Email...")
|
| 448 |
+
success2 = send_email_message("π€ Test Alert - Warning Receivers", "π€ <b>Test Alert from BIP CLI Notifier</b><br><br>Warning emails are working perfectly!", is_html=True, recipient=WARNING_EMAIL_RECIPIENT)
|
| 449 |
+
|
| 450 |
+
if success1 and success2:
|
| 451 |
+
logger.info("β
Test messages sent successfully!")
|
| 452 |
else:
|
| 453 |
+
logger.error("β Failed to send one or more test messages. Check your .env configuration.")
|
| 454 |
|
| 455 |
def test_real_event_alert():
|
| 456 |
"""Fetches the actual latest event from BIP and sends it as a test alert."""
|