-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiscordAlertService.py
More file actions
429 lines (375 loc) Β· 18.6 KB
/
DiscordAlertService.py
File metadata and controls
429 lines (375 loc) Β· 18.6 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""
DiscordAlertService.py
======================
Outbound-only Discord webhook integration for PropIQ Analytics Engine.
Reads DISCORD_WEBHOOK_URL from environment (with hardcoded fallback).
All methods are safe to call even when the webhook is unreachable --
failures are logged as warnings and silently swallowed so they never
crash the engine.
Public API
----------
send_startup_ping()
send_bet_alert(bet: dict)
send_daily_recap(results, profit, date_str)
send_parlay_alert(parlay: dict)
Usage
-----
from DiscordAlertService import discord_alert, MAX_STAKE_USD
discord_alert.send_startup_ping()
discord_alert.send_parlay_alert(parlay_dict)
"""
from __future__ import annotations
import logging
import os
from datetime import datetime, timezone
from zoneinfo import ZoneInfo as _ZoneInfo
_PT = _ZoneInfo("America/Los_Angeles")
from typing import Any
import requests
logger = logging.getLogger("propiq.discord")
# ββ Exported constant (imported by live_dispatcher.py) ββββββββββββββββββββ
MAX_STAKE_USD: float = 20.0 # Tier 5 ceiling ($20/unit)
# ββ Colour palette ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_COLOUR_GREEN = 0x2ECC71 # win / online
_COLOUR_RED = 0xE74C3C # loss / warning
_COLOUR_BLUE = 0x3498DB # bet alert
_COLOUR_GOLD = 0xF1C40F # daily recap
_COLOUR_GREY = 0x95A5A6 # push / neutral
# ββ Webhook URL β always read from DISCORD_WEBHOOK_URL env var ββββββββββββββββββββββ
# Never hardcode tokens here β they are public in the GitHub repo.
# Set DISCORD_WEBHOOK_URL in Railway service variables.
_FALLBACK_WEBHOOK = "" # intentionally empty β fails loudly if env var missing
# ββ Platform emoji map ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_PLATFORM_EMOJI = {
"prizepicks": "π",
"underdog": "πΆ",
"sleeper": "π΄",
}
# ββ Tier badge map βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_TIER_BADGE = {1: "π±", 2: "πΏ", 3: "β", 4: "π₯", 5: "π"}
class DiscordAlertService:
"""Thin wrapper around a single Discord incoming webhook URL."""
def __init__(self) -> None:
self._url: str = os.getenv("DISCORD_WEBHOOK_URL", _FALLBACK_WEBHOOK)
# ββ Internal helper βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _post(self, payload: dict[str, Any]) -> bool:
"""POST payload to the webhook. Returns True on success."""
url = os.getenv("DISCORD_WEBHOOK_URL", self._url) or _FALLBACK_WEBHOOK
try:
resp = requests.post(
url,
json=payload,
timeout=10,
headers={"Content-Type": "application/json"},
)
if resp.status_code in (200, 204):
return True
logger.warning("[Discord] Webhook returned HTTP %d: %s",
resp.status_code, resp.text[:200])
return False
except Exception as exc:
logger.warning("[Discord] Failed to reach webhook: %s", exc)
return False
# ββ Public methods βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def send_startup_ping(self) -> None:
"""Fire a test message the absolute second the application is ready."""
ok = self._post({
"embeds": [{
"title": "β
PropIQ Engine Online: Webhook Connected!",
"description": (
"All tasklets are scheduled and running.\n"
"17-Agent Army armed | Underdog + PrizePicks | Every 30s."
),
"color": _COLOUR_GREEN,
"footer": {"text": "PropIQ Analytics Engine"},
"timestamp": datetime.now(_PT).isoformat(),
}]
})
if ok:
logger.info("[Discord] Startup ping sent successfully.")
def send_bet_alert(self, bet: dict) -> None:
"""Send a formatted embed for a single queued bet."""
player = bet.get("player", "Unknown")
prop_type = bet.get("prop_type", "")
line = bet.get("line", "")
side = bet.get("side", "")
ev_pct = bet.get("ev_pct", 0.0)
kelly = bet.get("kelly_units", 0.0)
conf = bet.get("confidence", 5)
agents = bet.get("agents", [bet.get("agent", "Unknown")])
agent_cnt = bet.get("agent_count", len(agents))
platform = bet.get("recommended_platform", "PrizePicks")
odds_raw = bet.get("odds_american", -110)
model_prob = bet.get("model_prob", 50.0)
odds_str = f"+{odds_raw}" if isinstance(odds_raw, int) and odds_raw > 0 else str(odds_raw)
plat_lower = str(platform).lower()
plat_emoji = _PLATFORM_EMOJI.get(plat_lower, "π―")
plat_label = platform.capitalize()
filled = round(conf)
conf_bar = "β" * filled + "β" * (10 - filled)
checklist = bet.get("checklist", {})
checks = " ".join(
("β
" if v else "β") + k.replace("_ok", "").upper()
for k, v in checklist.items()
) if checklist else "N/A"
self._post({
"embeds": [{
"title": f"{plat_emoji} OPEN APP: {plat_label}",
"color": _COLOUR_BLUE,
"fields": [
{"name": "π§ Player", "value": player, "inline": True},
{"name": "π Prop", "value": f"{prop_type} {side} {line}", "inline": True},
{"name": "π° Odds", "value": odds_str, "inline": True},
{"name": "π Edge (EV)", "value": f"+{ev_pct:.1f}%", "inline": True},
{"name": "π² Kelly Units", "value": f"{kelly:.3f}u", "inline": True},
{"name": "π€ Model Prob", "value": f"{model_prob:.1f}%", "inline": True},
{"name": "π₯ Confidence", "value": f"{conf_bar} {conf}/10", "inline": False},
{"name": f"π€ Agent Consensus ({agent_cnt}/17)",
"value": ", ".join(agents), "inline": False},
{"name": "βοΈ 7-Point Check", "value": checks, "inline": False},
],
"footer": {"text": "PropIQ Analytics Engine"},
"timestamp": datetime.now(_PT).isoformat(),
}]
})
def send_daily_recap(
self,
parlay_results: list[dict],
total_profit: float,
date_str: str,
tier_updates: list[str] | None = None,
) -> None:
"""Send end-of-day settlement recap grouped by parlay slip. Each slip is one line."""
from zoneinfo import ZoneInfo as _ZI
_PT = _ZI("America/Los_Angeles")
wins = sum(1 for p in parlay_results if p.get("status") == "WIN")
losses = sum(1 for p in parlay_results if p.get("status") == "LOSS")
pushes = sum(1 for p in parlay_results if p.get("status") == "PUSH")
sign = "+" if total_profit >= 0 else ""
colour = _COLOUR_GREEN if total_profit >= 0 else _COLOUR_RED
lines: list[str] = []
for parlay in parlay_results:
status = parlay.get("status", "")
emoji = {"WIN": "β
", "LOSS": "β", "PUSH": "β"}.get(status, "β")
pl = parlay.get("profit_loss", 0.0)
pl_sign = "+" if pl >= 0 else ""
agent = parlay.get("agent", "")
legs = parlay.get("legs", [])
n_legs = parlay.get("leg_count", len(legs))
stake = parlay.get("stake", 5.0)
entry = parlay.get("entry_type", "")
# Header line: agent + slip-level result
agent_tag = f"`[{agent}]`" if agent else ""
entry_tag = f" {entry}" if entry and entry not in ("STANDARD", "FlexPlay") else ""
lines.append(
f"{emoji} {agent_tag} **{n_legs}-Leg Slip**{entry_tag} | "
f"${stake:.0f} stake | {pl_sign}{pl:.2f}u"
)
# One sub-line per leg showing actual vs line
for leg in legs:
leg_status = leg.get("status", "")
leg_emoji = {"WIN": "β
", "LOSS": "β", "PUSH": "β"}.get(leg_status, "β")
actual = leg.get("actual")
line_val = leg.get("line", "?")
prop_type = str(leg.get("prop_type", "?")).replace("_", " ").title()
side = leg.get("side", "?")
player = leg.get("player", "?")
actual_str = f"Actual **{actual}** vs {line_val}" if actual is not None else ""
lines.append(
f" {leg_emoji} {player} β {prop_type} {side} {actual_str}"
)
description = "\n".join(lines) or "_No graded slips._"
if len(description) > 3_000:
description = description[:2_950] + "\nβ¦(truncated)"
fields = [
{"name": "π Units", "value": f"{sign}{total_profit:.2f}u", "inline": True},
{"name": "π Record", "value": f"{wins}-{losses}-{pushes} W-L-P (slips)", "inline": True},
]
if tier_updates:
fields.append({
"name": "π° Tier Ladder",
"value": "\n".join(tier_updates),
"inline": False,
})
self._post({
"embeds": [{
"title": f"π PropIQ Daily Recap β {date_str}",
"description": description,
"color": colour,
"fields": fields,
"footer": {"text": "Powered by PropIQ Analytics π€ | 3 W or 3 L in a row = tier move"},
"timestamp": datetime.now(_PT).isoformat(),
}]
})
logger.info("[Discord] Daily recap sent β %s %s%+.2fu %d-%d-%d (slips)",
date_str, sign, total_profit, wins, losses, pushes)
def send_parlay_alert(self, parlay: dict) -> None:
"""
Send a formatted Discord embed for a DFS parlay slip.
Called by live_dispatcher.py for each agent parlay.
Expected parlay dict keys (from live_dispatcher.py build_parlay()):
agent_name str β e.g. "EVHunter"
legs list β list of leg dicts
confidence float β 0β10 score
ev_pct float β average EV% across legs
stake float β dollar stake from agent tier ($5β$20)
tier int β agent tier 1β5 (optional, derived from stake)
platform str β "prizepicks" or "underdog"
season_stats dict β {wins, losses, pushes, roi} (optional)
Each leg dict keys:
player_name str
prop_type str
side str β "Over" or "Under"
line float
ev_pct float
model_prob float (0β1)
platform str
"""
# --- Parlay-level fields ---
agent_name = parlay.get("agent_name") or parlay.get("agent", "Unknown Agent")
legs = parlay.get("legs", [])
confidence = parlay.get("confidence", 0.0)
ev_pct = parlay.get("ev_pct") or parlay.get("combined_ev_pct", 0.0)
stake = parlay.get("stake", parlay.get("unit_dollars", 5.0))
leg_count = len(legs)
if not legs:
return
# Derive tier badge from stake amount
stake_to_tier = {5.0: 1, 8.0: 2, 12.0: 3, 16.0: 4, 20.0: 5}
tier = parlay.get("tier", stake_to_tier.get(float(stake), 1))
tier_badge = _TIER_BADGE.get(tier, "π±")
# Confidence bar ββββββββββ (10 blocks)
filled = max(0, min(10, round(confidence)))
conf_bar = "β" * filled + "β" * (10 - filled)
# Platform
platform = parlay.get("platform", "underdog")
plat_lower = str(platform).lower()
plat_emoji = _PLATFORM_EMOJI.get(plat_lower, "π―")
if "prize" in plat_lower:
plat_label = "PrizePicks"
else:
et = parlay.get("entry_type", "FlexPlay")
entry_label = "PowerPlay" if et.upper() in ("STANDARD", "POWERPLAY", "POWER") else "FlexPlay"
plat_label = f"Underdog Fantasy β {entry_label}"
# --- Season record footer ---
season = parlay.get("season_stats", {})
s_wins = season.get("wins", 0)
s_losses = season.get("losses", 0)
s_pushes = season.get("pushes", 0)
s_roi = season.get("roi_pct", season.get("roi", 0.0))
season_str = f"{agent_name} Season: {s_wins}W-{s_losses}L-{s_pushes}P | ROI {s_roi:+.1f}%"
# --- Leg fields ---
fields: list[dict] = []
for i, leg in enumerate(legs, 1):
player = (leg.get("player_name") or leg.get("player", "?")).title()
prop_type = leg.get("prop_type", "?").replace("_", " ").title()
side_raw = leg.get("side", "?")
leg_plat = leg.get("platform", platform)
# Underdog uses Higher/Lower; translate for display
if "underdog" in str(leg_plat).lower() or "underdog" in plat_lower:
_s_map = {"over": "Higher", "under": "Lower"}
side = _s_map.get(side_raw.lower(), side_raw)
else:
side = side_raw
line = leg.get("line", "?")
leg_ev = leg.get("ev_pct", 0.0)
model_p = leg.get("model_prob", 0.0)
# model_prob may be 0-1 or 0-100
if isinstance(model_p, float) and model_p <= 1.0:
model_p *= 100.0
leg_plat = leg.get("platform", platform)
lp_lower = str(leg_plat).lower()
lp_emoji = _PLATFORM_EMOJI.get(lp_lower, "π―")
fields.append({
"name": f"Leg {i} β {player}",
"value": (
f"**{prop_type} {side} {line}** {lp_emoji}\n"
f"Model: `{model_p:.1f}%` | EV: `+{leg_ev:.1f}%`"
),
"inline": False,
})
fields.append({
"name": f"π Summary β {leg_count}-Leg Slip",
"value": (
f"Avg EV: **+{ev_pct:.1f}%** | "
f"Confidence: {conf_bar} {confidence:.1f}/10 | "
f"Stake: **${stake:.0f}**"
),
"inline": False,
})
# Colour by confidence
if confidence >= 8.5:
color = _COLOUR_GOLD
elif confidence >= 7.0:
color = _COLOUR_GREEN
else:
color = _COLOUR_BLUE
self._post({
"embeds": [{
"title": f"{tier_badge} {agent_name} β {leg_count}-Leg {plat_label} Slip",
"description": (
f"{plat_emoji} **Open {plat_label} to enter this slip**\n"
f"Stake: **${stake:.0f}** | EV: **+{ev_pct:.1f}%**"
),
"color": color,
"fields": fields,
"footer": {"text": season_str},
"timestamp": datetime.now(_PT).isoformat(),
}]
})
logger.info("[Discord] Parlay alert sent β %s | %d legs | +%.1f%% EV | $%.0f stake | %s T%d",
agent_name, leg_count, ev_pct, stake, tier_badge, tier)
def send_parlay_alert_streak(self, parlay: dict) -> None:
"""
Streak-specific Discord embed with Underdog Streaks branding.
Same field contract as send_parlay_alert() above.
"""
agent_name = parlay.get("agent_name", "StreakAgent")
legs = parlay.get("legs", [])
confidence = parlay.get("confidence", 0.0)
ev_pct = parlay.get("ev_pct", 0.0)
stake = parlay.get("stake", 5.0)
leg_count = len(legs)
if not legs:
return
fields: list[dict] = []
for i, leg in enumerate(legs, 1):
player = (leg.get("player_name") or leg.get("player", "?")).title()
prop_type = leg.get("prop_type", "?").replace("_", " ").title()
_side_raw = leg.get("side", "?")
_s_map = {"over": "Higher", "under": "Lower"}
side = _s_map.get(_side_raw.lower(), _side_raw)
line = leg.get("line", "?")
streak_n = leg.get("streak_length", leg.get("streak", "?"))
fields.append({
"name": f"Leg {i} β {player}",
"value": (
f"**{prop_type} {side} {line}**\n"
f"Streak: `{streak_n} consecutive`"
),
"inline": False,
})
fields.append({
"name": f"π₯ Streak Summary β {leg_count}-Leg",
"value": f"EV: **+{ev_pct:.1f}%** | Confidence: **{confidence:.1f}/10** | Stake: **${stake:.0f}**",
"inline": False,
})
season = parlay.get("season_stats", {})
s_wins = season.get("wins", 0)
s_losses = season.get("losses", 0)
s_roi = season.get("roi_pct", season.get("roi", 0.0))
footer_str = f"StreakAgent Season: {s_wins}W-{s_losses}L | ROI {s_roi:+.1f}%"
self._post({
"embeds": [{
"title": f"π₯ StreakAgent β {leg_count}-Leg Underdog Streak",
"description": "πΆ **Open Underdog Fantasy β Streaks tab**",
"color": _COLOUR_GOLD,
"fields": fields,
"footer": {"text": footer_str},
"timestamp": datetime.now(_PT).isoformat(),
}]
})
logger.info("[Discord] Streak alert sent β %d legs, +%.1f%% EV, $%.0f stake",
leg_count, ev_pct, stake)
# Module-level singleton β import this everywhere
discord_alert = DiscordAlertService()