telegram: entire message body now rendered at 1.5x (every line an H2 heading in Rich Messages)
513dcc9 Download modules/telegram_alert.py from deanpowers/blind-monkeys: direct link, hf CLI and curl.
- Browser
- Download file 8.14 kB
-
https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/telegram_alert.py
- Command line
-
hf download hf://deanpowers/blind-monkeys/modules/telegram_alert.py
-
curl -L -o telegram_alert.py https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/telegram_alert.py
8.14 kB
| import os | |
| import requests | |
| def _creds(): | |
| token = os.environ.get("TELEGRAM_BOT_TOKEN", "") | |
| chat = os.environ.get("TELEGRAM_CHAT_ID", "") | |
| return token, chat | |
| def _sym_link(sym): | |
| """Symbol as a clickable link to its 24h thumbnail chart.""" | |
| import urllib.parse as _up | |
| s = str(sym) | |
| return ('<a href="https://charts.blindmonkeys.org/grid/symbol-chart?symbol=' | |
| + _up.quote(s) + '">' + s + '</a>') | |
| def send_telegram_message(text: str) -> bool: | |
| """Send an HTML-formatted message to the configured Telegram chat.""" | |
| token, chat = _creds() | |
| if not token or not chat: | |
| print("β οΈ Telegram not configured (missing TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID)") | |
| return False | |
| from datetime import datetime, timezone, timedelta | |
| stamp = datetime.now(timezone(timedelta(hours=4))).strftime("%Y-%m-%d %H:%M:%S") | |
| # Primary: Rich Message β every line (stamp + body) rendered as an H2 | |
| # heading (~1.5Γ normal text size, per Dean's request 2026-11-05); | |
| # classic messages have no font-size markup. | |
| lines = ["## π’ " + stamp] | |
| for ln in text.split("\n"): | |
| lines.append("## " + ln if ln.strip() else "") | |
| try: | |
| r = requests.post(f"https://api.telegram.org/bot{token}/sendRichMessage", json={ | |
| "chat_id": chat, | |
| "rich_message": {"markdown": "\n".join(lines)}, | |
| }, timeout=15) | |
| if r.status_code == 200: | |
| return True | |
| except Exception: | |
| pass | |
| # Fallback: classic bold stamp (previous behavior) | |
| text = f"π’ <b>{stamp}</b>\n{text}" | |
| url = f"https://api.telegram.org/bot{token}/sendMessage" | |
| try: | |
| r = requests.post(url, json={ | |
| "chat_id": chat, | |
| "text": text, | |
| "parse_mode": "HTML", | |
| "disable_web_page_preview": True, | |
| }, timeout=10) | |
| if r.status_code != 200: | |
| print(f"β Telegram error {r.status_code}: {r.text}") | |
| return False | |
| return True | |
| except Exception as e: | |
| print(f"β Telegram send failed: {e}") | |
| return False | |
| def format_buy_signals(scan_data: dict) -> str: | |
| """Build a rich HTML message for coins that passed buy criteria.""" | |
| results = scan_data.get("results", []) | |
| signals = [r for r in results if r.get("buy_signal")] | |
| if not signals: | |
| return "" | |
| lines = [ | |
| f"π’ <b>Scan β {len(signals)} Buy Signal(s)</b>", | |
| f"<i>Lookback: {scan_data.get('lookback_days', 20)}d Β· " | |
| f"RSI: {scan_data.get('rsi_period', 14)} Β· " | |
| f"Scanned: {scan_data.get('total_scanned', 0)}</i>", | |
| "", | |
| ] | |
| for r in signals: | |
| lines.append( | |
| f"β’ <b>{_sym_link(r['symbol'])}</b> β " | |
| f"Z:<code>{r['zscore']}</code> | " | |
| f"RSI:<code>{r['rsi']}</code> | " | |
| f"Mom:<code>{r['momentum']}%</code> | " | |
| f"Vol:<code>{r['volatility']}%</code>" | |
| ) | |
| lines.append(f" Score: <b>{r['composite_score']}</b>") | |
| return "\n".join(lines) | |
| _CACHED_AUTO_OPEN = {"value": None, "ts": 0.0} | |
| def format_scan_summary(scan_data: dict) -> str: | |
| """Build an HTML summary message for ANY scan (buy signals or not).""" | |
| results = scan_data.get("results", []) | |
| signals = [r for r in results if r.get("buy_signal")] | |
| total = scan_data.get("total_scanned", len(results)) | |
| mode = scan_data.get("scan_mode", "conservative") | |
| if signals: | |
| header = "π’ <b>Scan β " + str(len(signals)) + " Buy Signal(s)</b>" | |
| else: | |
| mode_label = str(mode).capitalize() | |
| top = max(results, key=lambda x: x.get("composite_score", 0)) \ | |
| if results else None | |
| header = ("π <b>" + mode_label + " Scan Complete: No coin met " | |
| "the buy criteria.</b>") | |
| # The threshold shown is the auto-open value from the futures | |
| # settings (fut_auto_open), fetched from the trader config and | |
| # cached for 15 minutes (the trader scales to zero; its cold | |
| # start can exceed a short timeout). | |
| import time as _time | |
| _now = _time.time() | |
| if _now - _CACHED_AUTO_OPEN["ts"] > 900: | |
| try: | |
| import os as _os | |
| import urllib.request as _ur2 | |
| import json as _json2 | |
| _turl = _os.environ.get( | |
| "TRADER_URL", | |
| "https://blind-monkeys-trader-353804379600.europe-west1.run.app") | |
| with _ur2.urlopen(_turl.rstrip("/") + "/config", timeout=40) as _r: | |
| _cfg = _json2.loads(_r.read().decode("utf-8")) | |
| _val = _cfg.get("fut_auto_open") | |
| if _val is not None: | |
| _CACHED_AUTO_OPEN["value"] = _val | |
| _CACHED_AUTO_OPEN["ts"] = _now | |
| except Exception: | |
| pass | |
| threshold = _CACHED_AUTO_OPEN["value"] | |
| if threshold is None: | |
| threshold = 1 | |
| if threshold is not None: | |
| header += "\nThe current score threshold is <b>" + str(threshold) + "</b>" | |
| if top: | |
| _sc = top.get("composite_score") | |
| try: | |
| _sc = float(_sc) | |
| _sc_txt = ("NEGATIVE " + str(abs(_sc))) if _sc < 0 else str(_sc) | |
| except (TypeError, ValueError): | |
| _sc_txt = str(_sc) | |
| header += ("\nHighest scoring coin was <b>" | |
| + _sym_link(top.get("symbol", "?")) | |
| + "</b> with a score of <b>" + _sc_txt + "</b>") | |
| # report the actual blocking criterion for the top coin | |
| _crit = {"conservative": {"zscore": -1.0, "momentum": 5.0, | |
| "volatility": 8.0, "rsi": 70.0}, | |
| "risk": {"zscore": -1.5, "momentum": 10.0, | |
| "volatility": 25.0, "rsi": 60.0}}.get( | |
| str(mode).lower(), {}) | |
| try: | |
| _fails = [] | |
| if float(top.get("zscore") or 0) >= _crit["zscore"]: | |
| _fails.append("Z-score " + str(top.get("zscore")) + " (must be below " + str(_crit["zscore"]) + ")") | |
| if float(top.get("momentum") or 0) <= _crit["momentum"]: | |
| _fails.append("momentum " + str(top.get("momentum")) + " (must be above " + str(_crit["momentum"]) + ")") | |
| if float(top.get("volatility") or 0) >= _crit["volatility"]: | |
| _fails.append("volatility " + str(top.get("volatility")) + " (must be below " + str(_crit["volatility"]) + ")") | |
| if float(top.get("rsi") or 0) >= _crit["rsi"]: | |
| _fails.append("RSI " + str(top.get("rsi")) + " (must be below " + str(_crit["rsi"]) + ")") | |
| if _fails: | |
| # NOTE: Telegram does not support <font color> (message | |
| # would fail to send) β use a red-circle emoji instead. | |
| header += '\n<b>Blocked by:</b>' | |
| for _f in _fails: | |
| header += ('\n β’ π΄ ' + _f) | |
| except Exception: | |
| pass | |
| lines = [ | |
| header, | |
| "<i>Mode: " + str(mode) + " Β· Scanned: " + str(total) + " Β· Lookback: " | |
| + str(scan_data.get("lookback_days", 20)) + "d</i>", | |
| ] | |
| geo = scan_data.get("geo") | |
| if geo and (geo.get("city") or geo.get("country")): | |
| parts = [x for x in [geo.get("city"), geo.get("state"), geo.get("country")] if x] | |
| lines.append("π " + ", ".join(parts)) | |
| lines.append("") | |
| if signals: | |
| for r in signals[:10]: | |
| lines.append( | |
| "β’ <b>" + str(r.get("symbol", "?")) + "</b> β " | |
| + "Z:<code>" + str(r.get("zscore", "?")) + "</code> | " | |
| + "RSI:<code>" + str(r.get("rsi", "?")) + "</code> | " | |
| + "Mom:<code>" + str(r.get("momentum", "?")) + "%</code>" | |
| ) | |
| return "\n".join(lines) | |
| def alert_on_buy_signals(scan_data: dict) -> bool: | |
| """Send a Telegram summary for every scan (buy signals or not).""" | |
| text = format_scan_summary(scan_data) | |
| return send_telegram_message(text) | |