-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalerter.py
More file actions
407 lines (344 loc) · 17.8 KB
/
alerter.py
File metadata and controls
407 lines (344 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# Copyright (c) 2026 Simon HGR — instockornot.club — ELv2 License
#!/usr/bin/env python3
"""
alerter.py
Drop Watcher — Resend Alert System
Sends immediate emails for critical/high alerts.
Sends daily digest for all alerts.
HGR
"""
import html as html_mod
import os
import json
import logging
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv
import httpx
from sms_alerter import send_sms_alert
# ── Load environment ──────────────────────────────────────────────────────────
import paths
load_dotenv(paths.ENV_FILE, override=True)
# ── Config ────────────────────────────────────────────────────────────────────
RESEND_API_KEY = os.environ.get('RESEND_API_KEY')
FROM_ADDRESS = 'Drop Watcher <alerts@instockornot.club>'
ALERT_TO = os.environ.get('ALERT_TO')
REPLY_TO = os.environ.get('ALERT_TO')
UNSUBSCRIBE_URL = 'https://instockornot.club'
DROPS_LOG = paths.DROPS_JSONL
SENT_LOG = paths.ALERTS_SENT_JSONL
IMMEDIATE_PRIORITIES = {'critical', 'high'}
RESEND_API_URL = 'https://api.resend.com/emails'
# ── Logging ───────────────────────────────────────────────────────────────────
log = logging.getLogger('alerter')
# ── Resend sender ─────────────────────────────────────────────────────────────
def send_email(subject, body_html, body_text, extra_recipients=None):
if not RESEND_API_KEY:
log.error("RESEND_API_KEY not configured in .env")
return False
payload = {
'from': FROM_ADDRESS,
'to': [ALERT_TO],
'bcc': extra_recipients if extra_recipients else None,
'subject': subject,
'html': body_html,
'text': body_text,
'reply_to': REPLY_TO,
'headers': {
'List-Unsubscribe': f'<{UNSUBSCRIBE_URL}>',
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
}
}
try:
response = httpx.post(
RESEND_API_URL,
headers={
'Authorization': f'Bearer {RESEND_API_KEY}',
'Content-Type': 'application/json',
},
json=payload,
timeout=15
)
response.raise_for_status()
data = response.json()
log.info(f"Email sent via Resend: {subject} — id: {data.get('id')}")
return True
except httpx.HTTPStatusError as e:
log.error(f"Resend API error {e.response.status_code}: {e.response.text}")
return False
except Exception as e:
log.error(f"Failed to send email: {e}")
return False
# ── Track sent alerts ─────────────────────────────────────────────────────────
def already_sent(alert_id):
if not os.path.exists(SENT_LOG):
return False
with open(SENT_LOG, 'r') as f:
for line in f:
try:
entry = json.loads(line)
if entry.get('alert_id') == alert_id:
return True
except:
continue
return False
def mark_sent(alert_id, alert_type):
with open(SENT_LOG, 'a') as f:
f.write(json.dumps({
'alert_id': alert_id,
'type': alert_type,
'sent_at': datetime.now(timezone.utc).isoformat()
}) + '\n')
def make_alert_id(alert):
return f"{alert.get('timestamp','')}_{alert.get('source','')}"
# ── Format immediate alert email ──────────────────────────────────────────────
def format_immediate_email(alert):
priority = alert.get('priority', 'high').upper()
source = alert.get('source', 'Unknown')
url = alert.get('url', '#')
ts = alert.get('timestamp', '')
notable_items = alert.get('notable_items', [])
matches = alert.get('matches', [])
drop = alert.get('drop_announcement', {})
summary = alert.get('page_summary', '')
# Escape for HTML context
esc_source = html_mod.escape(source)
esc_url = html_mod.escape(url)
esc_summary = html_mod.escape(summary)
esc_items = [html_mod.escape(i) for i in notable_items]
esc_matches = [html_mod.escape(m) for m in matches]
subject = f"[DROP WATCHER] {priority} — {source}"
# Plain text
text_lines = [
f"DROP WATCHER ALERT",
f"Priority: {priority}",
f"Site: {source}",
f"URL: {url}",
f"Time: {ts}",
f"",
]
if drop and drop.get('detected'):
text_lines += [
f"🔥 DROP ANNOUNCEMENT",
f"Maker: {drop.get('maker', '')}",
f"What: {drop.get('description', '')}",
f"When: {drop.get('timing', 'unknown')}",
f"Confidence: {drop.get('confidence', '')}",
f"",
]
if notable_items:
text_lines.append("Notable Items:")
for item in notable_items:
text_lines.append(f" → {item}")
text_lines.append("")
if summary:
text_lines.append(f"Summary: {summary}")
if matches and not notable_items:
text_lines.append(f"Matched keywords: {', '.join(matches[:15])}")
text_lines += [
"",
"HGR",
"instockornot.club",
"",
f"To unsubscribe: {UNSUBSCRIBE_URL}"
]
body_text = '\n'.join(text_lines)
# HTML
priority_color = '#e74c3c' if priority == 'CRITICAL' else '#e67e22'
notable_html = ''
if notable_items:
items = ''.join(f'<li style="margin:4px 0">{item}</li>' for item in esc_items)
notable_html = f'<h3 style="color:#d0d0d0;margin:16px 0 8px">Notable Items</h3><ul style="color:#d0d0d0;padding-left:20px">{items}</ul>'
drop_html = ''
if drop and drop.get('detected'):
drop_html = f"""
<div style="background:rgba(192,57,43,0.2);border-left:3px solid #e74c3c;padding:12px 16px;margin:16px 0">
<div style="color:#e74c3c;font-weight:bold;font-size:16px">🔥 DROP ANNOUNCEMENT</div>
<div style="color:#d0d0d0;margin-top:8px">
<strong>Maker:</strong> {html_mod.escape(drop.get('maker', ''))}<br>
<strong>What:</strong> {html_mod.escape(drop.get('description', ''))}<br>
<strong>When:</strong> {html_mod.escape(drop.get('timing', 'unknown'))}<br>
<strong>Confidence:</strong> {html_mod.escape(drop.get('confidence', ''))}
</div>
</div>"""
matches_html = ''
if matches and not notable_items:
matches_html = f'<p style="color:#888;font-size:12px">Matched: {", ".join(esc_matches[:15])}</p>'
summary_html = f'<p style="color:#888;font-style:italic;margin-top:12px">{esc_summary}</p>' if summary else ''
unsubscribe_html = f'<p style="margin-top:8px"><a href="{UNSUBSCRIBE_URL}" style="color:#555;font-size:10px">Unsubscribe</a></p>'
body_html = f"""
<html><body style="background:#0a0a0a;color:#f0f0f0;font-family:'Courier New',monospace;padding:24px;max-width:600px">
<h1 style="font-size:28px;letter-spacing:2px;margin:0">DROP <span style="color:#c0392b">WATCHER</span></h1>
<div style="height:2px;background:linear-gradient(90deg,transparent,#c0392b,#e67e22,#c0392b,transparent);margin:12px 0 24px"></div>
<div style="display:flex;gap:12px;align-items:center;margin-bottom:16px">
<span style="color:{priority_color};font-size:18px;font-weight:bold;letter-spacing:2px">{priority}</span>
<span style="color:#888;font-size:12px">{ts}</span>
</div>
<div style="background:#1c1c1c;padding:16px;margin-bottom:16px">
<div style="color:#888;font-size:11px;letter-spacing:2px;margin-bottom:8px">SITE</div>
<div style="font-size:20px;font-weight:bold;margin-bottom:12px">{esc_source}</div>
<a href="{esc_url}" style="display:inline-block;background:#c0392b;color:#ffffff;font-size:14px;font-weight:bold;letter-spacing:2px;padding:12px 24px;text-decoration:none;margin-bottom:8px">→ GO TO SITE NOW</a>
<div style="margin-top:8px"><a href="{esc_url}" style="color:#888;font-size:11px">{esc_url}</a></div>
</div>
{drop_html}
{notable_html}
{summary_html}
{matches_html}
<div style="margin-top:32px;padding-top:16px;border-top:1px solid #2a2a2a;color:#888;font-size:11px;letter-spacing:2px">
instockornot.club — <a href="https://instockornot.club/alerts.html" style="color:#e67e22">VIEW ALL ALERTS</a>
<div style="margin-top:8px;color:#c0392b;font-size:16px;font-weight:bold">HGR</div>
{unsubscribe_html}
</div>
</body></html>"""
return subject, body_html, body_text
# ── Format daily digest email ─────────────────────────────────────────────────
def format_digest_email(alerts):
now = datetime.now()
count = len(alerts)
subject = f"[DROP WATCHER] Daily Digest — {count} alerts — {now.strftime('%Y-%m-%d')}"
critical = [a for a in alerts if a.get('priority') == 'critical']
high = [a for a in alerts if a.get('priority') == 'high']
medium = [a for a in alerts if a.get('priority') == 'medium']
def alert_row(alert):
source = html_mod.escape(alert.get('source', 'Unknown'))
url = html_mod.escape(alert.get('url', '#'))
ts = alert.get('timestamp', '')[:16].replace('T', ' ')
items = alert.get('notable_items', [])
matches = alert.get('matches', [])
detail = html_mod.escape(items[0]) if items else (', '.join(html_mod.escape(m) for m in matches[:3]) if matches else '')
return f'<tr><td style="padding:6px 12px;color:#d0d0d0"><a href="{url}" style="color:#d0d0d0">{source}</a></td><td style="padding:6px 12px;color:#888;font-size:11px">{ts}</td><td style="padding:6px 12px;color:#888;font-size:11px">{detail}</td></tr>'
def section(title, color, alerts_list):
if not alerts_list:
return ''
rows = ''.join(alert_row(a) for a in alerts_list)
return f"""
<h3 style="color:{color};letter-spacing:2px;margin:24px 0 8px">{title} ({len(alerts_list)})</h3>
<table style="width:100%;border-collapse:collapse;background:#1c1c1c">
<thead><tr>
<th style="text-align:left;padding:6px 12px;color:#888;font-size:11px;letter-spacing:2px;border-bottom:1px solid #2a2a2a">SITE</th>
<th style="text-align:left;padding:6px 12px;color:#888;font-size:11px;letter-spacing:2px;border-bottom:1px solid #2a2a2a">TIME</th>
<th style="text-align:left;padding:6px 12px;color:#888;font-size:11px;letter-spacing:2px;border-bottom:1px solid #2a2a2a">DETAIL</th>
</tr></thead>
<tbody>{rows}</tbody>
</table>"""
unsubscribe_html = f'<p style="margin-top:8px"><a href="{UNSUBSCRIBE_URL}" style="color:#555;font-size:10px">Unsubscribe</a></p>'
body_html = f"""
<html><body style="background:#0a0a0a;color:#f0f0f0;font-family:'Courier New',monospace;padding:24px;max-width:700px">
<h1 style="font-size:28px;letter-spacing:2px;margin:0">DROP <span style="color:#c0392b">WATCHER</span></h1>
<div style="height:2px;background:linear-gradient(90deg,transparent,#c0392b,#e67e22,#c0392b,transparent);margin:12px 0 24px"></div>
<h2 style="color:#888;font-size:14px;letter-spacing:3px;font-weight:normal">DAILY DIGEST — {now.strftime('%Y-%m-%d')}</h2>
<div style="display:flex;gap:24px;margin:24px 0">
<div style="background:#1c1c1c;padding:12px 20px;text-align:center">
<div style="color:#888;font-size:10px;letter-spacing:2px">TOTAL</div>
<div style="color:#f0f0f0;font-size:24px">{count}</div>
</div>
<div style="background:#1c1c1c;padding:12px 20px;text-align:center">
<div style="color:#888;font-size:10px;letter-spacing:2px">CRITICAL</div>
<div style="color:#e74c3c;font-size:24px">{len(critical)}</div>
</div>
<div style="background:#1c1c1c;padding:12px 20px;text-align:center">
<div style="color:#888;font-size:10px;letter-spacing:2px">HIGH</div>
<div style="color:#e67e22;font-size:24px">{len(high)}</div>
</div>
<div style="background:#1c1c1c;padding:12px 20px;text-align:center">
<div style="color:#888;font-size:10px;letter-spacing:2px">MEDIUM</div>
<div style="color:#f1c40f;font-size:24px">{len(medium)}</div>
</div>
</div>
{section('🔥 CRITICAL', '#e74c3c', critical)}
{section('⚡ HIGH', '#e67e22', high)}
{section('· MEDIUM', '#f1c40f', medium)}
<div style="margin-top:32px;padding-top:16px;border-top:1px solid #2a2a2a;color:#888;font-size:11px;letter-spacing:2px">
<a href="https://instockornot.club/alerts.html" style="color:#e67e22">VIEW FULL ALERTS PAGE</a>
<div style="margin-top:8px;color:#c0392b;font-size:16px;font-weight:bold">HGR</div>
{unsubscribe_html}
</div>
</body></html>"""
body_text = f"Drop Watcher Daily Digest — {now.strftime('%Y-%m-%d')}\n{count} total alerts\nCritical: {len(critical)} High: {len(high)} Medium: {len(medium)}\n\nSee https://instockornot.club/alerts.html\n\nHGR\n\nTo unsubscribe: {UNSUBSCRIBE_URL}"
return subject, body_html, body_text
# ── Send immediate alerts for new high/critical drops ────────────────────────
def send_immediate_alerts():
if not os.path.exists(DROPS_LOG):
return
cutoff = datetime.now(timezone.utc) - timedelta(minutes=35)
sent_count = 0
with open(DROPS_LOG, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
alert = json.loads(line)
priority = alert.get('priority', 'medium').lower()
if priority not in IMMEDIATE_PRIORITIES:
continue
ts_str = alert.get('timestamp', '')
if ts_str:
ts = datetime.fromisoformat(ts_str)
if ts < cutoff:
continue
alert_id = make_alert_id(alert)
if already_sent(alert_id):
continue
subject, body_html, body_text = format_immediate_email(alert)
if send_email(subject, body_html, body_text, extra_recipients=None):
mark_sent(alert_id, 'immediate')
send_sms_alert(alert)
sent_count += 1
except json.JSONDecodeError:
continue
if sent_count:
log.info(f"Sent {sent_count} immediate alert emails via Resend")
# ── Send daily digest ─────────────────────────────────────────────────────────
def send_daily_digest():
if not os.path.exists(DROPS_LOG):
log.info("No drops log found — skipping digest")
return
cutoff = datetime.now(timezone.utc) - timedelta(hours=24)
alerts = []
with open(DROPS_LOG, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
alert = json.loads(line)
ts_str = alert.get('timestamp', '')
if ts_str:
ts = datetime.fromisoformat(ts_str)
if ts > cutoff:
alerts.append(alert)
except json.JSONDecodeError:
continue
subject, body_html, body_text = format_digest_email(alerts)
if send_email(subject, body_html, body_text, extra_recipients=None):
log.info(f"Daily digest sent via Resend — {len(alerts)} alerts")
# ── Test ──────────────────────────────────────────────────────────────────────
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
import sys
if len(sys.argv) > 1 and sys.argv[1] == 'digest':
log.info("Sending daily digest...")
send_daily_digest()
elif len(sys.argv) > 1 and sys.argv[1] == 'test':
log.info("Sending test email via Resend...")
test_alert = {
'timestamp': datetime.now(timezone.utc).isoformat(),
'priority': 'high',
'source': 'Test Site',
'url': 'https://instockornot.club',
'notable_items': ['CRK Damascus Sebenza 31 — 1 in stock', 'Hinderer XM-18 Steel Flame — 1 in stock'],
'page_summary': 'Test alert from Drop Watcher system.',
'drop_announcement': {
'detected': True,
'maker': 'Steel Flame',
'description': 'New pendant drop',
'timing': 'Friday at noon',
'confidence': 'high'
}
}
subject, body_html, body_text = format_immediate_email(test_alert)
success = send_email(subject, body_html, body_text)
print("✓ Test email sent via Resend!" if success else "✗ Test email failed — check logs")
else:
log.info("Checking for unsent immediate alerts...")
send_immediate_alerts()