"""Platform-specific keyboard payloads built from one platform-neutral button spec. Callers describe buttons once; this module renders them for whichever platform the window belongs to. The wire format for a click is always `bg::` — at most 59 bytes, which clears Telegram's 64-byte callback_data limit (the tighter of the two) and QQ's 100. """ from __future__ import annotations import re from typing import Any BUTTON_DATA_RE = re.compile(r"^bg:(?P[a-z][a-z0-9_-]{0,15}):(?Pg1\.[A-Za-z0-9_-]{12}\.[0-9a-f]{24})$") # Telegram is the tighter limit; enforce it everywhere so a spec that works on one platform # works on both. MAX_DATA_BYTES = 64 def encode(action: str, ref: str) -> str: data = f"bg:{action}:{ref}" if len(data.encode("utf-8")) > MAX_DATA_BYTES: raise ValueError(f"按钮数据超长({len(data.encode('utf-8'))} > {MAX_DATA_BYTES})") return data def decode(value: Any) -> tuple[str, str]: match = BUTTON_DATA_RE.fullmatch(str(value or "")) if not match: raise ValueError("无法识别的按钮数据") return match.group("action"), match.group("ref") def build_qq_keyboard( buttons: list[dict[str, Any]], ref: str, *, allowed_user_id: str | None, per_row: int = 2, ) -> dict[str, Any]: """action.type=1 keyboard (native Interaction callbacks). permission.type=2 with specify_user_ids makes QQ itself reject clicks from anyone else, so a forged click never reaches us. click_limit=1 matches the registry's single-use default. """ if not buttons: raise ValueError("按钮列表不能为空") permission: dict[str, Any] = {"type": 2, "specify_role_ids": [], "specify_user_ids": []} if allowed_user_id: permission["specify_user_ids"] = [str(allowed_user_id)] else: permission = {"type": 0} # anyone in the conversation rows: list[dict[str, Any]] = [] for start in range(0, len(buttons), per_row): row_buttons = [] for index, spec in enumerate(buttons[start:start + per_row], start=start): action = str(spec["action"]) row_buttons.append({ "id": f"bg_{index}_{action}", "render_data": { "label": str(spec["label"])[:20], "visited_label": str(spec.get("visited_label") or spec["label"])[:20], "style": int(spec.get("style", 1)), }, "action": { "type": 1, "permission": permission, "click_limit": 1, "data": encode(action, ref), }, }) rows.append({"buttons": row_buttons}) return {"content": {"rows": rows}} def build_qq_c2c_payload(text: str, keyboard: dict[str, Any]) -> dict[str, Any]: """QQ only renders a keyboard alongside markdown; msg_type=0 drops it *silently*.""" text = str(text or "").strip() if not text or len(text) > 4000: raise ValueError("markdown 文本无效") if not keyboard.get("content", {}).get("rows"): raise ValueError("keyboard 内容无效") return {"msg_type": 2, "markdown": {"content": text}, "keyboard": keyboard} def build_telegram_markup(buttons: list[dict[str, Any]], ref: str, *, per_row: int = 2): """Lazily imported so the gateway still loads when python-telegram-bot is absent.""" from telegram import InlineKeyboardButton, InlineKeyboardMarkup # noqa: PLC0415 rows = [] for start in range(0, len(buttons), per_row): rows.append([ InlineKeyboardButton(str(spec["label"])[:30], callback_data=encode(str(spec["action"]), ref)) for spec in buttons[start:start + per_row] ]) return InlineKeyboardMarkup(rows)