keyboards.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. """QQ Bot inline keyboards + approval / update-prompt helpers. A button click dispatches an
  2. ``INTERACTION_CREATE`` event carrying the button's ``data``; the bot must ACK promptly via
  3. ``PUT /interactions/{id}`` or the user sees an error indicator. ``button_data`` formats:
  4. ``approve:<session_key>:<decision>`` (allow-once|allow-always|deny) and ``update_prompt:<answer>`` (y|n).
  5. Ported from WideLee's qqbot-agent-sdk v1.2.2 (authorship via Co-authored-by)."""
  6. from __future__ import annotations
  7. import re
  8. from dataclasses import dataclass, field, fields, is_dataclass
  9. from typing import Any, Dict, List, Optional
  10. APPROVAL_BUTTON_PREFIX = "approve:"
  11. UPDATE_PROMPT_PREFIX = "update_prompt:"
  12. # session_key may itself contain colons (agent:main:qqbot:c2c:OPENID): greedy group, decision trails.
  13. _APPROVAL_DATA_RE = re.compile(r"^approve:(.+):(allow-once|allow-always|deny)$")
  14. _UPDATE_PROMPT_RE = re.compile(r"^update_prompt:(y|n)$")
  15. def _to_dict(value: Any) -> Any:
  16. """Serialize a dataclass tree in field-declaration order (the wire shape)."""
  17. if is_dataclass(value):
  18. return {f.name: _to_dict(getattr(value, f.name)) for f in fields(value)}
  19. return [_to_dict(v) for v in value] if isinstance(value, list) else value
  20. class _Serializable:
  21. to_dict = _to_dict
  22. @dataclass
  23. class KeyboardButtonPermission(_Serializable):
  24. """Button permission metadata. ``type=2`` means all users can click."""
  25. type: int = 2
  26. @dataclass
  27. class KeyboardButtonAction(_Serializable):
  28. """Click behaviour: ``type`` 1 = Callback (INTERACTION_CREATE with ``data``), 2 = Link;
  29. ``click_limit=1`` = single-use."""
  30. type: int
  31. data: str
  32. permission: KeyboardButtonPermission = field(default_factory=KeyboardButtonPermission)
  33. click_limit: int = 1
  34. @dataclass
  35. class KeyboardButtonRenderData(_Serializable):
  36. """Visual rendering: pre/post-click labels; ``style`` 0 = grey, 1 = blue."""
  37. label: str
  38. visited_label: str
  39. style: int = 1
  40. @dataclass
  41. class KeyboardButton(_Serializable):
  42. """One button; buttons sharing a ``group_id`` are mutually exclusive."""
  43. id: str
  44. render_data: KeyboardButtonRenderData
  45. action: KeyboardButtonAction
  46. group_id: str = "default"
  47. @dataclass
  48. class KeyboardRow(_Serializable):
  49. buttons: list[KeyboardButton] = field(default_factory=list)
  50. @dataclass
  51. class KeyboardContent(_Serializable):
  52. rows: list[KeyboardRow] = field(default_factory=list)
  53. @dataclass
  54. class InlineKeyboard(_Serializable):
  55. """Top-level keyboard payload — goes into ``MessageToCreate.keyboard``."""
  56. content: KeyboardContent = field(default_factory=KeyboardContent)
  57. def parse_approval_button_data(button_data: str) -> Optional[tuple[str, str]]:
  58. """Parse approval ``button_data`` into ``(session_key, decision)`` or ``None``."""
  59. return m.groups() if (m := _APPROVAL_DATA_RE.match(button_data or "")) else None
  60. def parse_update_prompt_button_data(button_data: str) -> Optional[str]:
  61. """Parse update-prompt ``button_data`` into ``'y'`` / ``'n'`` or ``None``."""
  62. return m.group(1) if (m := _UPDATE_PROMPT_RE.match(button_data or "")) else None
  63. def _single_row_keyboard(group_id: str, *buttons: tuple) -> InlineKeyboard:
  64. """One row of callback buttons from ``(id, label, visited_label, data, style)`` tuples."""
  65. row = KeyboardRow(buttons=[
  66. KeyboardButton(id=btn_id, group_id=group_id, action=KeyboardButtonAction(type=1, data=data),
  67. render_data=KeyboardButtonRenderData(label=label, visited_label=visited, style=style))
  68. for btn_id, label, visited, data, style in buttons])
  69. return InlineKeyboard(content=KeyboardContent(rows=[row]))
  70. def build_approval_keyboard(session_key: str, *, allow_permanent: bool = True) -> InlineKeyboard:
  71. """Build ``[✅ 允许一次] [⭐ 始终允许] [❌ 拒绝]`` (one group, so a click greys the rest). ⭐ is hidden when
  72. persistent scope is unavailable; *session_key* rides in ``button_data`` so the decision routes correctly."""
  73. prefix = f"{APPROVAL_BUTTON_PREFIX}{session_key}"
  74. buttons = [("allow", "✅ 允许一次", "已允许", f"{prefix}:allow-once", 1)]
  75. if allow_permanent:
  76. buttons.append(("always", "⭐ 始终允许", "已始终允许", f"{prefix}:allow-always", 1))
  77. buttons.append(("deny", "❌ 拒绝", "已拒绝", f"{prefix}:deny", 0))
  78. return _single_row_keyboard("approval", *buttons)
  79. def build_update_prompt_keyboard() -> InlineKeyboard:
  80. """Build a Yes/No keyboard for update confirmation prompts."""
  81. return _single_row_keyboard("update_prompt", ("yes", "✓ 确认", "已确认", f"{UPDATE_PROMPT_PREFIX}y", 1),
  82. ("no", "✗ 取消", "已取消", f"{UPDATE_PROMPT_PREFIX}n", 0))
  83. @dataclass
  84. class ApprovalRequest:
  85. """Approval-request display data. ``command_preview`` / ``cwd`` are set for exec approvals, ``tool_name``
  86. for plugin approvals; ``severity`` is ``'critical' | 'info' | ''``."""
  87. session_key: str
  88. title: str
  89. description: str = ""
  90. command_preview: str = ""
  91. cwd: str = ""
  92. tool_name: str = ""
  93. severity: str = ""
  94. timeout_sec: int = 120
  95. allow_permanent: bool = True
  96. _SEVERITY_ICONS = {"critical": "🔴", "info": "🔵"}
  97. def build_approval_text(req: ApprovalRequest) -> str:
  98. """Render an :class:`ApprovalRequest` into the message body (markdown)."""
  99. if req.command_preview or req.cwd:
  100. lines = ["🔐 **命令执行审批**", ""]
  101. if req.command_preview:
  102. lines.append(f"```\n{req.command_preview[:300]}\n```")
  103. if req.cwd:
  104. lines.append(f"📁 目录: {req.cwd}")
  105. if req.title and req.title != req.command_preview:
  106. lines.append(f"📋 {req.title}")
  107. if req.description:
  108. lines.append(f"📝 {req.description}")
  109. else:
  110. lines = [f"{_SEVERITY_ICONS.get(req.severity, '🟡')} **审批请求**", "", f"📋 {req.title}"]
  111. if req.description:
  112. lines.append(f"📝 {req.description}")
  113. if req.tool_name:
  114. lines.append(f"🔧 工具: {req.tool_name}")
  115. lines += ["", f"⏱️ 超时: {req.timeout_sec} 秒"]
  116. return "\n".join(lines)
  117. @dataclass
  118. class InteractionEvent:
  119. """Parsed ``INTERACTION_CREATE`` payload (api-v2 event-emit docs)."""
  120. id: str = "" # required for the ``PUT /interactions/{id}`` ACK
  121. type: int = 0 # event type code (11 = message button)
  122. chat_type: int = 0 # 0 = guild, 1 = group, 2 = c2c
  123. scene: str = "" # 'guild' | 'group' | 'c2c'
  124. group_openid: str = ""
  125. group_member_openid: str = ""
  126. user_openid: str = ""
  127. channel_id: str = ""
  128. guild_id: str = ""
  129. button_data: str = ""
  130. button_id: str = ""
  131. resolver_user_id: str = ""
  132. @property
  133. def operator_openid(self) -> str:
  134. """Best available operator openid (group → member; c2c → user)."""
  135. return self.group_member_openid or self.user_openid or self.resolver_user_id
  136. _SCENE_NAMES = {0: "guild", 1: "group", 2: "c2c"}
  137. def parse_interaction_event(raw: dict[str, Any]) -> InteractionEvent:
  138. """Parse a raw ``INTERACTION_CREATE`` dispatch payload (``d``)."""
  139. data_raw = raw.get("data") or {}
  140. resolved, scene_code = data_raw.get("resolved") or {}, int(raw.get("chat_type", 0) or 0)
  141. return InteractionEvent(
  142. id=str(raw.get("id", "")), type=int(data_raw.get("type", 0) or 0), chat_type=scene_code,
  143. scene=_SCENE_NAMES.get(scene_code, ""), group_openid=str(raw.get("group_openid", "")),
  144. group_member_openid=str(raw.get("group_member_openid", "")), user_openid=str(raw.get("user_openid", "")),
  145. channel_id=str(raw.get("channel_id", "")), guild_id=str(raw.get("guild_id", "")),
  146. button_data=str(resolved.get("button_data", "")), button_id=str(resolved.get("button_id", "")),
  147. resolver_user_id=str(resolved.get("user_id", "")))