blind-monkeys / modules /high_score_alerts.py
deanpowers's picture
feat(alerts): banner shows current state sorted by score; dismiss snoozes 1h
11e8352
Raw History Blame Contribute Delete
5.7 kB
"""High-score alerts: per-coin, per-mode state tracker."""
import os, time
from modules.storage import load_json, save_json
from modules.alert_config import get_config, in_quiet_hours
STATE_FILE = "alert_state.json"
ALERTS_FILE = "alerts.json"
MAX_ALERTS = 50
def _load_state():
d = load_json(STATE_FILE, default=None) or {}
if not isinstance(d.get("coins"), dict):
d["coins"] = {}
if "last_telegram_sent" not in d:
d["last_telegram_sent"] = 0
return d
def _save_state(d):
save_json(STATE_FILE, d)
def _load_alerts():
a = load_json(ALERTS_FILE, default=[])
return a if isinstance(a, list) else []
def _save_alerts(a):
save_json(ALERTS_FILE, a[-MAX_ALERTS:])
def _key(sym, mode):
return "%s:%s" % (sym, mode)
def check_scan_results(results, scan_mode="conservative"):
cfg = get_config()
if not cfg.get("enabled", True):
return []
mode_cfg = cfg.get(scan_mode) or {}
if not mode_cfg.get("enabled", True):
return []
threshold = float(mode_cfg.get("threshold", 100))
state = _load_state()
coins = state["coins"]
alerts = _load_alerts()
now = int(time.time())
new = []
for r in results or []:
sym = r.get("symbol") or r.get("coin_id") or r.get("id")
score = r.get("composite_score")
if not sym or score is None:
continue
try:
score = float(score)
except Exception:
continue
sym = str(sym).upper()
key = _key(sym, scan_mode)
c = coins.get(key, {"armed": True})
armed = bool(c.get("armed", True))
last_alert_score = float(c.get("last_alert_score", 0))
# Re-arm if score jumped significantly above the last alert
if not armed and last_alert_score > 0:
jumped_abs = score >= last_alert_score + 50
jumped_rel = score >= last_alert_score * 1.5
if jumped_abs or jumped_rel:
armed = True
c["armed"] = True
if score >= threshold and armed:
entry = {"symbol": sym, "score": round(score, 2), "ts": now, "mode": scan_mode}
new.append(entry)
alerts = [a for a in alerts if not (a.get("symbol") == sym and a.get("mode") == scan_mode)]
alerts.append(entry)
c["armed"] = False
c["last_alert_score"] = round(score, 2)
c["last_alert_ts"] = now
elif score < threshold and not armed:
c["armed"] = True
c["last_score"] = round(score, 2)
coins[key] = c
state["coins"] = coins
_save_state(state)
_save_alerts(alerts)
return new
def get_active_alerts():
"""Banner view: every coin currently above its mode threshold, sorted by score desc."""
cfg = get_config()
state = _load_state()
coins = state.get("coins", {})
out = []
for key, c in coins.items():
if ":" not in key:
continue
sym, mode = key.split(":", 1)
threshold = float((cfg.get(mode) or {}).get("threshold", 100))
last = c.get("last_score")
if last is None:
continue
try:
last = float(last)
except Exception:
continue
if last < threshold:
continue
out.append({
"symbol": sym,
"score": round(last, 2),
"mode": mode,
"ts": c.get("last_alert_ts") or 0,
})
out.sort(key=lambda x: x["score"], reverse=True)
return out[:10]
DISMISS_COOLDOWN_SECONDS = 3600 # 1 hour
def filter_for_user(alerts, email):
try:
from modules.auth import get_user_alerts, get_dismissed_alerts
except Exception:
return alerts
prefs = get_user_alerts(email) or {}
if not prefs.get("high_score_alerts", True):
return []
dismissed = get_dismissed_alerts(email) or {}
now = int(time.time())
out = []
for a in alerts:
sym = a.get("symbol")
d = dismissed.get(sym, 0)
if d and (now - d) < DISMISS_COOLDOWN_SECONDS:
continue
out.append(a)
return out
def build_telegram_message(new_alerts):
n = len(new_alerts)
parts = ["%s %s" % (a["symbol"], int(a["score"])) for a in new_alerts]
return "\U0001F6A8 " + str(n) + " coin" + ("s" if n != 1 else "") + " crossed threshold: " + " \u00b7 ".join(parts)
def flush_telegram_batch():
cfg = get_config()
if not cfg.get("telegram_enabled", True):
return 0
if in_quiet_hours(cfg):
return 0
state = _load_state()
last_sent = state.get("last_telegram_sent", 0)
alerts = _load_alerts()
pending = []
for a in alerts:
if a.get("ts", 0) <= last_sent:
continue
mode = a.get("mode", "conservative")
threshold = float((cfg.get(mode) or {}).get("threshold", 100))
if float(a.get("score", 0)) < threshold:
continue
pending.append(a)
if alerts:
max_ts = max(a.get("ts", 0) for a in alerts)
if max_ts > last_sent:
state["last_telegram_sent"] = max_ts
_save_state(state)
if not pending:
return 0
try:
from modules.telegram_alert import send_telegram_message
except Exception as e:
print("telegram import failed: " + str(e))
return 0
msg = build_telegram_message(sorted(pending, key=lambda x: x.get("ts", 0)))
ok = send_telegram_message(msg)
return len(pending) if ok else 0
def clear_alerts_log():
save_json(ALERTS_FILE, [])
return True
def reset_alert_state():
save_json(STATE_FILE, {"coins": {}, "last_telegram_sent": 0})
return True