import logging import httpx from .config import settings from .http_client import httpx_client_kwargs logger = logging.getLogger(__name__) def _format_period_label(period_start: str, period_end: str) -> str: start = period_start[:16].replace("T", " ") end = period_end[:16].replace("T", " ") return f"{start} ~ {end}" def build_markdown(snapshot: dict) -> str: items = snapshot.get("items", []) period_label = _format_period_label( snapshot.get("period_start", ""), snapshot.get("period_end", ""), ) lines = [ "## 币安 U本位合约 成交额 Top30", f"> 统计周期(北京时间 8:00 切日)", f"> **{period_label}**", "", "| 排名 | 合约 | 成交额(USDT) | 涨跌幅 | 标记 |", "| --- | --- | --- | --- | --- |", ] for row in items: tags = [] if row.get("is_high_volume"): tags.append("千万+") if row.get("is_high_change"): tags.append("涨跌5%+") tag_str = " ".join(tags) if tags else "-" vol = row.get("quote_volume_fmt") or f"{row.get('quote_volume', 0):.0f}" pct = row.get("price_change_pct_fmt") or f"{row.get('price_change_pct', 0):+.2f}%" lines.append( f"| {row['rank']} | {row['symbol']} | {vol} | {pct} | {tag_str} |" ) lines.append("") lines.append("> 标记说明:千万+ = 成交额≥1000万 USDT;涨跌5%+ = |涨跌幅|≥5%") return "\n".join(lines) async def send_wecom_markdown(content: str) -> tuple[bool, str]: url = settings.wecom_webhook_url.strip() if not url: return False, "WECOM_WEBHOOK_URL 未配置" payload = {"msgtype": "markdown", "markdown": {"content": content}} last_err = "" for attempt in range(3): try: async with httpx.AsyncClient( timeout=15.0, **httpx_client_kwargs("wecom") ) as client: resp = await client.post(url, json=payload) data = resp.json() if data.get("errcode") == 0: return True, "ok" last_err = str(data) except Exception as e: last_err = str(e) logger.warning("WeCom push attempt %d failed: %s", attempt + 1, e) return False, last_err