Merge 366834d343 into c896c09c42
This commit is contained in:
commit
1bd696c9d7
|
|
@ -145,6 +145,13 @@ def _reply_anchor_for_event(event) -> str | None:
|
|||
platform = _platform_name(getattr(source, "platform", None))
|
||||
thread_id = getattr(source, "thread_id", None)
|
||||
raw_message = getattr(event, "raw_message", None)
|
||||
event_metadata = getattr(event, "metadata", None) or {}
|
||||
if event_metadata.get("_hermes_no_reply_anchor"):
|
||||
# Some synthetic events (for example Feishu bot-menu callbacks) have
|
||||
# a stable event ID for deduplication but no platform message that can
|
||||
# be replied to. Treating that event ID as a reply anchor makes the
|
||||
# outbound API reject the response as an invalid message ID.
|
||||
return None
|
||||
if (
|
||||
platform == "slack"
|
||||
and isinstance(raw_message, dict)
|
||||
|
|
|
|||
|
|
@ -257,6 +257,43 @@ _APPROVAL_LABEL_MAP: Dict[str, str] = {
|
|||
}
|
||||
|
||||
|
||||
_FEISHU_MENU_ACK_TEXT_ZH: Dict[str, str] = {
|
||||
"/new": "已接收:新会话,正在创建…",
|
||||
"/status": "已接收:状态,正在查询…",
|
||||
"/help": "已接收:帮助,正在整理命令…",
|
||||
"/agents": "已接收:任务,正在查询…",
|
||||
"/cron": "已接收:定时任务,正在查询…",
|
||||
"/sessions": "已接收:会话列表,正在查询…",
|
||||
"/memory": "已接收:记忆,正在查询…",
|
||||
"/model": "已接收:模型,正在查询…",
|
||||
}
|
||||
|
||||
_FEISHU_MENU_ACK_TEXT_EN: Dict[str, str] = {
|
||||
"/new": "Received: New session — creating…",
|
||||
"/status": "Received: Status — checking…",
|
||||
"/help": "Received: Help — listing commands…",
|
||||
"/agents": "Received: Tasks — checking…",
|
||||
"/cron": "Received: Scheduled tasks — checking…",
|
||||
"/sessions": "Received: Sessions — checking…",
|
||||
"/memory": "Received: Memory — checking…",
|
||||
"/model": "Received: Model — checking…",
|
||||
}
|
||||
|
||||
|
||||
def _bot_menu_ack_text(event_key: str, *, domain_name: str) -> str:
|
||||
"""Return a localized immediate acknowledgement for a menu click."""
|
||||
normalized = str(event_key or "").strip()
|
||||
if str(domain_name or "").strip().lower() == "lark":
|
||||
return _FEISHU_MENU_ACK_TEXT_EN.get(
|
||||
normalized,
|
||||
f"Received: {normalized or 'menu command'} — processing…",
|
||||
)
|
||||
return _FEISHU_MENU_ACK_TEXT_ZH.get(
|
||||
normalized,
|
||||
f"已接收:{normalized or '菜单命令'},正在处理…",
|
||||
)
|
||||
|
||||
|
||||
async def _read_limited_feishu_webhook_body(request: Any, max_bytes: int) -> bytes:
|
||||
"""Read at most ``max_bytes`` from an aiohttp request body."""
|
||||
try:
|
||||
|
|
@ -1723,6 +1760,7 @@ class FeishuAdapter(BasePlatformAdapter):
|
|||
"vc.bot.meeting_invited_v1",
|
||||
self._on_meeting_invited_event,
|
||||
)
|
||||
.register_p2_application_bot_menu_v6(self._on_bot_menu_event)
|
||||
.build()
|
||||
)
|
||||
|
||||
|
|
@ -2684,6 +2722,92 @@ class FeishuAdapter(BasePlatformAdapter):
|
|||
return
|
||||
self._submit_on_loop(loop, handle_meeting_invited_event(self, data))
|
||||
|
||||
def _on_bot_menu_event(self, data: Any) -> None:
|
||||
"""Handle bot menu clicks as synthetic P2P text messages."""
|
||||
event = getattr(data, "event", None)
|
||||
if event is None:
|
||||
return
|
||||
|
||||
event_key = str(getattr(event, "event_key", "") or "")
|
||||
operator = getattr(event, "operator", None)
|
||||
operator_id = getattr(operator, "operator_id", None)
|
||||
open_id = str(getattr(operator_id, "open_id", "") or "")
|
||||
if not event_key or not open_id:
|
||||
logger.debug("[Feishu] Dropping malformed bot menu event")
|
||||
return
|
||||
|
||||
header = getattr(data, "header", None)
|
||||
event_id = str(getattr(header, "event_id", "") or "")
|
||||
if not event_id:
|
||||
timestamp = str(getattr(event, "timestamp", "") or "")
|
||||
if not timestamp:
|
||||
logger.warning("[Feishu] Bot menu event missing event_id and timestamp, dropping")
|
||||
return
|
||||
event_id = hashlib.sha256(
|
||||
f"{open_id}\0{timestamp}\0{event_key}".encode("utf-8")
|
||||
).hexdigest()
|
||||
dedup_key = f"feishu_bot_menu:{event_id}"
|
||||
|
||||
loop = self._loop
|
||||
if not self._loop_accepts_callbacks(loop):
|
||||
logger.warning("[Feishu] Dropping bot menu event before adapter loop is ready")
|
||||
return
|
||||
|
||||
async def _handle_bot_menu() -> None:
|
||||
if self._is_duplicate(dedup_key):
|
||||
logger.debug("[Feishu] Dropping duplicate bot menu event: %s", event_id)
|
||||
return
|
||||
|
||||
# Model the click as a P2P message from the operator so the normal
|
||||
# Feishu allowlist/pairing admission policy remains authoritative.
|
||||
sender = SimpleNamespace(sender_type="user", sender_id=operator_id)
|
||||
message = SimpleNamespace(chat_type="p2p", chat_id=open_id)
|
||||
reason = self._admit(sender, message)
|
||||
if reason is not None:
|
||||
logger.debug("[Feishu] Dropping bot menu event: %s", reason)
|
||||
return
|
||||
|
||||
sender_profile = await self._resolve_sender_profile(operator_id)
|
||||
user_name = sender_profile["user_name"] or getattr(operator, "operator_name", "") or open_id
|
||||
source = self.build_source(
|
||||
chat_id=open_id,
|
||||
chat_name=user_name,
|
||||
chat_type="dm",
|
||||
user_id=sender_profile["user_id"],
|
||||
user_name=user_name,
|
||||
thread_id=None,
|
||||
user_id_alt=sender_profile["user_id_alt"],
|
||||
)
|
||||
synthetic_event = MessageEvent(
|
||||
text=event_key,
|
||||
message_type=MessageType.TEXT,
|
||||
source=source,
|
||||
raw_message=data,
|
||||
message_id=event_id,
|
||||
metadata={"_hermes_no_reply_anchor": True},
|
||||
channel_prompt=self._resolve_channel_prompt(open_id),
|
||||
timestamp=datetime.now(),
|
||||
)
|
||||
logger.info(
|
||||
"[Feishu] Routing bot menu key=%r from user=%s as P2P text",
|
||||
event_key,
|
||||
open_id,
|
||||
)
|
||||
ack_result = await self.send(
|
||||
open_id,
|
||||
_bot_menu_ack_text(event_key, domain_name=self._domain_name),
|
||||
)
|
||||
if not ack_result.success:
|
||||
logger.warning(
|
||||
"[Feishu] Bot menu acknowledgement failed for key=%r user=%s: %s",
|
||||
event_key,
|
||||
open_id,
|
||||
ack_result.error or "unknown error",
|
||||
)
|
||||
await self._handle_message_with_guards(synthetic_event)
|
||||
|
||||
self._submit_on_loop(loop, _handle_bot_menu())
|
||||
|
||||
def _on_reaction_event(self, event_type: str, data: Any) -> None:
|
||||
"""Route user reactions on bot messages as synthetic text events."""
|
||||
event = getattr(data, "event", None)
|
||||
|
|
@ -3656,6 +3780,8 @@ class FeishuAdapter(BasePlatformAdapter):
|
|||
self._on_drive_comment_event(data)
|
||||
elif event_type == "vc.bot.meeting_invited_v1":
|
||||
self._on_meeting_invited_event(data)
|
||||
elif event_type == "application.bot.menu_v6":
|
||||
self._on_bot_menu_event(data)
|
||||
else:
|
||||
logger.debug("[Feishu] Ignoring webhook event type: %s", event_type or "unknown")
|
||||
return web.json_response({"code": 0, "msg": "ok"})
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ from types import SimpleNamespace
|
|||
from typing import Dict
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
from gateway.platforms.base import ProcessingOutcome
|
||||
from gateway.platforms.base import MessageEvent, ProcessingOutcome, _reply_anchor_for_event
|
||||
|
||||
try:
|
||||
import lark_oapi
|
||||
|
|
@ -41,6 +41,7 @@ def _mock_event_dispatcher_builder(mock_handler_class):
|
|||
mock_builder.register_p2_im_message_reaction_created_v1 = Mock(return_value=mock_builder)
|
||||
mock_builder.register_p2_im_message_reaction_deleted_v1 = Mock(return_value=mock_builder)
|
||||
mock_builder.register_p2_card_action_trigger = Mock(return_value=mock_builder)
|
||||
mock_builder.register_p2_application_bot_menu_v6 = Mock(return_value=mock_builder)
|
||||
mock_builder.build = Mock(return_value=object())
|
||||
mock_handler_class.builder = Mock(return_value=mock_builder)
|
||||
return mock_builder
|
||||
|
|
@ -101,6 +102,136 @@ class TestFeishuMessageNormalization(unittest.TestCase):
|
|||
|
||||
|
||||
class TestFeishuAdapterMessaging(unittest.TestCase):
|
||||
def _bot_menu_adapter(self, *, admit_reason=None):
|
||||
from gateway.config import PlatformConfig
|
||||
from plugins.platforms.feishu.adapter import FeishuAdapter
|
||||
|
||||
adapter = FeishuAdapter(PlatformConfig())
|
||||
adapter._loop = object()
|
||||
adapter._admit = Mock(return_value=admit_reason)
|
||||
adapter._is_duplicate = Mock(return_value=False)
|
||||
adapter._resolve_sender_profile = AsyncMock(
|
||||
return_value={
|
||||
"user_id": "ou_user",
|
||||
"user_name": "Menu User",
|
||||
"user_id_alt": None,
|
||||
}
|
||||
)
|
||||
send_mock = AsyncMock()
|
||||
adapter.send = send_mock
|
||||
handle_message_mock = AsyncMock()
|
||||
adapter._handle_message_with_guards = handle_message_mock
|
||||
return adapter, send_mock, handle_message_mock
|
||||
|
||||
@staticmethod
|
||||
def _bot_menu_data(event_id="evt_menu_1", event_key="/status"):
|
||||
return SimpleNamespace(
|
||||
header=SimpleNamespace(event_id=event_id),
|
||||
event=SimpleNamespace(
|
||||
event_key=event_key,
|
||||
timestamp=1785063000,
|
||||
operator=SimpleNamespace(
|
||||
operator_name="Menu User",
|
||||
operator_id=SimpleNamespace(
|
||||
open_id="ou_user",
|
||||
user_id=None,
|
||||
union_id=None,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _dispatch_bot_menu(adapter, data):
|
||||
def run_submitted(_loop, coroutine):
|
||||
asyncio.run(coroutine)
|
||||
|
||||
with (
|
||||
patch.object(adapter, "_loop_accepts_callbacks", return_value=True),
|
||||
patch.object(adapter, "_submit_on_loop", side_effect=run_submitted),
|
||||
):
|
||||
adapter._on_bot_menu_event(data)
|
||||
|
||||
def test_bot_menu_event_routes_event_key_to_operator_p2p(self):
|
||||
from gateway.platforms.base import MessageType
|
||||
|
||||
adapter, send_mock, handle_message_mock = self._bot_menu_adapter()
|
||||
self._dispatch_bot_menu(adapter, self._bot_menu_data())
|
||||
|
||||
event = handle_message_mock.await_args.args[0]
|
||||
self.assertEqual(event.text, "/status")
|
||||
self.assertEqual(event.message_type, MessageType.TEXT)
|
||||
self.assertEqual(event.message_id, "evt_menu_1")
|
||||
self.assertTrue(event.metadata["_hermes_no_reply_anchor"])
|
||||
self.assertEqual(event.source.chat_id, "ou_user")
|
||||
self.assertEqual(event.source.chat_type, "dm")
|
||||
self.assertEqual(event.source.user_id, "ou_user")
|
||||
self.assertIsNone(_reply_anchor_for_event(event))
|
||||
send_mock.assert_awaited_once_with(
|
||||
"ou_user",
|
||||
"已接收:状态,正在查询…",
|
||||
)
|
||||
handle_message_mock.assert_awaited_once_with(event)
|
||||
adapter._admit.assert_called_once()
|
||||
|
||||
def test_bot_menu_event_rejected_by_dm_admission_is_dropped(self):
|
||||
adapter, send_mock, handle_message_mock = self._bot_menu_adapter(admit_reason="dm_policy_rejected")
|
||||
self._dispatch_bot_menu(adapter, self._bot_menu_data())
|
||||
|
||||
send_mock.assert_not_awaited()
|
||||
handle_message_mock.assert_not_awaited()
|
||||
adapter._resolve_sender_profile.assert_not_awaited()
|
||||
|
||||
def test_bot_menu_event_dispatches_even_if_acknowledgement_fails(self):
|
||||
from gateway.platforms.base import SendResult
|
||||
|
||||
adapter, send_mock, handle_message_mock = self._bot_menu_adapter()
|
||||
send_mock.return_value = SendResult(success=False, error="send failed")
|
||||
self._dispatch_bot_menu(adapter, self._bot_menu_data())
|
||||
|
||||
send_mock.assert_awaited_once_with(
|
||||
"ou_user",
|
||||
"已接收:状态,正在查询…",
|
||||
)
|
||||
handle_message_mock.assert_awaited_once()
|
||||
|
||||
def test_lark_bot_menu_acknowledgement_uses_english(self):
|
||||
adapter, send_mock, _handle_message_mock = self._bot_menu_adapter()
|
||||
adapter._domain_name = "lark"
|
||||
|
||||
self._dispatch_bot_menu(adapter, self._bot_menu_data())
|
||||
|
||||
send_mock.assert_awaited_once_with(
|
||||
"ou_user",
|
||||
"Received: Status — checking…",
|
||||
)
|
||||
|
||||
def test_duplicate_bot_menu_event_is_dropped(self):
|
||||
adapter, send_mock, handle_message_mock = self._bot_menu_adapter()
|
||||
adapter._is_duplicate.side_effect = [False, True]
|
||||
data = self._bot_menu_data()
|
||||
|
||||
self._dispatch_bot_menu(adapter, data)
|
||||
self._dispatch_bot_menu(adapter, data)
|
||||
|
||||
self.assertEqual(send_mock.await_count, 1)
|
||||
self.assertEqual(handle_message_mock.await_count, 1)
|
||||
adapter._is_duplicate.assert_called_with("feishu_bot_menu:evt_menu_1")
|
||||
|
||||
def test_distinct_bot_menu_event_ids_are_both_dispatched(self):
|
||||
adapter, send_mock, handle_message_mock = self._bot_menu_adapter()
|
||||
|
||||
self._dispatch_bot_menu(adapter, self._bot_menu_data(event_id="evt_menu_1"))
|
||||
self._dispatch_bot_menu(adapter, self._bot_menu_data(event_id="evt_menu_2"))
|
||||
|
||||
self.assertEqual(send_mock.await_count, 2)
|
||||
self.assertEqual(handle_message_mock.await_count, 2)
|
||||
message_ids = [
|
||||
call.args[0].message_id
|
||||
for call in handle_message_mock.await_args_list
|
||||
]
|
||||
self.assertEqual(message_ids, ["evt_menu_1", "evt_menu_2"])
|
||||
|
||||
@unittest.skipUnless(_HAS_LARK_OAPI, "lark-oapi not installed")
|
||||
def test_websocket_sdk_accepts_channel_ua_tag(self):
|
||||
"""The shipped SDK must support the Channel signaling argument.
|
||||
|
|
@ -417,6 +548,10 @@ class TestAdapterBehavior(unittest.TestCase):
|
|||
calls.append(f"customized:{event_key}")
|
||||
return self
|
||||
|
||||
def register_p2_application_bot_menu_v6(self, _handler):
|
||||
calls.append("bot_menu")
|
||||
return self
|
||||
|
||||
def build(self):
|
||||
calls.append("build")
|
||||
return "handler"
|
||||
|
|
@ -446,6 +581,7 @@ class TestAdapterBehavior(unittest.TestCase):
|
|||
"message_recalled",
|
||||
"customized:drive.notice.comment_add_v1",
|
||||
"customized:vc.bot.meeting_invited_v1",
|
||||
"bot_menu",
|
||||
"build",
|
||||
],
|
||||
)
|
||||
|
|
@ -876,6 +1012,42 @@ class TestAdapterBehavior(unittest.TestCase):
|
|||
self.assertEqual(response.status, 200)
|
||||
adapter._on_message_event.assert_called_once()
|
||||
|
||||
@patch.dict(os.environ, {}, clear=True)
|
||||
def test_webhook_request_dispatches_bot_menu_event(self):
|
||||
from gateway.config import PlatformConfig
|
||||
from plugins.platforms.feishu.adapter import FeishuAdapter
|
||||
|
||||
adapter = FeishuAdapter(PlatformConfig())
|
||||
adapter._on_bot_menu_event = Mock()
|
||||
|
||||
body = json.dumps({
|
||||
"header": {
|
||||
"event_type": "application.bot.menu_v6",
|
||||
"event_id": "evt_menu_webhook",
|
||||
},
|
||||
"event": {
|
||||
"event_key": "/status",
|
||||
"operator": {
|
||||
"operator_id": {"open_id": "ou_user"},
|
||||
},
|
||||
},
|
||||
}).encode("utf-8")
|
||||
request = SimpleNamespace(
|
||||
remote="127.0.0.1",
|
||||
content_length=None,
|
||||
headers={},
|
||||
content=_FakeRequestContent(body),
|
||||
)
|
||||
|
||||
response = asyncio.run(adapter._handle_webhook_request(request))
|
||||
|
||||
self.assertEqual(response.status, 200)
|
||||
adapter._on_bot_menu_event.assert_called_once()
|
||||
data = adapter._on_bot_menu_event.call_args.args[0]
|
||||
self.assertEqual(data.header.event_id, "evt_menu_webhook")
|
||||
self.assertEqual(data.event.event_key, "/status")
|
||||
self.assertEqual(data.event.operator.operator_id.open_id, "ou_user")
|
||||
|
||||
@patch.dict(os.environ, {"FEISHU_VERIFICATION_TOKEN": "expected-token"}, clear=True)
|
||||
def test_url_verification_requires_configured_verification_token(self):
|
||||
"""url_verification must be rejected when token is set but mismatched.
|
||||
|
|
|
|||
|
|
@ -85,6 +85,23 @@ In **Events and Callbacks**:
|
|||
2. In the **Event Configuration** section, subscribe to:
|
||||
- `im.message.receive_v1` — required for receiving messages
|
||||
|
||||
### Bot Custom Menu Commands
|
||||
|
||||
Hermes can turn a Feishu/Lark bot custom-menu click into a normal inbound text message. This is useful for exposing slash commands such as `/status`, `/help`, or `/new` without requiring users to type them.
|
||||
|
||||
1. In the developer console, enable the bot's **Custom Menu** capability.
|
||||
2. Add a menu item that uses **Push Event** as its action.
|
||||
3. Set the menu item's event key to the exact text Hermes should receive, for example `/status`.
|
||||
4. In **Events and Callbacks**, subscribe to `application.bot.menu_v6` (**Bot Custom Menu Event**).
|
||||
5. No special home-chat configuration is required. Hermes routes the click to the clicking user's P2P session using the operator's Open ID.
|
||||
6. Publish a new app version after saving the menu and event subscription.
|
||||
|
||||
When a user clicks the item, Hermes resolves the clicking user's identity, immediately sends a short acknowledgement (for example, `Received: Status — checking...`), and then processes the event key through the same direct-message admission and message-handling path as a text message. User allowlists and pairing therefore still apply, and the final result returns to the clicking user's P2P chat. Feishu event IDs are used for deduplication so a retried delivery does not send a second acknowledgement or execute the command twice. If the acknowledgement cannot be delivered, Hermes logs the delivery error and still attempts the requested command.
|
||||
|
||||
:::tip
|
||||
Use slash-command strings as event keys when you want deterministic command behavior. Other text is also accepted and is handled as though the user sent that text in a direct message.
|
||||
:::
|
||||
|
||||
### Publish the App
|
||||
|
||||
After configuring permissions and events, go to **Version Management** and publish a new version of the app. The permissions won't take effect until a version is published and approved (for enterprise apps, this may require admin approval).
|
||||
|
|
|
|||
|
|
@ -55,6 +55,27 @@ hermes gateway setup
|
|||
请妥善保管 App Secret。任何持有它的人都可以冒充你的应用。
|
||||
:::
|
||||
|
||||
### 配置权限与事件
|
||||
|
||||
在飞书开发者后台的 **权限管理** 中,至少开通接收消息、以机器人身份发送消息、读取资源和读取会话信息所需权限。然后在 **事件与回调** 中选择 **长连接(WebSocket)**(推荐)或配置 webhook,并订阅 `im.message.receive_v1`。
|
||||
|
||||
### 机器人自定义菜单命令
|
||||
|
||||
Hermes 可以把飞书/Lark 机器人自定义菜单的点击事件转换为普通入站文本消息。这适合把 `/status`、`/help` 或 `/new` 等命令放进菜单,用户无需手动输入。
|
||||
|
||||
1. 在开发者后台启用机器人的 **自定义菜单** 能力。
|
||||
2. 新建菜单项,动作类型选择 **推送事件**。
|
||||
3. 将菜单项的事件 key 设置为 Hermes 应收到的完整文本,例如 `/status`。
|
||||
4. 在 **事件与回调** 中订阅 `application.bot.menu_v6`(机器人自定义菜单事件)。
|
||||
5. 无需额外配置 home chat。Hermes 会使用点击者的 Open ID,将事件路由到该用户自己的 P2P 会话。
|
||||
6. 保存菜单与事件订阅后,创建并发布新的应用版本。
|
||||
|
||||
用户点击菜单后,Hermes 会解析点击者身份,立即发送一条简短确认(例如“已接收:状态,正在查询…”),然后通过与普通私信相同的准入和处理链路处理事件 key。因此用户白名单和配对机制仍然生效,最终结果也会返回点击者自己的 P2P 聊天。Hermes 使用飞书 event ID 去重,飞书重试投递时不会重复确认或执行命令。如果即时确认发送失败,Hermes 会记录发送错误,但仍继续尝试执行用户请求。
|
||||
|
||||
:::tip
|
||||
需要确定性命令行为时,建议直接使用 slash command 字符串作为事件 key。也可以填写普通文本,Hermes 会像用户在私信中发送该文本一样处理。
|
||||
:::
|
||||
|
||||
## 第二步:选择连接模式
|
||||
|
||||
### 推荐:WebSocket 模式
|
||||
|
|
|
|||
Loading…
Reference in New Issue